-
Notifications
You must be signed in to change notification settings - Fork 0
/
life.php
69 lines (62 loc) · 1.66 KB
/
life.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
include_once ("config.php");
function alive($num_of_neighbors){
if ($num_of_neighbors < 2 || $num_of_neighbors > 3) {
return false;
}
return true;
}
function apply_rules() {
$new_world=[];
$_SESSION['last_world'] = $_SESSION['world'];
for($x=0;$x<SIZE;$x++) {
for($y=0;$y<SIZE;$y++) {
$num_of_neighbors=num_of_neighbors($x,$y);
$new_world[$x][$y]=$_SESSION["world"][$x][$y] ? alive($num_of_neighbors) : dead($num_of_neighbors);
}
}
$_SESSION['world']=$new_world;
should_it_continue();
}
function dead($num_of_neighbors){
if ($num_of_neighbors == 3) {
return true;
}
return false;
}
function everything_is_dead() {
for($x=0;$x<SIZE;$x++) {
for($y=0;$y<SIZE;$y++) {
if ($_SESSION["world"][$x][$y]) {
return false;
}
}
}
return true;
}
function neighbors($home_x, $home_y) {
$neighbors = [];
for ($x=($home_x-1);$x<($home_x+2);$x++){
for ($y=($home_y-1);$y<($home_y+2);$y++){
if ($x!=$home_x || $y!=$home_y){
$coords=["x"=>$x, "y"=>$y];
array_push($neighbors, $coords);
}
}
}
return $neighbors;
}
function num_of_neighbors($x, $y) {
$neighbors = neighbors($x, $y);
$num = 0;
for ($i = 0; $i < 8; $i++) {
if (isset($_SESSION["world"][$neighbors[$i]["x"]][$neighbors[$i]["y"]])
&& $_SESSION["world"][$neighbors[$i]["x"]][$neighbors[$i]["y"]]) {
$num++;
}
}
return $num;
}
function should_it_continue() {
$_SESSION['stop'] = ($_SESSION['last_world'] ==$_SESSION['world'] || everything_is_dead());
}