Class: Rsb::Gol::Universe

Inherits:
Object
  • Object
show all
Defined in:
lib/rsb/gol/universe.rb

Constant Summary collapse

DEFAULT_ROWS =
50
DEFAULT_COLUMNS =
50

Instance Attribute Summary collapse

Instance Method Summary collapse

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(options = {})
  @grid = if options[:grid]
            options[:grid]
          elsif options[:cols] && options[:rows]
            Rsb::Gol::Grid.new(options[:rows], options[:cols])
          else
            Rsb::Gol::Grid.new(DEFAULT_ROWS, DEFAULT_COLUMNS)
          end
  @clock = 0
end

Instance Attribute Details

#clockObject (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

#evolutionObject



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