Skip to content

Instantly share code, notes, and snippets.

@pedrocarmona
Last active January 22, 2016 17:00
Show Gist options
  • Save pedrocarmona/16e915a644968990653d to your computer and use it in GitHub Desktop.
Save pedrocarmona/16e915a644968990653d to your computer and use it in GitHub Desktop.
game
require 'drawille'
class Ceil < Struct.new(:x, :y, :state)
def alive?
state == 1
end
end
class World
attr_accessor :x, :y, :ceils
def print
canvas = Drawille::Canvas.new
ceils.each do |cell|
canvas.set(cell.x, cell.y) if cell.alive?
end
puts canvas.frame
end
def fill
0.upto(x) do |i|
0.upto(y) do |j|
set_ceil(Ceil.new(i, j, rand(2)))
end
end
end
def initialize(x, y)
@x = x
@dim = Array.new(x*y)
@y = y
@ceils = []
end
def set_ceil(ceil)
@ceils << ceil
@dim[ceil.x*x + ceil.y] = ceil
end
def ceil(x,y)
return nil if (x<0 || y < 0 || x > @x || y > @y)
@dim[x*@x + y]
end
def neigbors(ceil)
x = ceil.x
y = ceil.y
[
ceil(x-1, y-1),
ceil(x, y-1),
ceil(x+1, y-1),
ceil(x-1, y),
ceil(x+1, y),
ceil(x-1, y+1),
ceil(x, y+1),
ceil(x+1, y+1),
].compact
end
end
def evolute(world)
new_world = World.new(world.x, world.y)
world.ceils.each do |ceil|
new_ceil = evolute_ceil(world, ceil)
new_world.set_ceil(new_ceil)
end
new_world
end
def evolute_ceil(world, ceil)
neigbors = world.neigbors(ceil)
count_alive = neigbors.select(&:alive?).count
state =
case
when count_alive < 2 then 0
when (count_alive == 2 || count_alive == 3) && ceil.alive? then 1
when count_alive > 3 && ceil.alive? then 0
when (count_alive == 3) && !ceil.alive? then 1
end
Ceil.new(ceil.x, ceil.y, state)
end
world = World.new(140, 240)
world.fill
while true
world = evolute(world)
system("clear")
world.print
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment