#!/usr/bin/perl
use warnings;
use strict;
####
my $life = new life : 20;
####
loop { $life.display() }
####
class life
{
####
has Int $.count;
has Int $.dimension;
has Array of Bit @.grid;
####
method BUILD(Int $dimension)
{
$.count = 0;
$.max = $dimension - 1;
####
my Array of Bit @.grid is dim($dimension,$dimension)
is default(0);
####
@grid[$dimension / 2 - 1][$dimension / 2] = 1;
@grid[$dimension / 2 - 1][$dimension / 2 + 1] = 1;
@grid[$dimension / 2][$dimension / 2] = 1;
@grid[$dimension / 2][$dimension / 2 - 1] = 1;
@grid[$dimension / 2 + 1][$dimension / 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();
}
}