Диляна обнови решението на 20.12.2011 22:25 (преди около 13 години)
+require 'enumerator'
+
+module GameOfLife
+ class Board
+ include Enumerable
+ attr_accessor :alive_cells
+ attr_reader :expand_cells
+
+ def initialize(*alives)
+ @alive_cells = alives
+ @alive_cells.uniq!
+ @expand_cells = Array.new(Array.new)
+ end
+
+ def each
+ @alive_cells.each do | x,y |
+ yield x, y
+ end
+ end
+
+ def [] (x, y)
+ @alive_cells.any? { |point| point[0] == x and point[1] == y }
+ end
+
+ def count
+ @alive_cells.count
+ end
+
+ def next_generation
+ survives = @alive_cells.select { |cell| [2,3].include? neighbors(cell[0], cell[1]) }
+ prepare_to_born_new_cells
+ next_gen = survives + @expand_cells.select { |cell| neighbors(cell[0], cell[1]) == 3 }
+ Board.new(*next_gen.uniq!)
+ end
+
+ #generate neighbors of the cell
+ def generate_neigbors (x,y)
+ @expand_cells.concat([ [x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1], [x + 1, y + 1],
+ [x - 1, y - 1], [x + 1, y - 1], [x - 1, y + 1]])
+end
+
+ #prepare all new dead cells who can be born
+ def prepare_to_born_new_cells
+ self.each { |x, y| generate_neigbors(x, y) }
+ end
+ #calculate numbers of alive neighbors
+ def neighbors(x, y)
+ [[x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1],
+ [x + 1, y + 1], [x - 1, y - 1], [x + 1, y - 1], [x - 1, y + 1]].inject(0) do
+ |sum, cell| self[cell[0], cell[1]] ? (sum + 1) : sum
+ end
+ end
+ end # of class Board
+end
- Не ти трябва да require-ваш
enumerator
- Идентация... Цялото тяло на класа
Board
трябва да е идентирано с едно ниво навътре. Някои методи са неправилно идентирани.
Разгледай решенията на колегите си. Има интересни неща, които могат да се видят там.