Advertisement
nuit

Conway - game of life

Apr 9th, 2011
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.92 KB | None | 0 0
  1. <?php
  2. class Conway {
  3.     private $population = array(
  4.         array(1,0,1),
  5.         array(1,1,1),
  6.         array(0,1,0)
  7.     );
  8.     private $nextPopulation = array();
  9.     private $time=0;
  10.    
  11.     /* You can set a specific population from the outside */
  12.     public function setPopulation($arr) {
  13.         $this->population = $arr;
  14.         $this->time=0;
  15.     }
  16.  
  17.     /* Calculate the next generation */
  18.     public function nextGen() {
  19.         for($x = 0; $x < count($this->population); $x++) {
  20.             for($y = 0; $y < count($this->population[$x]); $y++) {
  21.                 $nbs = $this->_countNeighboursAlive($x,$y);
  22.                 if($nbs == 3) $this->nextPopulation[$x][$y] = 1;
  23.                 elseif($nbs < 2 or $nbs > 3) $this->nextPopulation[$x][$y] = 0;
  24.                 else $this->nextPopulation[$x][$y] = $this->population[$x][$y];
  25.             }
  26.         }
  27.         $this->population = $this->nextPopulation;
  28.         $this->time++;
  29.     }
  30.  
  31.     /* count all existent and alive neighbours */
  32.     private function _countNeighboursAlive($x,$y) {
  33.         $neighbours = $this->_getNeighbours($x,$y);
  34.         $ret = 0;
  35.         foreach($neighbours as $n) {
  36.             if(isset($this->population[$n[0]][$n[1]]) and $this->population[$n[0]][$n[1]]) $ret++;
  37.         }
  38.         return $ret;
  39.     }
  40.    
  41.     /* It returns all possibilities of neighbours, despite the fact, some might not exists */
  42.     private function _getNeighbours($x,$y) {
  43.         $neighbours = array();
  44.         array_push($neighbours, array($x-1,$y-1));
  45.         array_push($neighbours, array($x-1,$y));
  46.         array_push($neighbours, array($x-1,$y+1));
  47.        
  48.         array_push($neighbours, array($x,$y-1));
  49.         array_push($neighbours, array($x,$y+1));
  50.        
  51.         array_push($neighbours, array($x+1,$y-1));
  52.         array_push($neighbours, array($x+1,$y));
  53.         array_push($neighbours, array($x+1,$y+1));
  54.  
  55.         return $neighbours;
  56.     }
  57.  
  58.     public function get() {
  59.         for($x = 0; $x < count($this->population); $x++) {
  60.             for($y = 0; $y < count($this->population[$x]); $y++) {
  61.                 print ($this->population[$x][$y] ? ' # ' : ' . ');
  62.             }
  63.             print "\n";
  64.         }
  65.         print "\nGeneraten: ".$this->time;
  66.     }
  67. }
  68. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement