my $life = new life: 20;
####
loop { $life.display() }
##
##
class life
{
has Int $.count;
has Int $.max;
has Array of Bit @.grid;
##
##
method BUILD(Int $dim)
##
##
{
$.count = 0;
$.max = $dimension-1;
my Array of Bit @grid is dim($dim,$dim) is default(0);
##
##
@grid[$dim / 2 - 1][$dim / 2 ] = 1;
@grid[$dim / 2 - 1][$dim / 2 + 1] = 1;
@grid[$dim / 2 ][$dim / 2 ] = 1;
@grid[$dim / 2 ][$dim / 2 - 1] = 1;
@grid[$dim / 2 + 1][$dim / 2 ] = 1;
@.grid := @grid;
##
##
}
sub iterate (&block)
##
##
{
for 0..$.max -> $x
##
##
{
for 0..$.max -> $y
{
block($x,$y);
}
}
}
method calculate() is private
{
my @newgrid;
iterate
{
my $live = sum(@.grid[$^x-1..$^x+1][$^y-1..$^y+1]);
@newgrid[$^x][$^y] = $live==2 && @.grid[$^x][$^y]
|| $live==3;
}
##
##
@.grid = @newgrid;
}
method display
{
iterate {
print $.grid[$^x][$^y] ?? '+' :: '.';
print "\n" if $^x == $.max;
}
print "\n";
print "Turn $(++$.count), press enter to continue or ctl-c to quit;
<$*IN>;
##
##
.calculate();
}
}