Skip to content

Instantly share code, notes, and snippets.

@aashish
Last active August 29, 2015 14:21
Show Gist options
  • Save aashish/35fdc4a149dbb03fbe0b to your computer and use it in GitHub Desktop.
Save aashish/35fdc4a149dbb03fbe0b to your computer and use it in GitHub Desktop.
The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway. The "game" is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with the Game of Life by creating an initial configuration and observing how it ev…
class GameOfLife
def initialize(name, size, generations, initial_life=nil)
@size = size
@board = new_board
populate_board(initial_life)
print_board(name, 0)
reason = generations.times do |gen|
prev_board = @board
@board = evolve
print_board(name, gen+1)
break :static if prev_board == @board
end
if reason == :static then puts "no movement"
else puts "specified lifetime ended"
end
end
def new_board
Array.new(@size) {Array.new(@size, 0)}
end
def populate_board(points=nil)
if points.nil?
@size.times { |x| @size.times { |y| @board[rand(@size)][rand(@size)] = 1 } }
else
points.each do |x,y|
@board[y][x] = 1
end
end
end
def evolve
new = new_board
@size.times { |x| @size.times { |y| new[x][y] = fate(x, y) }}
new
end
def fate(i, j)
i1 = [0, i-1].max; i2 = [i+1, @size-1].min
j1 = [0, j-1].max; j2 = [j+1, @size-1].min
sum = 0
for x in i1..i2
for y in j1..j2
sum += @board[x][y] if !(x == i and y == j)
end
end
(sum == 3 or (sum == 2 and @board[i][j] == 1)) ? 1 : 0
end
def print_board(name, generation)
puts "#{name}: generation #{generation}"
@board.each {|row| row.each {|val| print "#{val == 1 ? '#' : '.'} "}; puts}
end
end
GameOfLife.new "blinker", 3, 2, [[1,0],[1,1],[1,2]]
GameOfLife.new "glider", 4, 4, [[1,0],[2,1],[0,2],[1,2],[2,2]]
GameOfLife.new "random", 5, 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment