-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBoard.php
112 lines (96 loc) · 2.54 KB
/
Board.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
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
110
111
112
<?php
class Board
{
private array $board = [];
private static int $score = 0;
/**
* @throws BoardFullError
*/
public function __construct(private int $size)
{
$this->setRandomTile();
}
public function show()
{
echo PHP_EOL;
for ($i = 0; $i < $this->size; $i++) {
for ($j = 0; $j < $this->size; $j++) {
print isset($this->board[$i][$j]) ? sprintf('%4d', ($this->board[$i][$j])) : sprintf('%4s', '-');
}
echo PHP_EOL;
}
echo PHP_EOL;
}
public function generateRandomTile(): int
{
$random = rand(1, 100) > 90 ? 4 : 2;
$this::$score += $random;
return $random;
}
public function getMaxTile(): int
{
$max = 0;
foreach ($this->board as $array) {
foreach ($array as $value) {
if ($value > $max) {
$max = $value;
}
}
}
return $max;
}
/**
* will take too much time to find find empty index
* @throws BoardFullError
* @todo can be optimized the logic
*/
public function setRandomTile(): void
{
if ($this->isFull() and $this->noMovesLeft()) {
throw new \BoardFullError();
}
do {
$randomIndexX = rand(0, $this->size - 1);
$randomIndexY = rand(0, $this->size - 1);
} while (isset($this->board[$randomIndexX][$randomIndexY]));
$this->board[$randomIndexX][$randomIndexY] = $this->generateRandomTile();
}
private function isFull(): bool
{
$full = true;
for ($i = 0; $i < $this->size; $i++) {
for ($j = 0; $j < $this->size; $j++) {
if (!isset($this->board[$i][$j])) {
$full = false;
break 2;
}
}
}
return $full;
}
public function score(): string
{
return PHP_EOL . 'Highest Tile: ' . $this->getMaxTile() . PHP_EOL . 'Total Score: ' . $this::$score;
}
public function resetBoard(array $array): void
{
$this->board = $array;
}
public function setBoard(int $row, int $col, ?int $value): void
{
$this->board[$row][$col] = $value;
}
public function getBoard(): array
{
return $this->board;
}
public function getSize(): int
{
return $this->size;
}
public function noMovesLeft(): bool
{
/** @todo add logic later */
return false;
}
}