Created
March 6, 2016 14:25
-
-
Save octopuss/4c192c2a904f1d529eb3 to your computer and use it in GitHub Desktop.
GOL php simple implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Cell { | |
public $x; | |
public $y; | |
public $surroundings = []; | |
public function __construct($x, $y) | |
{ | |
$this->x = $x; | |
$this->y = $y; | |
array_push($this->surroundings, ($x) . "|" . ($y+1)); | |
array_push($this->surroundings, ($x) . "|" . ($y-1)); | |
array_push($this->surroundings, ($x+1) . "|" . ($y)); | |
array_push($this->surroundings, ($x-1) . "|" . ($y)); | |
array_push($this->surroundings, ($x-1) . "|" . ($y-1)); | |
array_push($this->surroundings, ($x+1) . "|" . ($y-1)); | |
array_push($this->surroundings, ($x-1) . "|" . ($y+1)); | |
array_push($this->surroundings, ($x+1) . "|" . ($y+1)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class GolTest extends PHPUnit_Framework_TestCase { | |
/** | |
* @test | |
*/ | |
public function shouldDieIfHaveLessThan2Neighbours(){ | |
$world = new World( | |
array( | |
"1|1" => new Cell(1,1) | |
) | |
); | |
$world->step(); | |
$this->assertEquals(false, isset($world->cells["1|1"])); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class World { | |
public $cells; | |
public function __construct($cells) | |
{ | |
$this->cells = $cells; | |
} | |
public function step(){ | |
$newWorld = []; | |
foreach ($this->cells as $cell) { | |
$siblingsCount = 0; | |
foreach($cell->surroundings as $surrounding) { | |
if(isset($this->cells[$surrounding])) { | |
$siblingsCount++; | |
} else { | |
$surroundingArray = preg_split('/\|+/',$surrounding); | |
$tmpCell = new Cell($surroundingArray[0],$surroundingArray[1]); | |
$tmpSiblingCount = 0; | |
foreach ($tmpCell->surroundings as $tmpSurrounding) { | |
if(isset($this->cells[$tmpSurrounding])) { | |
$tmpSiblingCount++; | |
} | |
} | |
if($tmpSiblingCount == 3) { | |
$newWorld[$tmpCell->x . "|" . $tmpCell->y] = $tmpCell; | |
} | |
} | |
} | |
if($siblingsCount == 2 || $siblingsCount == 3) { | |
$newWorld[$cell->x . "|" . $cell->y] = $cell; | |
} | |
} | |
$this->cells = $newWorld; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment