From: Daniel Moore Date: 2009-02-28T12:39:26+09:00 Subject: Re: [QUIZ] Game of Life (#193) > ## Game of Life (#193) It's about time I solve one of my own quizzes! My solutions only goal was to teach me how to user Fibers in 1.9. Fibers are definitely worth puzzling over. Reading about them is fine but you won't really get that "Aha!" moment until you start using them. Quiz summary coming tomorrow. Thanks everyone for your participation this week! #!/usr/bin/ruby1.9 class Cell < Fiber def initialize super do alive = rand(2) == 1 loop do neighbors = Fiber.yield(alive) if(alive) alive = ((2..3) === neighbors) else alive = (3 == neighbors) end Fiber.yield(alive) end end @alive = resume end def step @alive = resume end def set_neighbors(neighbors) resume(neighbors) end def alive? @alive end def to_s alive? ? '0' : '.' end end class Life def initialize(width=5, height=5) @width, @height = width, height @board = Array.new(height) {Array.new(width) {Cell.new}} end def step @board.each_with_index do |row, y| row.each_with_index do |cell, x| cell.set_neighbors(alive_neighbours(y, x)) end end @board.each{|row| row.each{|cell| cell.step }} end # Based on code by Andrea Fazzi def alive_neighbours(y, x) [[-1, -1], [0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0]].inject(0) do |sum, cell| sum += @board[(y + cell[0])%@height][(x + cell[1])%@width].alive? ? 1 : 0 end end def to_s @board.map{|row| row.join('')}.join("\n") end end game = Life.new(30, 30) 250.times do game.step #puts game.counts puts game end -- -Daniel http://strd6.com