Class: GameOfLife::Core
- Inherits:
-
Object
- Object
- GameOfLife::Core
- Defined in:
- lib/gameoflife/core.rb
Constant Summary collapse
- LIVE =
1
- DEAD =
nil
Instance Attribute Summary collapse
-
#world ⇒ Object
readonly
Returns the value of attribute world.
Instance Method Summary collapse
-
#initialize(array) ⇒ Core
constructor
A new instance of Core.
- #neighbor_count(x, y) ⇒ Object
- #next_state(x, y) ⇒ Object
- #next_world ⇒ Object
Constructor Details
#initialize(array) ⇒ Core
Returns a new instance of Core.
6 7 8 9 10 11 12 13 14 15 16 |
# File 'lib/gameoflife/core.rb', line 6 def initialize array @world = {} array.each_with_index do |row, row_index| row.each_with_index do |e, col_index| @world[[row_index, col_index]] = e end end @world.reject!{|k, v|v.nil? || v == 0} @static_world = @world.clone end |
Instance Attribute Details
#world ⇒ Object (readonly)
Returns the value of attribute world.
5 6 7 |
# File 'lib/gameoflife/core.rb', line 5 def world @world end |
Instance Method Details
#neighbor_count(x, y) ⇒ Object
18 19 20 21 22 23 24 25 26 27 |
# File 'lib/gameoflife/core.rb', line 18 def neighbor_count x, y count_map = {} (-1..1).each do |i| (-1..1).each do |j| count_map[[x+i,y+j]] = @static_world[[x+i,y+j]] end end count_map.reject! {|k, v| v.nil?} count_map.count - count_map[[x,y]].to_i end |
#next_state(x, y) ⇒ Object
47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/gameoflife/core.rb', line 47 def next_state x, y conditions = { 1 => DEAD, 2 => @static_world[[x,y]], 3 => LIVE, 4 => DEAD, 5 => DEAD, 6 => DEAD, 7 => DEAD, 8 => DEAD }[neighbor_count x, y] end |
#next_world ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/gameoflife/core.rb', line 29 def next_world visited_pos = {} @static_world.each do |k, v| x,y = k[0], k[1] (-1..1).each do |i| (-1..1).each do |j| if not visited_pos[[x+i,y+j]] @world[[x+i,y+j]] = next_state(x+i, y+j) visited_pos[[x+i,y+j]] = true end end end end @world.reject!{|k, v|v.nil?} @static_world = @world.clone end |