Class: RubyLife::Grid
- Inherits:
-
Object
- Object
- RubyLife::Grid
- Defined in:
- lib/ruby_life/grid.rb
Instance Attribute Summary collapse
-
#size ⇒ Object
readonly
Returns the value of attribute size.
Instance Method Summary collapse
- #[](x, y) ⇒ Object
- #generate! ⇒ Object
- #get_neighbors_from_index(index) ⇒ Object
-
#initialize(size, state: nil) ⇒ Grid
constructor
A new instance of Grid.
- #state ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(size, state: nil) ⇒ Grid
Returns a new instance of Grid.
5 6 7 8 9 10 11 12 13 14 |
# File 'lib/ruby_life/grid.rb', line 5 def initialize(size, state: nil) @size = size if state raise BadInitialState unless size_matches_state?(@size, state) @storage = state.map { |status| Cell.new(status) } else @storage = number_of_cells(@size).times.map { Cell.new } end end |
Instance Attribute Details
#size ⇒ Object (readonly)
Returns the value of attribute size.
3 4 5 |
# File 'lib/ruby_life/grid.rb', line 3 def size @size end |
Instance Method Details
#[](x, y) ⇒ Object
36 37 38 |
# File 'lib/ruby_life/grid.rb', line 36 def [](x, y) @storage[x + (y * size)] end |
#generate! ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/ruby_life/grid.rb', line 40 def generate! next_generation = {} @storage.each_with_index do |cell, index| neighbors = get_neighbors_from_index(index) living_neighbor_count = neighbors.select(&:alive?).count if cell.alive? && [2, 3].include?(living_neighbor_count) next_generation[index] = :alive elsif cell.alive? && living_neighbor_count == 4 next_generation[index] = :dead elsif cell.dead? && living_neighbor_count == 3 next_generation[index] = :alive else next_generation[index] = :dead end end next_generation.each do |index, status| status == :alive ? @storage[index].live! : @storage[index].die! end end |
#get_neighbors_from_index(index) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/ruby_life/grid.rb', line 16 def get_neighbors_from_index(index) indices_to_retrieve = [] indices_to_retrieve << (index - 1) unless beginning_of_row?(index) indices_to_retrieve << (index + 1) unless end_of_row?(index) unless first_row?(index) indices_to_retrieve << (above(index - 1)) unless beginning_of_row?(index) indices_to_retrieve << (above(index + 1)) unless end_of_row?(index) indices_to_retrieve << (above(index)) end unless last_row?(index) indices_to_retrieve << (below(index) - 1) unless beginning_of_row?(index) indices_to_retrieve << (below(index) + 1) unless end_of_row?(index) indices_to_retrieve << (below(index)) end indices_to_retrieve.map { |i| @storage[i] } end |
#state ⇒ Object
63 64 65 |
# File 'lib/ruby_life/grid.rb', line 63 def state @storage.map(&:status) end |
#to_s ⇒ Object
67 68 69 70 71 72 73 74 75 76 |
# File 'lib/ruby_life/grid.rb', line 67 def to_s grid_string = "" @storage.each_with_index do |cell, index| grid_string += " #{cell}" grid_string += "\n" if end_of_row?(index) end grid_string end |