-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathboard.php
More file actions
109 lines (85 loc) · 2.85 KB
/
board.php
File metadata and controls
109 lines (85 loc) · 2.85 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
class board {
private $width;
private $height;
private $board = [];
/* Initialize an empty board */
public function __construct($height, $width) {
/* less than 3 will lead to overlapping neighboouring cells */
if ($width < 3 or $height < 3) {
throw new \RuntimeException('Width and height must be at least 3');
}
for ($x = 0; $x < $height; $x++) {
$this->board[$x] = [];
for ($y = 0; $y < $width; $y++) {
$this->board[$x][$y] = 0;
}
}
$this->width = $width;
$this->height = $height;
}
/* set any cell on the board to 1 or 0 */
public function set($x, $y, $value) {
/* wrap board */
$x = $x % $this->height;
$y = $y % $this->width;
/* enforce 0/1 integers to make counting easier */
$value = $value ? 1 : 0;
$this->board[$x][$y] = $value;
}
/* fetch the value of any cell */
public function get($x, $y) {
/* wrap board */
$x = ($this->height+$x) % $this->height;
$y = ($this->width+$y) % $this->width;
return $this->board[$x][$y];
}
/* Return the number of neighbouring cells that are alive */
private function neighbourCount($x, $y) {
return $this->get($x-1, $y-1)
+ $this->get($x-1, $y )
+ $this->get($x-1, $y+1)
+ $this->get($x , $y-1)
+ $this->get($x , $y+1)
+ $this->get($x+1, $y-1)
+ $this->get($x+1, $y )
+ $this->get($x+1, $y+1)
;
}
/* Jump one step in time ahead */
public function cycle() {
$newBoard = [];
for ($x = 0; $x < $this->height; $x++) {
$newBoard[] = [];
for ($y = 0; $y < $this->width; $y++) {
$newCell = $this->board[$x][$y];
$count = $this->neighbourCount($x, $y);
if ($count < 2) {
$newCell = 0;
}
if ($count > 3) {
$newCell = 0;
}
if ($count == 3) {
$newCell = 1;
}
$newBoard[$x][$y] = $newCell;
}
}
$this->board = $newBoard;
}
/* Dump the board with 1337 ascii art */
public function print() {
/* PHP Cli does not have an easy, cross-platform compatible clear screen :( */
echo str_repeat(PHP_EOL, 100);
echo '╔'.str_repeat('═', $this->width).'╗'.PHP_EOL;
for ($x = 0; $x < $this->height; $x++) {
echo '║';
for ($y = 0; $y < $this->width; $y++) {
echo $this->get($x, $y) ? '█' : ' ';
}
echo '║'.PHP_EOL;
}
echo '╚'.str_repeat('═', $this->width).'╝'.PHP_EOL;
}
}