public
Created

My current best try at a twitter-length implementation of Conway's Game of Life for #roguesgolf

  • Download Gist
conway-twitter.rb
Ruby
1 2 3 4
n=(0..3);g=[!1]*4;b=[g,g,[!1]+[1]*3,g]
4.times{b=n.map{|x|n.map{|y|l=[x-1,x+1,x].product([y-1,y+1,y])[0..7].select{|f,g|(r=b[f])&&r[g]}.size
l==3||b[x][y]&&l==2}}
b.map{|r|puts r.map{|c|c ??#:?.}*""}}
conway.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
# my original implementation before golfing
class Board
def initialize size, alives=[]
@size = size
@board = (0..size-1).map do |x|
(0..size-1).map do |y|
Cell.new(x, y, alives.include?([x, y]) ? :alive : :dead, self)
end
end
end
 
def [](x, y)
row = @board[x]
row and row[y]
end
 
def neighbor_positions(x, y)
[x -1, x, x + 1].map do |x_prime|
[y - 1, y, y + 1].map do |y_prime|
next if x == x_prime and y == y_prime
[x_prime, y_prime]
end
end.flatten(1).compact
end
 
def neighbors(x, y)
neighbor_positions(x, y).map {|(x, y)| self[x, y] }.compact
end
 
def display
@board.each do |row|
row.each do |cell|
print cell.alive? ? "* " : ". "
end
puts
end
puts
 
self
end
 
def run!
@board = next_board
end
 
def next_board
@board.map do |row|
row.map do |cell|
cell.run
end
end
end
 
def simulate(rounds)
rounds.times do
run!
display
end
end
end
 
class Cell
attr_accessor :state
attr_reader :x, :y
 
def initialize(x, y, state, board)
@x, @y, @state, @board = x, y, state, board
end
 
def to_s
"(#{x}, #{y}):#{state}"
end
 
def alive?
@state == :alive
end
 
def neighbors
@board.neighbors(x, y)
end
 
def live_neighbors
neighbors.select(&:alive?).size
end
 
def next_state
if (state == :dead)
live_neighbors == 3 ? :alive : :dead
else
[2,3].include?(live_neighbors) ? :alive : :dead
end
end
 
def run
self.class.new @x, @y, next_state, @board
end
end
 
board = Board.new(6, [[1, 1], [1, 2], [2, 1], [3, 4], [4, 3], [4, 4]])
board.display
board.simulate(5)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.