Created
December 5, 2014 08:48
-
-
Save AmazingDreams/845093d31657e2e81d9f to your computer and use it in GitHub Desktop.
Game of Life
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 | |
define('LIFE', '+'); | |
define('VOID', ' '); | |
define('MAX_X', $argv[1]); | |
define('MAX_Y', $argv[2]); | |
$world = genWorld(MAX_X, MAX_Y); | |
while(true) | |
{ | |
$world = draw($world); | |
$world = update($world); | |
usleep(0.5 * 1000 * 1000); | |
} | |
function genWorld() | |
{ | |
$world = array(); | |
for($x = 0; $x < MAX_X; $x++) | |
{ | |
for($y = 0; $y < MAX_Y; $y++) | |
{ | |
$world[$x][$y] = VOID; | |
} | |
} | |
for($i = 0; $i < MAX_X * MAX_Y * 0.25; $i++) | |
{ | |
$world[rand(0, MAX_X)][rand(0, MAX_Y)] = LIFE; | |
} | |
return $world; | |
} | |
function update($world) | |
{ | |
$toFill = []; | |
$toKill = []; | |
for($x = 0; $x < MAX_X; $x++) | |
{ | |
for($y = 0; $y < MAX_Y; $y++) | |
{ | |
$neighbors = countNeighbors($world, $x, $y); | |
if($world[$x][$y] == LIFE) | |
{ | |
if ($neighbors < 2 OR $neighbors > 3 ) | |
{ | |
$toKill[] = array($x, $y); | |
} | |
} | |
else | |
{ | |
if($neighbors == 3) | |
{ | |
$toFill[] = array($x, $y); | |
} | |
} | |
} | |
} | |
foreach($toFill as $ent) | |
{ | |
$world[$ent[0]][$ent[1]] = LIFE; | |
} | |
foreach($toKill as $ent) | |
{ | |
$world[$ent[0]][$ent[1]] = VOID; | |
} | |
return $world; | |
} | |
function draw($world) | |
{ | |
for($x = 0; $x < MAX_X; $x++) | |
{ | |
for($y = 0; $y < MAX_Y; $y++) | |
{ | |
echo ' '.$world[$x][$y]; | |
} | |
echo PHP_EOL; | |
} | |
return $world; | |
} | |
function countNeighbors($world, $x, $y) | |
{ | |
$count = 0; | |
for($a = $x - 1; $a <= $x + 1; $a++) | |
{ | |
for($b = $y - 1; $b <= $y + 1; $b++) | |
{ | |
if($a == $x AND $b == $y) continue; | |
if(isset($world[$a][$b]) AND $world[$a][$b] == LIFE) | |
$count++; | |
} | |
} | |
return $count; | |
} | |
function fillAround($world, $x, $y, $with = LIFE) | |
{ | |
for($a = $x - 1; $a <= $x + 1 AND $a <= MAX_X; $a++) | |
{ | |
for($b = $y - 1; $b <= $y + 1 AND $b <= MAX_Y; $b++) | |
{ | |
if($a == $x AND $b == $y) continue; | |
$world[$a][$b] = $with; | |
} | |
} | |
return $world; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
run with eg
php gameoflife.php 100 100