Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Conway {
- private $population = array(
- array(1,0,1),
- array(1,1,1),
- array(0,1,0)
- );
- private $nextPopulation = array();
- private $time=0;
- /* You can set a specific population from the outside */
- public function setPopulation($arr) {
- $this->population = $arr;
- $this->time=0;
- }
- /* Calculate the next generation */
- public function nextGen() {
- for($x = 0; $x < count($this->population); $x++) {
- for($y = 0; $y < count($this->population[$x]); $y++) {
- $nbs = $this->_countNeighboursAlive($x,$y);
- if($nbs == 3) $this->nextPopulation[$x][$y] = 1;
- elseif($nbs < 2 or $nbs > 3) $this->nextPopulation[$x][$y] = 0;
- else $this->nextPopulation[$x][$y] = $this->population[$x][$y];
- }
- }
- $this->population = $this->nextPopulation;
- $this->time++;
- }
- /* count all existent and alive neighbours */
- private function _countNeighboursAlive($x,$y) {
- $neighbours = $this->_getNeighbours($x,$y);
- $ret = 0;
- foreach($neighbours as $n) {
- if(isset($this->population[$n[0]][$n[1]]) and $this->population[$n[0]][$n[1]]) $ret++;
- }
- return $ret;
- }
- /* It returns all possibilities of neighbours, despite the fact, some might not exists */
- private function _getNeighbours($x,$y) {
- $neighbours = array();
- array_push($neighbours, array($x-1,$y-1));
- array_push($neighbours, array($x-1,$y));
- array_push($neighbours, array($x-1,$y+1));
- array_push($neighbours, array($x,$y-1));
- array_push($neighbours, array($x,$y+1));
- array_push($neighbours, array($x+1,$y-1));
- array_push($neighbours, array($x+1,$y));
- array_push($neighbours, array($x+1,$y+1));
- return $neighbours;
- }
- public function get() {
- for($x = 0; $x < count($this->population); $x++) {
- for($y = 0; $y < count($this->population[$x]); $y++) {
- print ($this->population[$x][$y] ? ' # ' : ' . ');
- }
- print "\n";
- }
- print "\nGeneraten: ".$this->time;
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement