logo
Published on KernelTrap (http://kerneltrap.org)

Cellular Automata

By Greg Buchholz
Created Mar 8 2007 - 18:15

After seeing a cellular automata simulator [1] in F#, I thought I'd make a more general version with Perl/TK which was also shorter. Invoke with a numeric argument on the command line to see automata other than rule 30 (e.g. 90, 110).

#!/usr/bin/perl 
use Tk;
$rule=shift;

if($rule eq '') { $rule=30 }

$width=1024;

$canv = MainWindow->new()->Canvas(-width  => $width, 
                                  -height => $width/2)->pack();
$p[$width/2]=1;

for(my $y=0;$y<$width/2;$y++) 
{
  for(my $x=$width/2-$y-1;$x<$width/2+$y+1;$x++)
  {
    $this_row[$x] = $p[$x-1] &&  $p[$x] &&  $p[$x+1] && ($rule & 128) ||
                    $p[$x-1] &&  $p[$x] && !$p[$x+1] && ($rule & 64)  ||
                    $p[$x-1] && !$p[$x] &&  $p[$x+1] && ($rule & 32)  ||
                    $p[$x-1] && !$p[$x] && !$p[$x+1] && ($rule & 16)  ||
                   !$p[$x-1] &&  $p[$x] &&  $p[$x+1] && ($rule & 8)   ||
                   !$p[$x-1] &&  $p[$x] && !$p[$x+1] && ($rule & 4)   ||
                   !$p[$x-1] && !$p[$x] &&  $p[$x+1] && ($rule & 2)   ||
                   !$p[$x-1] && !$p[$x] && !$p[$x+1] && ($rule & 1);

    if($this_row[$x]){ $canv->createLine($x, $y, $x+1, $y,-fill => 'black');}
  }
  @p=@this_row;
}	

MainLoop();


Source URL:
http://kerneltrap.org/node/7821