Version 1 of Game of Life

Updated 2009-04-09 20:29:22 by glennj

Here's another implementation (text-only) of Conway's Game of Life:

 package require Tcl 8.5 

 proc main {} {
     evolve 3 blinker [initialize_tableau {3 3} {{0 1} {1 1} {2 1}}]
     evolve 5 glider  [initialize_tableau {5 5} {{0 1} {1 2} {2 0} {2 1} {2 2}}]
 }

 proc evolve {generations name tableau} {
     for {set gen 1} {$gen <= $generations} {incr gen} {
         puts "$name generation $gen:"
         print $tableau
         set tableau [next_generation $tableau]
     }
     puts ""
 }

 proc initialize_tableau {size initial_life} {
     lassign $size ::max_x ::max_y 
     set tableau [blank_tableau]
     foreach pair $initial_life {
         lassign $pair x y
         lset tableau $x $y 1
     }
     return $tableau
 }

 proc blank_tableau {} {
     return [lrepeat $::max_x [lrepeat $::max_y 0]]
 }

 proc print {tableau} {
     foreach row $tableau {puts [string map {0 . 1 #} [join $row]]}
 }

 proc next_generation {tableau} {
     set new [blank_tableau]
     for {set x 0} {$x < $::max_x} {incr x} {
         for {set y 0} {$y < $::max_y} {incr y} {
             lset new $x $y [fate $x $y $tableau]
         }
     }
     return $new
 }

 proc fate {x y tableau} {
     set C [lindex $tableau $x $y]
     set N [sum_neighbours $x $y $tableau]
     return [expr {($N == 3) || ($N == 2 && $C == 1)}]
 }

 proc sum_neighbours {x y tableau} {
     set sum 0
     foreach {i j} [get_neighbour_indices $x $y] {
         incr sum [lindex $tableau $i $j]
     }
     return $sum
 }

 proc get_neighbour_indices {x y} {
     set results [list]
     foreach x_off {-1 0 1} {
         foreach y_off {-1 0 1} {
             if { ! ($x_off == 0 && $y_off == 0)} {
                 set i [expr {$x + $x_off}] 
                 set j [expr {$y + $y_off}]
                 if {(0 <= $i && $i < $::max_x) && (0 <= $j && $j < $::max_y)} {
                     lappend results $i $j
                 }
             }
         }
     }
     return $results
 }

 main

See also Game of Life at rosettacode.org[L1 ]


Artificial Life