Skip to content

Instantly share code, notes, and snippets.

@octopuss
Created March 6, 2016 14:25
Show Gist options
  • Save octopuss/4c192c2a904f1d529eb3 to your computer and use it in GitHub Desktop.
Save octopuss/4c192c2a904f1d529eb3 to your computer and use it in GitHub Desktop.
GOL php simple implementation
<?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));
}
}
<?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"]));
}
}
<?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