-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathBoard.php
263 lines (224 loc) · 7.75 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
<?php
namespace Packages\Models\Othello\Board;
use Packages\Models\Common\Matrix\Matrix;
use Packages\Models\Othello\Board\Color\Color;
use Packages\Models\Othello\Board\Position\Position;
use Packages\Models\Othello\Board\Position\PositionConverterTrait;
class Board
{
use PositionConverterTrait;
/**
* @var Matrix
*/
private Matrix $board;
/**
* @var array<int, int>
*/
private array $flipScores;
const BOARD_EMPTY = 0;
const BOARD_SIZE_ROWS = 8;
const BOARD_SIZE_COLS = 8;
private function __construct(array $board)
{
$matrix = Matrix::make($board);
// 行数チェック
if ($matrix->dim() != self::BOARD_SIZE_ROWS) throw new \RuntimeException('lack of row');
// 各行の列数チェック
if ($matrix->size() != self::BOARD_SIZE_COLS) throw new \RuntimeException('lack of column');
$this->board = $matrix;
}
public static function init(): Board
{
$matrix = Matrix::init(self::BOARD_SIZE_COLS, self::BOARD_SIZE_ROWS, self::BOARD_EMPTY);
$matrix->setData(Color::white()->toCode(), 4, 4);
$matrix->setData(Color::black()->toCode(), 4, 5);
$matrix->setData(Color::black()->toCode(), 5, 4);
$matrix->setData(Color::white()->toCode(), 5, 5);
return new Board($matrix->toArray());
}
public static function make(array $board): Board
{
return new Board($board);
}
public function toArray(): array
{
return $this->board->toArray();
}
public function isFulfilled(): bool
{
return $this->getRest() === 0;
}
/**
* 何も置かれていない場所の数を取得
*
* @return int
*/
public function getRest(): int
{
$filterd = array_filter($this->board->flatten(), function ($value) {
return $value === self::BOARD_EMPTY;
});
return count($filterd);
}
/**
* 片方の色の石の数(=得点)を取得
*
* @param Color $color
* @return int
*/
public function getPoint(Color $color): int
{
$filterd = array_filter($this->board->flatten(), function ($value) use ($color) {
return $color->codeEquals($value);
});
return count($filterd);
}
/**
*
*
* @param Color $color
* @return bool
*/
public function hasPlayablePosition(Color $color): bool
{
for ($row = 1; $row <= $this->board->dim(); $row++) {
for ($col = 1; $col <= $this->board->size(); $col++) {
// 一つでもおけるマスがあったらtrueを返す
if ($this->isValid(Position::make([$row, $col]), $color)) return true;
}
}
return false;
}
/**
* @param Color $color
* @return array
*/
public function playablePositions(Color $color): array
{
if (empty($this->flipScores)) $this->analyze($color);
// ひっくり返せるPositionだけ返す
// TODO: ここで処理が重くなっている可能性があるので検証する
return array_map(fn($positionId) => Position::make($positionId), array_keys($this->flipScores));
}
private function getFlipScore(array $position, Color $color): int
{
$flipScore = 0;
// 調査するマスが空白ではないときは取れないので0を返す
$fieldItem = $this->board->getData($position[0], $position[1]);
if ($fieldItem) {
return $flipScore;
}
$lineDataList = $this->board->getLinesClockwise($position, true);
foreach ($lineDataList as $lineData) {
// 何個裏返すことができるか計算
$lineCount = $this->flipCountInLine($lineData, $color);
// 裏返したコマの数を追加
$flipScore += $lineCount;
}
return $flipScore;
}
public function isValid(Position $position, Color $color): bool
{
if ($this->getFlipScore($position->toMatrixPosition(), $color) > 0) {
return true;
}
return false;
}
public function update(Position $position, Color $color): Board
{
// 指定された場所にコマを置くことができるか確認
if (!$this->isValid($position, $color)) {
throw new \Exception('指定された場所に置くことができません');
}
// 更新された盤面を返す
$updatedBoard = $this->flipStones($position->toMatrixPosition(), $color);
return new Board($updatedBoard);
}
/**
* Undocumented function
*
* @param array $board
* @param Color $color
* @return array
*/
private function flipStones(array $position, Color $color): array
{
// TODO: #6 番兵などでパフォーマンス改善
$board = clone $this->board;
// HACK: 毎回全要素を取得しているとオーバーヘッドが大きいかもなので、位置だけ取得してデータは必要なときに都度取得する形式の方がいいかも
$lineDataList = $board->getLinesClockwise($position, true);
$totalCount = 0;
$updatedLines = [];
foreach ($lineDataList as $lineData) {
// 何個裏返すことができるか計算
$flipCount = $this->flipCountInLine($lineData, $color);
if ($flipCount > 0) {
// 裏返せるコマがあったら裏返す
for ($i = 0; $i < $flipCount; $i++) {
$lineData[$i] = $color->toCode();
}
}
$updatedLines[] = $lineData;
// 裏返したコマの数を追加
$totalCount += $flipCount;
}
if ($totalCount > 0) {
// ひとつでも裏返せていたらコマを置く
$board->setData($color->toCode(), $position[0], $position[1]);
$board->setLinesClockwise($updatedLines, $position, true);
}
return $board->toArray();
}
/**
* Undocumented function
*
* @param array $lineData
* @param Color $color
* @return int $length
*/
private function flipCountInLine(array $lineData, Color $color): int
{
if (empty($lineData)) return 0;
// 添字を初期化(念の為)
$lineData = array_values($lineData);
// 反対の色が連続する数を調べる
$lastKey = 0;
foreach ($lineData as $key => $field) {
// 反対の色以外が出たらその位置のキーを記録
if (!$color->isOppositeCode($field)) {
$lastKey = $key;
break;
}
}
// ループが終了したマスの状態に応じて処理分岐
if ($color->codeEquals($lineData[$lastKey])) {
// 同じ色があったらカウント数を返す
return $lastKey; // 0の場合も含む
} else {
// 何も置いていない or 範囲外に到達した場合はひっくり返すコマは0個
return 0;
}
}
public function equals(Board $board): bool
{
return $this->board->toArray() === $board->toArray();
}
public function diff(Board $board)
{
//
}
public function analyze(Color $color)
{
$flipScores = [];
for ($row = 1; $row <= $this->board->dim(); $row++) {
for ($col = 1; $col <= $this->board->size(); $col++) {
$score = $this->getFlipScore([$row, $col], $color);
if ($score > 0) {
$positionId = $this->convertToPositionId([$row, $col]);
$flipScores[$positionId] = $score;
}
}
}
$this->flipScores = $flipScores;
}
}