Skip to content

Instantly share code, notes, and snippets.

@nwjsmith
Created November 15, 2014 19:11
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/8d789932c241eafc3140 to your computer and use it in GitHub Desktop.
Save nwjsmith/8d789932c241eafc3140 to your computer and use it in GitHub Desktop.
class Cell
CHARACTERS = { :live => 'X', :dead => 'O' }
attr_reader :live
def self.live
new(:live)
end
def self.dead
new(:dead)
end
def initialize(live)
@live = live
end
def print
Kernel.print CHARACTERS[@live]
end
def evolve(neighbours)
living_neighbours = neighbours.count { |neighbour| neighbour.live == :live }
next_cell_lookup = {
:live => [
Cell.new(:dead),
Cell.new(:dead),
Cell.new(:live),
Cell.new(:live),
Cell.new(:dead),
Cell.new(:dead),
Cell.new(:dead),
Cell.new(:dead),
Cell.new(:dead),
],
:dead => [
Cell.new(:dead),
Cell.new(:dead),
Cell.new(:dead),
Cell.new(:live),
Cell.new(:dead),
Cell.new(:dead),
Cell.new(:dead),
Cell.new(:dead),
Cell.new(:dead),
],
}
next_cell_lookup[@live][living_neighbours]
end
end
class Grid
def initialize(rows)
@rows = rows
@height = rows.length
@width = rows.first.length
end
def evolve
Grid.new(
@rows.map do |row|
row.map do |cell|
cell.evolve(neighbours(cell))
end
end
)
end
def puts
Kernel.puts "-" * @width
@rows.each do |row|
row.each do |cell|
cell.print
end
Kernel.puts
end
Kernel.puts "-" * @width
end
def neighbours(cell)
x, y = coordinates(cell)
[
@rows[north(y)][x],
@rows[north(y)][east(x)],
@rows[y][east(x)],
@rows[south(y)][east(x)],
@rows[south(y)][x],
@rows[south(y)][west(x)],
@rows[y][west(x)],
@rows[north(y)][west(x)]
]
end
def coordinates(cell)
@rows.each_with_index do |row, y|
column = row.index(cell)
column and return [column, y]
end
end
private
def north(y)
(y - 1) % @height
end
def south(y)
(y + 1) % @height
end
def east(x)
(x + 1) % @width
end
def west(x)
(x - 1) % @width
end
end
grid = Grid.new(
[
[Cell.dead, Cell.dead, Cell.dead, Cell.dead, Cell.dead],
[Cell.dead, Cell.dead, Cell.live, Cell.dead, Cell.dead],
[Cell.dead, Cell.dead, Cell.live, Cell.dead, Cell.dead],
[Cell.dead, Cell.dead, Cell.live, Cell.dead, Cell.dead],
[Cell.dead, Cell.dead, Cell.dead, Cell.dead, Cell.dead]
]
)
grid.puts
grid.evolve.puts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment