Created
August 8, 2008 17:03
-
-
Save qoobaa/4586 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class GameOfLife | |
def initialize(alive = [2, 3], born = [3]) | |
@generation = {} | |
@generations = 0 | |
@alive = alive | |
@born = born | |
end | |
def add_neighbour(pos) | |
if cell = @generation[pos] | |
cell[:neighbours] = (cell[:neighbours] or 0) + 1 | |
else | |
@generation[pos] = { :alive => false, :neighbours => 1 } | |
end | |
end | |
def next_gen | |
@generations += 1 | |
@generation.dup.each_key do |pos| | |
[[-1, -1], [0, -1], [1, -1], | |
[-1, 0], [1, 0], | |
[-1, 1], [0, 1], [1, 1]].each do |d| | |
add_neighbour([pos[0] + d[0], pos[1] + d[1]]) | |
end | |
end | |
@generation.delete_if do |pos, cell| | |
cell[:alive] = false unless @alive.include?(cell[:neighbours]) | |
cell[:alive] = true if @born.include?(cell[:neighbours]) | |
cell[:neighbours] = 0 | |
not cell[:alive] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment