package Organism; # based on http://perlmonks.org/?node_id=1197284 use strict; use warnings; sub count { return shift->{config}[0] =~ tr/1//; } # Input a list of [ x, y ] coords sub insert_cells { my $extra = 3; my $self = shift; my $xl = my $xh = $_[0][0]; # find cell limits my $yl = my $yh = $_[0][1]; for (@_) { my ($x, $y) = @$_; $xl > $x and $xl = $x; $xh < $x and $xh = $x; $yl > $y and $yl = $y; $yh < $y and $yh = $y; } my $xoffset = $xl - $extra; # get sizes and insert live cells my $w = $xh - $xl + 2 * $extra; my $yoffset = $yl - $extra; my $h = $yh - $yl + 2 * $extra; my $grid = '0' x $w x $h; for (@_) { my ($x, $y) = @$_; substr $grid, $x - $xoffset + ($y - $yoffset) * $w, 1, '1'; } $self->{config} = [ $grid, $w, $h, $xoffset, $yoffset ]; } # Return sorted list of cells in the Organism. # Used for verification and testing the state of the organism. sub get_live_cells { my $self = shift; my ( $grid, $w, $h, $xoffset, $yoffset ) = @{ $self->{config} }; my @cells; push @cells, [ $-[0] % $w + $xoffset, int( $-[0] / $w ) + $yoffset ] while $grid =~ /1/g; sort { $a->[0] <=> $b->[0] || $a->[1] <=> $b->[1] } @cells; } sub tick { my $self = shift; my ( $grid, $w, $h, $xoffset, $yoffset ) = @{ $self->{config} }; # expand $grid = join '00', '0' x ($w + 1), unpack("(a$w)*", $grid), '0' x ($w + 1); $w += 2; $h += 2; $xoffset--; $yoffset--; # now get new generation my $all = '0' x ($w + 1) . $grid; my $sum = $all =~ tr/1/2/r; ( $sum |= substr $all, $_ ) =~ tr/1357/2468/ for 1, 2, $w, $w + 2, $w * 2, $w * 2 + 1, $w * 2 + 2; # other 7 neighbors $grid = substr $grid | $sum, 0, $w * $h; $self->{config} = [ $grid =~ tr/1-9/000011100/r, $w, $h, $xoffset, $yoffset ]; } sub new { my $class = shift; my %init_self = ( ); bless \%init_self, $class; } 1;