Skip to content

Instantly share code, notes, and snippets.

@apeschar
Created March 31, 2016 16:20
Show Gist options
  • Save apeschar/714b6d77b3b5025ba8a20e708156a21a to your computer and use it in GitHub Desktop.
Save apeschar/714b6d77b3b5025ba8a20e708156a21a to your computer and use it in GitHub Desktop.
<?php
// Implementation of Conway's game of life in PHP
// Incomplete and buggy ;)
$board = "
-------------------
-------------------
-------------------
-------------------
-------------------
-------------------
--------***--------
--------*-*--------
--------***--------
--------***--------
--------***--------
--------***--------
--------***--------
--------*-*--------
--------***--------
-------------------
-------------------
-------------------
-------------------
-------------------
-------------------
";
function read_board($board) {
$lines = explode("\n", trim($board));
$w = strlen($lines[0]);
$a = [];
foreach($lines as $l) {
$k = [];
for($i = 0; $i < $w; $i++)
$k[] = $l[$i] == '*' ? 1 : 0;
$a[] = $k;
}
return $a;
}
function write_board($a) {
foreach($a as $l) {
foreach($l as $b)
echo $b ? '*' : '-';
echo "\n";
}
}
function play($a) {
$b = [];
$w = sizeof($a[0]);
for($y = 0, $h = sizeof($a); $y < $h; $y++)
for($x = 0, $ww = $w; $x < $w; $x++) {
$c = $a[$y][$x];
$n = @$a[$y-1][$x-1] + @$a[$y-1][$x] + @$a[$y-1][$x+1] +
@$a[$y][$x-1] + @$a[$y][$x+1] +
@$a[$y+1][$x-1] + @$a[$y+1][$x] + @$a[$y+1][$x+1];
if($c && $n < 2)
$c = false;
elseif($c && $n > 3)
$c = false;
elseif($c)
$c = true;
elseif(!$c && $n == 3)
$c = true;
$b[$y][$x] = $c;
}
return $b;
}
$a = read_board($board);
while(1) {
write_board($a);
echo "\n";
$a = play($a);
sleep(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment