Skip to content

Instantly share code, notes, and snippets.

@RSully
Last active December 19, 2015 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RSully/5962165 to your computer and use it in GitHub Desktop.
Save RSully/5962165 to your computer and use it in GitHub Desktop.
PHP implementation of Game Of Life
<?php
// Implementation
function iterate($original)
{
$board = $original;
for ($x = 0; $x < count($board); $x++) {
$row = $board[$x];
for ($y = 0; $y < count($row); $y++) {
$cell = $row[$y];
$live_neighbors = live_neighbors($original, $x, $y);
if ($cell == 1) {
// Cell is alive
if ($live_neighbors < 2) {
$board[$x][$y] = 0;
} else if ($live_neighbors > 3) {
$board[$x][$y] = 0;
}
} else {
// Cell is dead
if ($live_neighbors == 3) {
$board[$x][$y] = 1;
}
}
}
}
return $board;
}
function live_neighbors($board, $x, $y)
{
$neighbors = @array(
$board[$x-1][$y-1], $board[$x-1][$y], $board[$x-1][$y+1],
$board[$x][$y-1], $board[$x][$y+1],
$board[$x+1][$y-1], $board[$x+1][$y], $board[$x+1][$y+1]
);
return array_sum($neighbors);
}
// Assume board
$board = array(
array(1, 0, 1),
array(0, 1, 1),
array(0, 0, 0)
);
print_r($board);
print_r(iterate($board));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment