Skip to content

Instantly share code, notes, and snippets.

@johnhaitas
Created December 5, 2011 16:51
Show Gist options
  • Save johnhaitas/1434279 to your computer and use it in GitHub Desktop.
Save johnhaitas/1434279 to your computer and use it in GitHub Desktop.
Conway's Game of Life in Ruby
def neighbors(cell)
neighbors = []
x = cell[0]
y = cell[1]
(x-1..x+1).each do |xx|
(y-1..y+1).each do |yy|
next if xx==x && yy==y
neighbors.push([xx,yy])
end
end
neighbors
end
def step(this_gen)
next_gen = []
dead_neighbors = []
# all live cells
this_gen.each do |cell|
live_neighbors = []
these_neighbors = neighbors(cell)
these_neighbors.each do |this_neighbor|
if (this_gen.include?(this_neighbor))
live_neighbors.push(this_neighbor)
elsif (!dead_neighbors.include?(this_neighbor))
dead_neighbors.push(this_neighbor)
end
end
next_gen.push(cell) if (live_neighbors.count >= 2 && live_neighbors.count <= 3)
end
# all dead neighbors
dead_neighbors.each do |cell|
live_neighbors = []
these_neighbors = neighbors(cell)
these_neighbors.each do |this_neighbor|
live_neighbors.push(this_neighbor) if (this_gen.include?(this_neighbor))
end
next_gen.push(cell) if (live_neighbors.count == 3)
end
next_gen
end
def display(board,size=40)
(1..size).each do |row|
str = ""
(1..size).each do |col|
if (board.include?([row,col]))
str += "O"
else
str += " "
end
end
puts str
end
end
def game_of_life(start_gen,generations)
this_gen = start_gen
while(generations>0)
display(this_gen)
next_gen = step(this_gen)
generations -= 1
this_gen = next_gen
sleep 0.1
end
end
start_gen = [[2,1],[3,2],[1,3],[2,3],[3,3]]
game_of_life(start_gen,150)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment