Class: Rsb::Gol::Universe
- Inherits:
-
Object
- Object
- Rsb::Gol::Universe
- Defined in:
- lib/rsb/gol/universe.rb
Constant Summary collapse
- DEFAULT_ROWS =
50
- DEFAULT_COLUMNS =
50
Instance Attribute Summary collapse
-
#clock ⇒ Object
readonly
Returns the value of attribute clock.
Instance Method Summary collapse
- #evolution ⇒ Object
-
#initialize(options = {}) ⇒ Universe
constructor
A new instance of Universe.
- #populate(population) ⇒ Object
- #seed(coords) ⇒ Object
- #tick! ⇒ Object
- #visualize(alive = 'o', dead = ' ') ⇒ Object
Constructor Details
#initialize(options = {}) ⇒ Universe
Returns a new instance of Universe.
10 11 12 13 14 15 16 17 18 19 |
# File 'lib/rsb/gol/universe.rb', line 10 def initialize( = {}) @grid = if [:grid] [:grid] elsif [:cols] && [:rows] Rsb::Gol::Grid.new([:rows], [:cols]) else Rsb::Gol::Grid.new(DEFAULT_ROWS, DEFAULT_COLUMNS) end @clock = 0 end |
Instance Attribute Details
#clock ⇒ Object (readonly)
Returns the value of attribute clock.
8 9 10 |
# File 'lib/rsb/gol/universe.rb', line 8 def clock @clock end |
Instance Method Details
#evolution ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/rsb/gol/universe.rb', line 21 def evolution deaths = [] births = [] @grid.cell_neighbors do |state, x, y, neighbors| if state == 1 deaths << [x, y] if neighbors.size < 2 || neighbors.size > 3 end if state == 0 births << [x, y] if neighbors.size == 3 end end { deaths: deaths, births: births } end |
#populate(population) ⇒ Object
38 39 40 41 42 43 44 45 |
# File 'lib/rsb/gol/universe.rb', line 38 def populate(population) population[:deaths].each {|(x, y)| @grid.kill(x, y)} population[:births].each {|(x, y)| @grid.spawn(x, y)} { deaths: population[:deaths].size, births: population[:births].size } end |
#seed(coords) ⇒ Object
47 48 49 50 51 |
# File 'lib/rsb/gol/universe.rb', line 47 def seed(coords) coords.each do |x, y| @grid.spawn(x,y) end end |
#tick! ⇒ Object
57 58 59 60 61 62 63 64 65 66 |
# File 'lib/rsb/gol/universe.rb', line 57 def tick! @clock += 1 stats = populate(evolution()) { empty_universe: stats[:deaths] == 0 && stats[:births] == 0, deaths: stats[:deaths], births: stats[:births], clock: clock } end |
#visualize(alive = 'o', dead = ' ') ⇒ Object
53 54 55 |
# File 'lib/rsb/gol/universe.rb', line 53 def visualize(alive = 'o', dead = ' ') @grid.visualize(alive, dead) end |