Skip to content

Instantly share code, notes, and snippets.

@lgleasain
Created October 10, 2014 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lgleasain/34d0aa4971db7ef7f447 to your computer and use it in GitHub Desktop.
Save lgleasain/34d0aa4971db7ef7f447 to your computer and use it in GitHub Desktop.
Bad Ass GOL implementation
class Cell
def initialize
become_dead
end
def eigenclass
class << self
self
end
end
def redefine_methods(mod)
%i{state live_count }.each do |m|
eigenclass.send :define_method, m, mod.instance_method(m)
end
end
def arm(number_of_neighbors)
@number_of_neighbors = number_of_neighbors
end
def fire
send @number_of_neighbors.to_s.to_sym
end
def become_alive
redefine_methods LiveCell
end
def become_dead
redefine_methods DeadCell
end
def inspect
"Cell(#{state}}"
end
define_method(:'2'){}
define_method(:'3'){become_alive}
%i{0 1 4 5 6 7 8}.each do |n|
define_method(n){become_dead}
end
end
module LiveCell
def state
:live
end
def live_count
1
end
end
module DeadCell
def state
:dead
end
def live_count
0
end
end
class Board
attr_reader :cells
def initialize
@cells = Hash.new{Cell.new}
end
def neighbors_for(x, y)
([x-1, x, x+1].product([y-1, y, y+1]) - [[x, y]]).map do |c|
@cells[c]
end
end
def live_neighbors_for(x, y)
neighbors_for(x, y).inject(0) do |n, cell|
n + cell.live_count
end
end
def slay(x, y)
@cells[[x, y]] = Cell.new
end
def enliven(x, y)
slay(x, y)
@cells[[x, y]].become_alive
end
def arm
@cells.each do |(x, y), c|
c.arm live_neighbors_for(x, y)
end
end
def fire
@cells.values.each(&:fire)
end
end
# describe 'Cell' do
# describe LiveCell do
# it 'stays alive with 2 or 3 neighbors' do
# [2, 3].each do |n|
# expect(subject.next n).to be_a LiveCell
# end
# end
# it 'dies with 0, 1, 4, 5, 6, 7, or 8 neighbors' do
# [0, 1, 4, 5, 6, 7, 8].each do |n|
# expect(subject.next n).to be_a DeadCell
# end
# end
# end
# describe DeadCell do
# it 'comes to life with 3 neighbors' do
# expect(subject.next 3).to be_a LiveCell
# end
# it 'stays dead with 0, 1, 2, 4, 5, 6, 7, or 8 neighbors' do
# [0, 1, 2, 4, 5, 6, 7, 8].each do |n|
# expect(subject.next n).to be_a DeadCell
# end
# end
# end
# end
# describe Board do
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment