#!/usr/bin/ruby

var w = Number(`tput cols`  || 80)
var h = Number(`tput lines` || 24)
var r = "\033[H"

var rh = ^h
var rw = ^w

var dirs = [[-1,-1], [-1, 0], [-1, 1], [ 0,-1],
            [ 0, 1], [ 1,-1], [ 1, 0], [ 1, 1]]

var universe = h.of { w.of { 1.rand < 0.1 } }

func iterate {
    var new = h.of { w.of(nil) }
    for i=rh, j=rw {
        var neighbor = 0
        for y,x in (dirs.map {|dir| dir »+« [i, j] }) {
            universe[y % h][x % w] && ++neighbor
            neighbor > 3 && break
        }
        new[i][j] = (universe[i][j]
                        ? (neighbor==2 || neighbor==3)
                        : (neighbor==3))
    }
    universe = new
}

STDOUT.autoflush(true)

loop {
    print r
    print universe.map{|row| row.map{|cell| cell ? '#' : ' '}.join }.join("\n")
    iterate()
}
