-
Notifications
You must be signed in to change notification settings - Fork 0
/
Life.php
57 lines (51 loc) · 1.45 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
<?php
class Life
{
/**
* @var Universe
*/
private $universe;
private $generation;
public function __construct(Universe $universe)
{
$this->universe = $universe;
$this->generation = 0;
}
public function evolve()
{
$newuniverse = $this->universe->getCells();
for ($r = 0; $r < $this->universe->getNumRows(); $r++) {
for ($c = 0; $c < $this->universe->getNumCols(); $c++) {
$newuniverse[$r][$c] = $this->tick($r, $c);
}
}
$this->universe->setCells($newuniverse);
$this->generation++;
}
public function getGeneration(): int
{
return $this->generation;
}
private function tick(int $row, int $col): int
{
$new = null;
$current = $this->universe->getCellAt($row, $col);
$numAliveNeighbours = $this->universe->countNeighbours($row, $col);
if (1 === $current) {
if (in_array($numAliveNeighbours, [0, 1])) { // Die lonely
$new = 0;
} elseif (in_array($numAliveNeighbours, [4, 5, 6, 7, 8])) { // Die overcrowded
$new = 0;
} elseif (in_array($numAliveNeighbours, [2, 3])) {
$new = 1;
}
} else {
if ($numAliveNeighbours === 3) { // Birth
$new = 1;
} else { // Barren
$new = 0;
}
}
return $new;
}
}