Skip to content

Instantly share code, notes, and snippets.

@qoobaa
Created August 8, 2008 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qoobaa/4586 to your computer and use it in GitHub Desktop.
Save qoobaa/4586 to your computer and use it in GitHub Desktop.
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