Class: Vida::Grid

Inherits:
Object
  • Object
show all
Defined in:
lib/vida/grid.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ Grid

Returns a new instance of Grid.



4
5
6
7
8
9
10
11
12
13
# File 'lib/vida/grid.rb', line 4

def initialize(args = {})
  @rows       = args.fetch(:rows, 50)
  @columns    = args.fetch(:columns, 50)
  @elements   = Array.new(rows) do |row|
    Array.new(columns) do |column|
      Vida::Cell.new(x: column, y: row, alive: random_status)
    end
  end
  @generation_number = 0
end

Instance Attribute Details

#columnsObject (readonly)

Returns the value of attribute columns.



2
3
4
# File 'lib/vida/grid.rb', line 2

def columns
  @columns
end

#elementsObject (readonly)

Returns the value of attribute elements.



2
3
4
# File 'lib/vida/grid.rb', line 2

def elements
  @elements
end

#rowsObject (readonly)

Returns the value of attribute rows.



2
3
4
# File 'lib/vida/grid.rb', line 2

def rows
  @rows
end

Instance Method Details

#live_cells_around(cell) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/vida/grid.rb', line 15

def live_cells_around(cell)
  cells = []
  cells << [
    north(cell),
    south(cell),
    west(cell),
    east(cell),
    ul_corner(cell),
    ur_corner(cell),
    dl_corner(cell),
    dr_corner(cell)
  ]
  cells.flatten!.count { |c| !c.nil? && c.alive == true }
end

#update_cellsObject



30
31
32
33
34
35
36
37
# File 'lib/vida/grid.rb', line 30

def update_cells
  elements.each do |column|
    column.each do |element|
      element.update_status(live_cells_around(element))
    end
  end
  @generation_number += 1
end