Permalink
Browse files

Added rule#5 (ageing) into the game

  • Loading branch information...
1 parent e0604e9 commit aac4614b437ee9518b5e1b1ae9cdd1fd7009d81e @arnab committed Feb 14, 2012
Showing with 37 additions and 1 deletion.
  1. +26 −0 features/ageing.feature
  2. +9 −0 lib/game_of_life/cell.rb
  3. +2 −1 lib/game_of_life/rules.rb
@@ -0,0 +1,26 @@
+Feature: Aeging in Game of Life
+ In order to observe aeging of cells
+ As an observer
+ I want to see live cells die after a certian number of generations
+
+ Scenario: A
+ Given that the game is seeded with:
+ """
+ X X
+ X X
+ """
+ When the next tick occurs
+ When the next tick occurs
+ Then the board's state should change to:
+ """
+ X X
+ X X
+ """
+ When the next tick occurs
+ When the next tick occurs
+ When the next tick occurs
+ Then the board's state should change to:
+ """
+ - -
+ - -
+ """
@@ -4,17 +4,22 @@ class Board
class Cell
STATES = [:live, :dead]
attr_accessor :state, :should_live_in_next_generation
+ # Number of generations this has lived through
+ attr_reader :age
# Creates a {Cell}. A cell starts out as dead unless explicitly set alive.
def initialize(initial_state=:dead)
raise ArgumentError, "Unknown state #{initial_state}" unless STATES.include? initial_state
@state = initial_state
+ @age = 0
end
def change_state_if_needed!
if self.should_live_in_next_generation
+ @age += 1
self.state = :live
else
+ @age = 0
self.state = :dead
end
end
@@ -27,6 +32,10 @@ def dead?
! alive?
end
+ def old?
+ @age > 3
+ end
+
def to_s
fields = %w{state should_live_in_next_generation}
important_details = fields.map {|attr| "#{attr}:#{self.send(attr)}"}
@@ -6,11 +6,12 @@ module Rules
# 2. Any live cell with two or three live neighbours lives on to the next generation.
# 3. Any live cell with more than three live neighbours dies, as if by overcrowding.
# 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
+ # 5. Any live cell that is over 3 generations dies
def should_cell_live?(board, cell, x, y)
live_neighbors_count = board.neighbors_of_cell_at(x, y).select { |n| n.alive? }.size
case cell.state
when :live
- (2..3).include? live_neighbors_count
+ ((2..3).include? live_neighbors_count) && (! cell.old?)
when :dead
live_neighbors_count == 3
end

0 comments on commit aac4614

Please sign in to comment.