-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboard.py
373 lines (315 loc) · 12.2 KB
/
board.py
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
from __future__ import annotations
import re
from enum import Enum
from typing import Optional
from PIL import Image, ImageDraw, ImageFont
BOARD_SIZE = 8
TILE_SIZE = 8
BOARD_IMAGE = Image.open("./img/board.png")
BLACK_IMAGE = Image.open("./img/black.png")
WHITE_IMAGE = Image.open("./img/white.png")
SELECTED_ROW_IMAGE = Image.open("./img/selected-row.png")
SELECTED_TILE_IMAGE = Image.open("./img/selected-tile.png")
POSSIBLE_TILE_IMAGE = Image.open("./img/possible-tile.png")
BUFFER_PATTERN = re.compile(f"^([BW.]{{{BOARD_SIZE}}}($|\\|)){{{BOARD_SIZE}}}")
def deserialize_place(place_string: str) -> Optional[tuple[int, int]]:
try:
rs, _, cs = place_string.partition(",")
r = int(rs)
c = int(cs)
return (r, c)
except:
return None
class Tile(Enum):
EMPTY = "."
BLACK = "B"
WHITE = "W"
@property
def image(self) -> Optional[Image.Image]:
if self == Tile.BLACK:
return BLACK_IMAGE
elif self == Tile.WHITE:
return WHITE_IMAGE
else:
return None
def opposite(self) -> Tile:
if self == Tile.BLACK:
return Tile.WHITE
elif self == Tile.WHITE:
return Tile.BLACK
else:
raise ValueError()
def is_occupied(self) -> bool:
return self != Tile.EMPTY
class Board:
def __init__(self) -> None:
self._board = [[Tile.EMPTY for _c in range(BOARD_SIZE)] for _r in range(BOARD_SIZE)]
self._board[3][3] = Tile.WHITE
self._board[3][4] = Tile.BLACK
self._board[4][3] = Tile.BLACK
self._board[4][4] = Tile.WHITE
def to_image(self, selected_row: Optional[int] = None, selected_col: Optional[int] = None, color: Tile = Tile.EMPTY) -> Image.Image:
image = Image.new("RGBA", BOARD_IMAGE.size)
image.paste(BOARD_IMAGE)
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("./minecraft_font.ttf", 8)
# Checkerboard, possible moves and placed tiles
for r in range(BOARD_SIZE):
for c in range(BOARD_SIZE):
tile_image = self._board[r][c].image
if tile_image is not None:
image.paste(tile_image, (c * TILE_SIZE, r * TILE_SIZE), tile_image)
elif color != Tile.EMPTY and self._is_move_valid(color, r, c):
image.paste(POSSIBLE_TILE_IMAGE, (c * TILE_SIZE, r * TILE_SIZE), POSSIBLE_TILE_IMAGE)
# Selected rows, columns
if selected_row is not None:
if selected_col is not None:
image.paste(SELECTED_TILE_IMAGE,
(selected_col * TILE_SIZE, selected_row * TILE_SIZE), SELECTED_TILE_IMAGE)
else:
image.paste(SELECTED_ROW_IMAGE, (0, selected_row * TILE_SIZE), SELECTED_ROW_IMAGE)
# Current turn indicator
if color != Tile.EMPTY:
image.paste(color.image, (86, 54), color.image)
# Current scores
scores = self.scores()
draw.text((67, 14), str(scores[Tile.WHITE]), font=font, fill="WHITE")
draw.text((67, 38), str(scores[Tile.BLACK]), font=font, fill="WHITE")
return image.convert("RGB")
def serialize(self) -> str:
return "|".join("".join(c.value for c in r) for r in self._board)
@staticmethod
def deserialize(buffer: str) -> Optional[Board]:
if not BUFFER_PATTERN.match(buffer):
return None
board = Board()
for r, tiles in enumerate(buffer.split("|")):
for c, tile in enumerate(tiles):
board._board[r][c] = Tile(tile)
return board
def rows_with_valid_moves(self, color: Tile) -> list[int]:
return list(row for row in range(BOARD_SIZE) if self.tiles_with_valid_move(color, row))
def tiles_with_valid_move(self, color: Tile, row: int) -> list[int]:
return list(col for col in range(BOARD_SIZE) if self._is_move_valid(color, row, col))
def _is_move_valid(self, color: Tile, row: int, col: int) -> bool:
do_i_return_true = False
if (self._board[row][col].is_occupied()):
return False
# right
for i in range(BOARD_SIZE - col - 1):
tile_to_check = self._board[row][col + (i + 1)]
if tile_to_check.is_occupied():
if tile_to_check == color.opposite():
do_i_return_true = True
elif do_i_return_true:
return True
else:
break
else:
break
do_i_return_true = False
# left
for i in range(col):
tile_to_check = self._board[row][col - (i + 1)]
if tile_to_check.is_occupied():
if tile_to_check == color.opposite():
do_i_return_true = True
elif do_i_return_true:
return True
else:
break
else:
break
do_i_return_true = False
# up
for i in range(row):
tile_to_check = self._board[row - (i + 1)][col]
if tile_to_check.is_occupied():
if tile_to_check == color.opposite():
do_i_return_true = True
elif do_i_return_true:
return True
else:
break
else:
break
do_i_return_true = False
# down
for i in range(BOARD_SIZE - row - 1):
tile_to_check = self._board[row + (i + 1)][col]
if tile_to_check.is_occupied():
if tile_to_check == color.opposite():
do_i_return_true = True
elif do_i_return_true:
return True
else:
break
else:
break
do_i_return_true = False
# up-right
for i in range(min(BOARD_SIZE - col - 1, row)):
tile_to_check = self._board[row - (i + 1)][col + (i + 1)]
if tile_to_check.is_occupied():
if tile_to_check == color.opposite():
do_i_return_true = True
elif do_i_return_true:
return True
else:
break
else:
break
do_i_return_true = False
# up-left
for i in range(min(col, row)):
tile_to_check = self._board[row - (i + 1)][col - (i + 1)]
if tile_to_check.is_occupied():
if tile_to_check == color.opposite():
do_i_return_true = True
elif do_i_return_true:
return True
else:
break
else:
break
do_i_return_true = False
# down-left
for i in range(min(col, BOARD_SIZE - row - 1)):
tile_to_check = self._board[row + (i + 1)][col - (i + 1)]
if tile_to_check.is_occupied():
if tile_to_check == color.opposite():
do_i_return_true = True
elif do_i_return_true:
return True
else:
break
else:
break
do_i_return_true = False
# down-right
for i in range(min(BOARD_SIZE - col - 1, BOARD_SIZE - row - 1)):
tile_to_check = self._board[row + (i + 1)][col + (i + 1)]
if tile_to_check.is_occupied():
if tile_to_check == color.opposite():
do_i_return_true = True
elif do_i_return_true:
return True
else:
break
else:
break
return False
def _flip_tiles(self, color: Tile, row: int, col: int):
# right
for i in range(BOARD_SIZE - col - 1):
tile_to_check = self._board[row][col + (i + 1)]
if tile_to_check.is_occupied():
if tile_to_check == color:
while i >= 0:
self._board[row][col + (i + 1)] = color
i -= 1
break
else:
break
# left
for i in range(col):
tile_to_check = self._board[row][col - (i + 1)]
if tile_to_check.is_occupied():
if tile_to_check == color:
while i >= 0:
self._board[row][col - (i + 1)] = color
i -= 1
break
else:
break
# up
for i in range(row):
tile_to_check = self._board[row - (i + 1)][col]
if tile_to_check.is_occupied():
if tile_to_check == color:
while i >= 0:
self._board[row - (i + 1)][col] = color
i -= 1
break
else:
break
# down
for i in range(BOARD_SIZE - row - 1):
tile_to_check = self._board[row + (i + 1)][col]
if tile_to_check.is_occupied():
if tile_to_check == color:
while i >= 0:
self._board[row + (i + 1)][col] = color
i -= 1
break
else:
break
# up-right
for i in range(min(BOARD_SIZE - col - 1, row)):
tile_to_check = self._board[row - (i + 1)][col + (i + 1)]
if tile_to_check.is_occupied():
if tile_to_check == color:
while i >= 0:
self._board[row - (i + 1)][col + (i + 1)] = color
i -= 1
break
else:
break
# up-left
for i in range(min(col, row)):
tile_to_check = self._board[row - (i + 1)][col - (i + 1)]
if tile_to_check.is_occupied():
if tile_to_check == color:
while i >= 0:
self._board[row - (i + 1)][col - (i + 1)] = color
i -= 1
break
else:
break
# down-left
for i in range(min(col, BOARD_SIZE - row - 1)):
tile_to_check = self._board[row + (i + 1)][col - (i + 1)]
if tile_to_check.is_occupied():
if tile_to_check == color:
while i >= 0:
self._board[row + (i + 1)][col - (i + 1)] = color
i -= 1
break
else:
break
# down-right
for i in range(min(BOARD_SIZE - col - 1, BOARD_SIZE - row - 1)):
tile_to_check = self._board[row + (i + 1)][col + (i + 1)]
if tile_to_check.is_occupied():
if tile_to_check == color:
while i >= 0:
self._board[row + (i + 1)][col + (i + 1)] = color
i -= 1
break
else:
break
def place(self, row: int, col: int, color: Tile) -> None:
if self._is_move_valid(color, row, col):
self._board[row][col] = color
self._flip_tiles(color, row, col)
def scores(self) -> dict[Tile, int]:
blacks = 0
whites = 0
for row in self._board:
for tile in row:
if tile == Tile.BLACK:
blacks += 1
elif tile == Tile.WHITE:
whites += 1
return {Tile.BLACK: blacks, Tile.WHITE: whites}
def winner(self) -> Tile:
# players wins when at least one condition is met:
score = self.scores()
# 1) the board has no empty tile
# 2) any of the players cannot make a valid move
if score[Tile.WHITE] + score[Tile.BLACK] == BOARD_SIZE * BOARD_SIZE or not self.rows_with_valid_moves(Tile.BLACK) or not self.rows_with_valid_moves(Tile.WHITE):
return max(score, key=score.get)
# 3) there is only one tile color on the board
if score[Tile.WHITE] == 0 or score[Tile.BLACK] == 0:
return min(score, key=score.get)
return Tile.EMPTY