Last active
May 9, 2016 09:41
-
-
Save mort/f2d2110e48c19a300388021a93e334f6 to your computer and use it in GitHub Desktop.
Conway's Game of Life (WIP)
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' | |
class LifeBoard | |
attr_reader :board, :cells, :h, :w | |
ALIVE = 1 #🐮 | |
DEAD = 0 #💀 | |
def initialize(s = 20) | |
@h = @w = s | |
@board = [] | |
@cells = [] | |
create_board | |
end | |
def create_board | |
(0..@h - 1).each do |y| | |
r = [] | |
(0..@w - 1).each do |x| | |
r << ((rand > 0.5) ? ALIVE : DEAD) | |
@cells << [x, y] | |
end | |
@board << r | |
end | |
end | |
def cell_state(x, y) | |
@board[x][y] | |
end | |
def cell_alive?(x, y) | |
cell_state(x, y) == ALIVE | |
end | |
def cell_dead?(x, y) | |
!cell_alive?(x, y) | |
end | |
def cell_valid?(x, y) | |
cells.include? [x, y] | |
end | |
def cell_neighbours(x, y) | |
return nil unless cell_valid?(x, y) | |
cells.select do |cell| | |
[ | |
[x - 1, y + 1], | |
[x - 1, y], | |
[x - 1, y - 1], | |
[x, y + 1], | |
[x + 1, y + 1], | |
[x + 1, y], | |
[x + 1, y - 1] | |
].include? cell | |
end | |
end | |
def cell_live_neighbour_count(x, y) | |
return nil unless cell_valid?(x, y) | |
cell_neighbours(x, y).count { |c| cell_alive?(*c) } | |
end | |
def cell_next_state(x, y) | |
#pp "Processing #{x}, #{y}" | |
return nil unless cell_valid?(x, y) | |
live_count = cell_live_neighbour_count(x, y) | |
#puts "(#{x},#{y})| #{cell_alive?(x,y)} | anc: #{anc}" | |
next_state = case | |
# Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. | |
# Any live cell with two or three live neighbours lives on to the next generation. | |
when live_count == 3 | |
ALIVE | |
when live_count == 2 && cell_alive?(x, y) | |
ALIVE | |
else | |
# Any live cell with fewer than two live neighbours dies, as if caused by under-population. | |
# Any live cell with more than three live neighbours dies, as if by over-population. | |
DEAD | |
end | |
puts "Current: #{cell_alive?(x,y)} - Live count: #{live_count} - Next: #{next_state}" | |
next_state | |
sleep 1 | |
end | |
def tick | |
next_state = @board | |
@cells.each do |cell| | |
x, y = *cell | |
next_state[x][y] = cell_next_state(x, y) | |
end | |
@board = next_state | |
end | |
def play | |
gen = 1 | |
loop do | |
puts "--- Gen #{gen}" | |
pp tick | |
gen += 1 | |
end | |
end | |
def print_board | |
@board.each do |r| | |
r.each do |c| | |
print c | |
print '|' | |
end | |
print "\n" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment