Created
August 8, 2015 22:13
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Author
sfcgeorge
commented
Aug 8, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment