Skip to content

Instantly share code, notes, and snippets.

@jbgutierrez
Last active October 29, 2015 20:59
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 jbgutierrez/d1848ab850be07cf07c3 to your computer and use it in GitHub Desktop.
Save jbgutierrez/d1848ab850be07cf07c3 to your computer and use it in GitHub Desktop.
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