Created
July 29, 2017 02:52
-
-
Save josephan/459175cf9d3b966df28020afdcb7a5ef to your computer and use it in GitHub Desktop.
Conway's Game Of Life
This file contains 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
class GameOfLife | |
attr_reader :height, :width | |
def initialize | |
@board = { | |
[10,10] => true, | |
[10,11] => true, | |
[10,12] => true, | |
} | |
@height = 40 | |
@width = 100 | |
@generation = 0 | |
end | |
def loop | |
sleep 0.5 | |
@board = next_generation | |
print_board | |
puts "Generation: #{@generation}" | |
@generation += 1 | |
loop | |
end | |
private | |
def next_generation | |
next_board = {} | |
height.times do |y| | |
width.times do |x| | |
alive = @board[[x,y]] | |
neighbour_count = live_neighbours(x, y) | |
if (alive && (neighbour_count == 2 || neighbour_count == 3)) || (!alive && neighbour_count == 3) | |
next_board[[x,y]] = true | |
end | |
end | |
end | |
next_board | |
end | |
def live_neighbours(x, y) | |
[ | |
@board[[x+1,y+1]], | |
@board[[x+1,y]], | |
@board[[x+1,y-1]], | |
@board[[x,y+1]], | |
@board[[x,y-1]], | |
@board[[x-1,y+1]], | |
@board[[x-1,y]], | |
@board[[x-1,y-1]], | |
].compact.count | |
end | |
def print_board | |
system("clear") | |
height.times do |y| | |
width.times do |x| | |
cell = @board.has_key?([x,y]) ? "#" : " " | |
print cell | |
end | |
print "\n" | |
end | |
end | |
end | |
GameOfLife.new.loop | |
# copy and paste into a file | |
# then run in terminal `$ ruby filename.rb` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment