From 425d47831220643a73e66f580ce72cd56f93e822 Mon Sep 17 00:00:00 2001 From: a14m Date: Wed, 2 Dec 2020 22:53:16 +0100 Subject: Update the Universe implementation Moving neighbors implementation from cells to universe as per the single responsibility principle that the universe should be responsible for it's object states and that the cells are only aware of their neighbors (via the universe) by passing the neighbors sub-universe to each cell --- CLI/ruby/lib/game_of_life/universe.rb | 36 ++++++++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) (limited to 'CLI/ruby') 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] the {GameOfLife::Universe#current} state of universe + # @return [Array] 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 -- cgit v1.2.3