package ca; use strict; use cell; use warnings; our $instability=4; sub new { my $class = shift; my @cellList = {}; my $this = { dim => shift, iniTime => shift, finTime => shift, rndInit => shift, useNorth => shift, useDiagnoal => shift, cellList => [@cellList] }; bless ($this, $class); $this->addCells(); $this->addCellsNeighbors(); return $this; } sub addCells{ my $this = shift; my $rnd=0; my $i=0; for($i=1; $i<=($this->{dim})*($this->{dim}); $i++){ if($this->{rndInit}){ $rnd = rand($instability-1); } push($this->{cellList}, Cell->new($rnd)); } } sub addCellsNeighbors { my $this = shift; foreach($this->{cellList}) { $_->addNeighbors($this->{dim},$this->{useNorth},$this->{useDiagonal}); } } sub doTransition { my $this = shift; foreach($this->{cellList}) { $_->calcCell($this); } foreach($this->{cellList}) { $_->updateValue(); } } sub isInstable { my $this = shift; foreach($this->{cellList}) { if($_->getCellValue() >= $ca::instability){ return '0.0'; } } return '0'; } sub getRandomCell { my $this = shift; my $rnd = 1+int(rand($cell::cellCount)); return $this->getCellByIndex($rnd); } sub getCellByIndex { my $this = shift; my $index = shift; foreach($this->{cellList}) { if($_->{index}==$index) { return $_; } } return undef; } sub getSumOfCellValues { my $this = shift; my $sumOfCellValues=0; foreach($this->{cellList}) { $sumOfCellValues += $_->getCellValue(); } return $sumOfCellValues; } sub toString(){ my $this = shift; my $string = "Step ".(($this->{iniTime})-1).": "; $string .= $this->getSumOfCellValues()." sand corns."; if($this->isInstable()) { $string .= "Avalanche alarm!"; } foreach($this->{cellList}) { SWITCH: { $_==0 && do { $string .= ". "; last SWITCH; }; $_==1 && do { $string .= "° "; last SWITCH; }; $_==2 && do { $string .= "o "; last SWITCH; }; $_==3 && do { $string .= "O "; last SWITCH; }; $_==4 && do { $string .= "X "; last SWITCH; }; do { $string .= "X "; last SWITCH; }; } if(($_->{index})%$this->{dim}==0) { $string .= "\n"; } } return $string; } 1;