Class: CellGrid

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

Instance Method Summary collapse

Constructor Details

#initialize(rows, columns) ⇒ CellGrid

Returns a new instance of CellGrid.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/cellgrid.rb', line 5

def initialize (rows, columns)
  @cells = Array.new rows
  for row in 0...rows
    @cells[row] = Array.new columns
    for column in 0...columns
      cell = Cell.new
      @cells[row][column] = cell
      if row > 0
        cell.add_neighbor @cells[row-1][column]
        cell.add_neighbor @cells[row-1][column+1] if column <= columns - 2
      end
      if column > 0
        cell.add_neighbor @cells[row][column-1]
        cell.add_neighbor @cells[row-1][column-1] if row > 0
      end
    end
  end
end

Instance Method Details

#cell_at(row, column) ⇒ Object



24
25
26
# File 'lib/cellgrid.rb', line 24

def cell_at (row, column)
  @cells[row][column]
end

#column_countObject



32
33
34
# File 'lib/cellgrid.rb', line 32

def column_count
  @cells[0].size
end

#each_cellObject



59
60
61
62
63
64
65
# File 'lib/cellgrid.rb', line 59

def each_cell
  @cells.each do |row|
    row.each do |cell|
      yield cell
    end
  end
end

#evolveObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/cellgrid.rb', line 36

def evolve
  each_cell do |cell|
    # kill the lonely
    cell.queued_state = :dead if cell.cell_state == :live && cell.number_of_live_neighbors < 2
    
    # kill the overcrowded
    cell.queued_state = :dead if cell.cell_state == :live && cell.number_of_live_neighbors > 3
    
    # give birth
    cell.queued_state = :live if cell.cell_state == :dead && cell.number_of_live_neighbors == 3
  end
  each_cell do |cell|
    cell.transition_state
  end
end

#kill_allObject



52
53
54
55
56
57
# File 'lib/cellgrid.rb', line 52

def kill_all
  each_cell do |cell|
    cell.cell_state = :dead
    cell.queued_state = nil
  end
end

#row_countObject



28
29
30
# File 'lib/cellgrid.rb', line 28

def row_count
  @cells.size
end