diff options
| -rw-r--r-- | CLI/ruby/lib/game_of_life/universe.rb | 36 |
1 files changed, 33 insertions, 3 deletions
diff --git a/CLI/ruby/lib/game_of_life/universe.rb b/CLI/ruby/lib/game_of_life/universe.rb index ccaf0cd..5b6e29a 100644 --- a/CLI/ruby/lib/game_of_life/universe.rb +++ b/CLI/ruby/lib/game_of_life/universe.rb @@ -6,6 +6,7 @@ module GameOfLife class Universe extend Forwardable delegate :[] => :@current + delegate :[]= => :@current # Initialize the empty initial universe 2D plane (circular arrays) # @param width [Integer] the width of the universe array @@ -17,19 +18,48 @@ module GameOfLife # Representation of the game of life universe # @return [String] representing the current state - # @see ::GameOfLife::Cell#to_s + # @see GameOfLife::Cell#to_s def to_s @current.map(&:join).join("\n") end + # Update the current state of the universe (according to the game of life laws) and + # set the current state to the next future generation + # + # This have computational order O(width*height) + # It loops over all the universe cells and evolves them to the next generation + # @see #neighbors def evolve! @current.each do |row| row.each do |cell| - @future[cell.pos_y][cell.pos_x] = cell.evolve!(@current) - # @future[cell.pos_y][cell.pos_x] = cell.send(:living_neighbors, @current) + @future[cell.y][cell.x] = cell.evolve!(neighbors(cell)) end end @current = @future end + + # Return the array of all the neighboring cells using the circular universe array + # @param universe [Array<GameOfLife::Cell>] the {GameOfLife::Universe#current} state of universe + # @return [Array<GameOfLife::Cell>] of all the immediate neighboring cells + # @example given a cell "C" in a universe of cells "." the immediate neighbors would be "x" as in + # the following different examples + # + # ..... | .xxx. | .xCx. | xCx.. | Cx..x | xx..x | + # .xxx. | .xCx. | .xxx. | xxx.. | xx..x | Cx..x | + # .xCx. | .xxx. | ..... | ..... | ..... | xx..x | + # .xxx. | ..... | ..... | ..... | ..... | ..... | + # ..... | ..... | .xxx. | xxx.. | xx..x | ..... | + # + # @smell AbcSize higher than configuration, but needed to return the neighboring cells array + # rubocop:disable Metrics/AbcSize + private def neighbors(cell) + x, y = cell.x, cell.y # rubocop:disable Style/ParallelAssignment + [ + @current[y - 1][x - 1], @current[y - 1][x], @current[y - 1][x + 1], + @current[y][x - 1], @current[y][x + 1], + @current[y + 1][x - 1], @current[y + 1][x], @current[y + 1][x + 1] + ] + end + # rubocop:enable Metrics/AbcSize end end |
