Create a gist now

Instantly share code, notes, and snippets.

@jbgutierrez /life.rb
Last active Oct 29, 2015

What would you like to do?
Conway's Game of Life in Ruby
board = """
........................o...........
......................o.o...........
............oo......oo............oo
...........o...o....oo............oo
oo........o.....o...oo..............
oo........o...o.oo....o.o...........
..........o.....o.......o...........
...........o...o....................
............oo......................
"""
ALIVE = 'o'
DEAD = '.'
class Life
def initialize board
@board = board.scan(%r/^[.o]+$/m).map &:chars
end
def run
puts "\e[H\e[2J"
@board.each { |row| puts row.join }
sleep 1
@board = tick
run
end
def tick
y = -1
@board.map do |row|
x = -1
y += 1
row.map do |_|
x += 1
next_state x, y
end
end
end
def next_state x, y
cell = @board[y][x]
live_count = live_neighbors x, y
alive = cell == ALIVE
if alive
case live_count
when 2..3 then ALIVE
else DEAD
end
else
case live_count
when 3 then ALIVE
else DEAD
end
end
end
def live_neighbors x, y
neighbors(x, y).count { |cell| cell == ALIVE }
end
def neighbors x, y
coords = [[x-1, y-1], [x, y-1], [x+1, y-1],
[x-1, y], [x+1, y],
[x-1, y+1], [x, y+1], [x+1, y+1]]
coords.map { |x,y| @board[y][x] rescue DEAD }
end
end
life = Life.new board
life.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment