Skip to content

Instantly share code, notes, and snippets.

@suprnova32
Created February 11, 2014 10:07
Show Gist options
  • Select an option

  • Save suprnova32/c95034181715384b61cb to your computer and use it in GitHub Desktop.

Select an option

Save suprnova32/c95034181715384b61cb to your computer and use it in GitHub Desktop.
Ruby implementation of Comway's Game of Life
class Comway
def initialize(size)
@size = size
@grid = (1..@size*@size).map { rand(0..1)==1 ? 1 : nil }
end
def start_simulation
while true do
system 'clear'
@grid = life
(0..@size-1).each do |y|
(0..@size-1).each do |x|
print "#{(@grid[x+(y*@size)] ? 'O' : '.')}"
end
puts
end
sleep 0.1
end
end
def life
(0..@size*@size-1).map do |i|
neighbours(compact_grid(i), i)
end
end
def compact_grid(i)
[
@grid[i-@size-1], @grid[i-@size], @grid[i-@size+1],
@grid[i-1], @grid[i+1],
@grid[i+@size-1], @grid[i+@size], @grid[i+@size+1]
].compact.count
end
def neighbours(n, i)
n == 3 || ( @grid[i] && n == 2 )|| nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment