Skip to content

Instantly share code, notes, and snippets.

@sfcgeorge
Created August 8, 2015 22:13
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 sfcgeorge/e35043c37303adc070fe to your computer and use it in GitHub Desktop.
Save sfcgeorge/e35043c37303adc070fe to your computer and use it in GitHub Desktop.
Conway's Game of Life in Ruby, aiming to be short but readable
class String
def reverse_color; "\033[7m#{self}\033[27m" end
end
class Cell
attr_accessor :alive
def initialize(neighbors)
@neighbors = neighbors
@alive = @fate = [false, true].sample
end
def breathe
living = @neighbors.call.count(&:alive)
@fate = false if living < 2 || living > 3
@fate = true if living == 3
end
def existential
@alive = @fate
end
end
class World
def initialize(size, speed, output = PutsGrid)
@size, @speed, @output = size, speed, output
generate
end
def live
loop do
tick
sleep @speed
end
end
def tick
@output.out @grid.each { |y| y.each(&:breathe) }
end
def generate
@grid = @size.times.map do |y|
@size.times.map do |x|
Cell.new(lambda do
[-1, 1, 0].flat_map do |yp|
[-1, 1, 0].map do |xp|
@grid[(y + yp) % @size][(x + xp) % @size]
end
end[0...-1]
end)
end
end
end
end
class PutsGrid
def self.out(grid)
puts "\e[H\e[2J" # clear screen
grid.each do |y|
puts y.map{ |cell| cell.existential ? " ".reverse_color : " " }.join("")
end
end
end
size, speed = (ARGV[0] || 30).to_i, (ARGV[1] || 0.1).to_f
World.new(size, speed).live
@sfcgeorge
Copy link
Author

game_of_life

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment