Skip to content

Instantly share code, notes, and snippets.

@janlindblom janlindblom/cell.rb
Created Sep 1, 2015

Embed
What would you like to do?
A simple implementation of Game of Life in Ruby.
class Cell
attr_accessor :state
def initialize(state=:dead)
@state = state
end
# Set a new state for the cell
def step(newstate)
@state = newstate
end
def self.next_state_based_on(current_state, living_neighbours)
next_state = :dead
case living_neighbours
when 2
next_state = :living if current_state == :living
when 3
next_state = :living
end
next_state
end
end
require 'grid'
class Game
attr_accessor :iteration, :grid
def initialize
@iteration = 0
@grid = Grid.new
end
def start(iterations=200)
while @iteration < iterations
grid.print
grid.step
puts "-" * @grid.width
@iteration += 1
end
end
end
#!/usr/bin/env ruby
$LOAD_PATH.unshift(File.expand_path('..', __FILE__))
require 'game'
game = Game.new
unless ARGV.empty?
game.start ARGV.first.to_i
else
game.start
end
require 'cell'
class Grid
attr_accessor :cells, :width, :height
def initialize(args=nil)
@cells = []
@width = 32
@height = 32
unless args.nil?
@width = args[:width] unless args[:width].nil?
@height = args[:height] unless args[:height].nil?
end
(1..@height).each do |y|
@cells[y-1] = []
(1..@width).each do |x|
@cells[y-1][x-1] = Cell.new [:dead, :living][(rand*2).to_i]
end
end
end
def step
states = []
# Calculate next state for all cells in the grid
(1..@height).each do |y|
states[y-1] = []
(1..@width).each do |x|
current_state = cells[y-1][x-1].state
states[y-1][x-1] = current_state
n = neighbours(x-1, y-1)
n_states = n.map{ |cell| cell.state }
alive = n_states.reject{ |state| state == :dead }
living_neighbours = alive.count
next_state = Cell.next_state_based_on current_state, living_neighbours
states[y-1][x-1] = next_state
end
end
# Apply the new state to each cell in the grid
(1..@height).each do |y|
(1..@width).each do |x|
@cells[y-1][x-1].state = states[y-1][x-1]
end
end
end
def print
puts to_s
end
def to_s
str = ""
@cells.each do |row|
str += row.map{ |cell|
case cell.state
when :living then '*'
when :dead then ' '
end
}.join("") + "\n"
end
str
end
private
def neighbours(x,y)
neighbours = []
(y-1..y+1).each do |y1|
yc = (y1 == @cells.count) ? 0 : y1
(x-1..x+1).each do |x1|
xc = (x1 == @cells[yc].count) ? 0 : x1
neighbours << @cells[yc][xc]
end
end
neighbours
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.