Created
April 7, 2011 07:51
-
-
Save showell/907252 to your computer and use it in GitHub Desktop.
yet another Game of Life implementation (functional style)
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
require 'pp' | |
HEIGHT = 37 | |
WIDTH = 17 | |
def alive(game_board, x, y) | |
x %= WIDTH | |
y %= HEIGHT | |
coords = "#{x},#{y}" | |
game_board[coords] | |
end | |
def neighbors(game_board, x, y) | |
offsets = [ | |
[-1, -1], | |
[-1, 0], | |
[-1, 1], | |
[0, -1], | |
[0, 1], | |
[1, -1], | |
[1, 0], | |
[1, 1], | |
] | |
sum = 0 | |
offsets.each do |dx, dy| | |
sum += alive(game_board, x+dx, y+dy) ? 1 : 0 | |
end | |
sum | |
end | |
def still_alive(game_board, x, y) | |
n = neighbors(game_board, x, y) | |
if alive(game_board, x, y) | |
(n == 2 || n == 3) | |
else | |
(n == 3) | |
end | |
end | |
def next_gen(game_board) | |
new_board = {} | |
HEIGHT.times do |y| | |
WIDTH.times do |x| | |
coords = "#{x},#{y}" | |
new_board[coords] = still_alive(game_board, x, y) | |
end | |
end | |
new_board | |
end | |
def show(game_board) | |
system('clear') | |
puts 'GAME OF LIFE' | |
HEIGHT.times do |y| | |
line = WIDTH.times.map do |x| | |
alive(game_board, x, y) ? 'X': ' ' | |
end.join('') + '|' | |
puts line | |
end | |
puts '-' * WIDTH | |
end | |
def play | |
game_board = {} | |
107.times do |n| | |
i = n * 5 | |
x = (i / 21) % 21 | |
y = i % 21 | |
coords = "#{x},#{y}" | |
game_board[coords] = true | |
end | |
while true | |
game_board = next_gen(game_board) | |
show(game_board) | |
gets | |
end | |
end | |
play |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment