Skip to content

Instantly share code, notes, and snippets.

@nwjsmith
Created November 15, 2014 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nwjsmith/2a239ac92ba22b5d68bb to your computer and use it in GitHub Desktop.
Save nwjsmith/2a239ac92ba22b5d68bb to your computer and use it in GitHub Desktop.
class Cell
def self.random
number = Random.rand(100)
if number > 50
live
else
dead
end
end
def self.live
new(true)
end
def self.dead
new(false)
end
def initialize(live)
@live = live
end
def live?
@live
end
def dead?
!live?
end
def evolve(neighbours)
live_count = neighbours.count(&:live?)
if live?
if live_count < 2 || live_count > 3
Cell.dead
else
Cell.live
end
else
if live_count == 3
Cell.live
else
Cell.dead
end
end
end
end
class Grid
def self.random(width, height)
new(
(1..height).map {
(1..width).map { Cell.random }
}
)
end
def initialize(rows)
@rows = rows
@width = rows.first.length
@height = rows.length
end
def evolve
Grid.new(
@rows.map do |row|
row.map do |cell|
cell.evolve(neighbours(cell))
end
end
)
end
def neighbours(cell)
x, y = coordinates(cell)
north = @rows[(y - 1) % @height][(x) % @width]
northeast = @rows[(y - 1) % @height][(x + 1) % @width]
east = @rows[(y) % @height][(x + 1) % @width]
southeast = @rows[(y + 1) % @height][(x + 1) % @width]
south = @rows[(y + 1) % @height][(x) % @width]
southwest = @rows[(y + 1) % @height][(x - 1) % @width]
west = @rows[(y) % @height][(x - 1) % @width]
northwest = @rows[(y - 1) % @height][(x - 1) % @width]
[north, northeast, east, southeast, south, southwest, west, northwest]
end
def coordinates(cell)
@width.times do |x|
@height.times do |y|
return [x, y] if @rows[y][x] == cell
end
end
end
def putsit
puts "-" * @width
@rows.each do |row|
row.each do |cell|
if cell.live?
print "x"
else
print " "
end
end
puts
end
puts "-" * @width
end
end
a = Cell.live
b = Cell.live
grid = Grid.random(40, 35)
while true
grid = grid.evolve
grid.putsit
puts
sleep (1.0 / 24.0)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment