package termite; use strict; use warnings; #keeps track of how many termites there are { my $_count=0; sub getcount{ $_count; } sub inccount{ $_count++; } sub deccount{ $_count--; } } #creates a new termite sub new { my ($class, %arg)=@_; my $termite = bless { _grid => $arg{"grid"}, _xpos => $arg{"x"}, _ypos => $arg{"y"}, _direction => $arg{"direction"}, _chip => $arg{"chip"}, },$class; $class->inccount(); return $termite; } #returns the value of the variable asked for sub getgrid {$_[0] -> {_grid}} sub getx {$_[0] -> {_xpos}} sub gety {$_[0] -> {_ypos}} sub getdir {$_[0] -> {_direction}} sub getchip {$_[0] -> {_chip}} #randomly pick a direction #sub setdir { # #} #pick direction take a step forward sub step { my ($termite,$grid)=@_; my @xoff=(-1,0,1,0); my @yoff=(0,1,0,-1); print STDERR "$termite->{_xpos} $termite->{_ypos} $termite->{_chip} $termite->{_direction}\n"; if ($$grid[$termite->{_xpos}+$xoff[$termite->{_direction}]+($termite->{_ypos}+$yoff[$termite->{_direction}])*20]==1) { if($termite->{_chip}==0){ $termite->{_xpos}+=$xoff[$termite->{_direction}]; $termite->{_ypos}+=$yoff[$termite->{_direction}]; $termite->pickup($grid,$termite); } else { $termite->drop($grid,$termite); $termite->{_xpos}-=$xoff[$termite->{_direction}]; $termite->{_ypos}-=$yoff[$termite->{_direction}]; $termite->{_direction}=($termite->{_direction}+1)%4; } } else { $termite->{_xpos}+=$xoff[$termite->{_direction}]; $termite->{_ypos}+=$yoff[$termite->{_direction}]; } if(rand()<.2){ if(rand()<.5){ $termite->{_direction}=($termite->{_direction}+1)%4; } else { $termite->{_direction}=($termite->{_direction}+3)%4; } } if($termite->{_xpos}<0){ $termite->{_xpos}=0; } if($termite->{_ypos}<0){ $termite->{_ypos}=0; } if($termite->{_xpos}>=20){ $termite->{_xpos}=19; } if($termite->{_ypos}>=20){ $termite->{_ypos}=19; } } #set chip to true, keep wandering sub pickup { my($termite,$grid)=@_; $$grid[$termite->{_xpos}+$termite->{_ypos}*20]=0; $termite->{_chip}=1; } #set chip to false, move to new empty spot sub drop { my($termite,$grid)=@_; $$grid[$termite->{_xpos}+$termite->{_ypos}*20]=1; $termite->{_chip}=0; } 1;