-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmouv.py
458 lines (353 loc) · 9.61 KB
/
mouv.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
import string
from constants import REVERSE, Dir
import copy
class Movement:
@classmethod
def coords_to_index(cls, coords):
if isinstance(coords, bytes):
coords = coords.decode()
if not isinstance(coords, str):
coords = cls.index_to_coords(*coords)
x, y = coords[0], coords[1:]
x, y = string.ascii_lowercase.index(x), int(y)-1
if x >= 8 and y >= 8: # >= i / Red
x = 11 - x # = 4 - (x - 9) <=> lkji => abcd
elif x >= 8 and 4 <= y <= 8: # Black
x = x - 4 # ijkl => efgh
return x, y # x= lettre, y = chiffre
@classmethod
def index_to_coords(cls, x, y=None, two_players=False):
if y is None:
if isinstance(x, Vec2):
x, y = x.tuple()
elif isinstance(x, tuple):
x, y = x
else:
raise ValueError('y must be specified')
if y <= 3:
# White zone
pass # Don't change anything
elif y <= 7:
# Black zone
if x <= 3:
# White side
pass # Don't change anything
else:
# Red side
if not two_players:
x = x + 4 # efgh => ijkl
else:
# Red zone
if x <= 3:
# Black side
x = 11 - x # abcd => lkji
else:
# White side
pass # Don't change anything
return ''.join((string.ascii_lowercase[x], str(y+1)))
def get_straight_line(self, coords, direction, skipped_first=False, origin=None):
# Renvoie une liste de coordonnées dans une direction donnée
# S'arrête lorsque l'on atteint un mur ou une autre pièce, en ignorant la première case
if not isinstance(coords, str):
coords = self.index_to_coords(*coords)
# Check limits
if not self.validate_coordinates(coords):
# Could be invalid coordinate, but it can still be mapped to a correct one
return []
# Check cell
if isinstance(self.board, list):
b = self
else:
b = self.board
# if not skipped_first and b[coords] is not None:
# return []
if origin is not None and b[coords] is not None:
return [coords]
adj = dict(self.get_adjacent(coords))
if origin is not None:
for dir, cells in adj.items():
if origin == cells:
break
else:
# wtf?
raise Exception
next_cell = adj.get(REVERSE[dir], None)
else:
next_cell = adj.get(direction, None)
if next_cell is None:
return [coords]
out = [coords] + self.get_straight_line(
next_cell, direction, skipped_first=True, origin=coords
)
return out
def get_adjacent(self, coords):
if coords is None:
return
if isinstance(coords, str):
x, y = self.coords_to_index(coords)
else:
x, y = coords
for dir, (dx, dy) in [(Dir.DOWN, (-1, 0)), (Dir.UP, (1, 0)), (Dir.RIGHT, (0, -1)), (Dir.LEFT, (0, 1))]:
nx, ny = x+dx, y+dy
# region: bounds
if not (0 <= nx < 8):
# Out of bounds
continue
if y == 0 and dy == -1:
# Out of bounds, behind white
continue
if y == 7 and dy == 1:
# Out of bounds, behind black
continue
if y == 11 and dy == 1:
# Out of bounds, behind red
continue
# endregion
# region: Red borders
if y == 8 and dy == -1:
# Red zone outer border
if 4 <= x:
# White side
ny = 3
else:
# Black side
nx, ny = 7-nx, 4
if y >= 8:
# Red zone inner border
if x == 4 and dx == -1: # == e
# White side
nx = 8
elif x == 8 and dx == 1:
# Black side
nx = 4
# endregion
# region: White border
if y == 3 and x >= 4 and dy == 1:
# Red side
ny += 4
# endregion
# region: Black border
if y == 4 and x >= 4 and dy == -1:
# Red side
ny = 8
nx = 7-nx
# endregion
out = self.index_to_coords(nx, ny)
yield (dir, out)
def get_diagonal_line(self, coords, direction, origin=None):
# Renvoie une liste de coordonnées dans une direction donnée, en diagonale
# S'arrête lorsque l'on atteint un mur ou une autre pièce, en ignorant la première case
if not isinstance(coords, str):
coords = self.index_to_coords(*coords)
# Check limits
if not self.validate_coordinates(coords):
# Could be invalid coordinate, but it can still be mapped to a correct one
return []
# Check cell
if isinstance(self.board, list):
b = self
else:
b = self.board
if origin is not None and b[coords] is not None:
return [coords]
adj = dict(self.get_adjacent_diagonale(coords))
if origin is not None:
for dir, cells in adj.items():
if origin in cells:
break
else:
# wtf?
raise Exception
next_cells = adj.get(REVERSE[dir], [])
else:
next_cells = adj.get(direction, [])
out = [coords]
for next_cell in next_cells:
out += self.get_diagonal_line(
next_cell, None, coords
)
return out
def get_adjacent_diagonale(self, coords):
x, y = self.coords_to_index(coords)
for dir, (dx, dy) in [
(Dir.DOWN, (-1, 1)),
(Dir.UP, (1, -1)),
(Dir.LEFT, (1, 1)),
(Dir.RIGHT, (-1, -1)),
]:
nx, ny = x + dx, y + dy
# region: bounds
if not (0 <= nx < 8):
# Out of bounds
continue
if y == 0 and dy == -1:
# Out of bounds, behind white
continue
if y == 7 and dy == 1:
# Out of bounds, behind black
continue
if y == 11 and dy == 1:
# Out of bounds, behind red
continue
# endregion
# region: Center
center = {3, 4, 7, 8}
if {x, y, nx, ny} <= center:
# Crossing the center
if (x - y) % 4 == 0:
# Gray cross
cross = {"d4", "e9", "i5"} # Gray cross
else:
cross = {"e4", "d5", "i9"} # White cross
yield (dir, list(cross - {coords}))
continue
# endregion
# region: Red borders
if y == 8 and dy == -1:
# Red zone outer border
if 4 <= x:
# White side
ny = 3
else:
# Black side
nx, ny = 7 - nx, 4
if y >= 8:
# Red zone inner border
if x == 4 and dx == -1: # == e
# White side
nx = 8
elif x == 8 and dx == 1:
# Black side
nx = 4
# endregion
# region: White border
if y == 3 and x >= 4 and dy == 1:
# Red side
ny += 4
# endregion
# region: Black border
if y == 4 and x >= 4 and dy == -1:
# Red side
ny = 8
nx = 7 - nx
# endregion
out = self.index_to_coords(nx, ny)
yield (dir, [out])
def validate_coordinates(self, coords):
# Check if coordinates are actually on the board
# Returns bool
if not isinstance(coords, str):
coords = self.index_to_coords(*coords)
x, y = coords[0], coords[1:]
x, y = string.ascii_lowercase.index(x), int(y)-1
if 0 <= x < 4:
if 0 <= y < 8:
return True
elif x < 8:
if 0 <= y < 4 or 8 <= y < 12:
return True
elif x < 12:
if 4 <= y < 12:
return True
return False
def is_check(self, board, team, src = None, dest = None ):
#check if a team is in check
if src is None and dest is None:
#find the king
king = None
for piece in board.iterate():
if piece != None:
if piece.type == 'King' and piece.team == team:
king = piece # Only one king for each team
if king is None:
# The king was eaten, that's a checkmate
return True
#check if the king is in check
cell = self.index_to_coords(*king.pos)
for piece in board.iterate():
if piece.team != team:
if piece.pos is not None:
for posibilities in piece.list_moves():
if posibilities == cell:
return True
return False
else:
# piece = board[src]
# if piece is not None and piece.type == 'King' and piece.team == team:
# # Yeah, sometimes the bot tries to eat the king
# return True
new_board = board.copy()
new_board.move(src, dest)
return self.is_check(new_board, team)
def is_checkmate(self, team):
for piece in self.iterate():
for move in piece.list_moves():
if piece.team == team:
new_board = self.copy()
new_board.move(piece.pos, move)
if not self.is_check(new_board, team):
return False # There is a move that can be made
return True
checkmate = False
#find the king
for piece in self.iterate():
if piece != None:
if piece.type == 'King' and piece.team == team:
king = piece.pos
#wich pieces are making check
make_check = []
for piece in self.iterate():
if piece != None and piece.type != 'King' and piece.team != king.team and king in piece.list_moves():
make_check.append(piece.pos)
# the king can move to a safe place ?
for move in king.list_moves():
new_board = self.copy()
new_board.move(king.pos, move, board = new_board)
if not self.is_check(new_board, team):
return checkmate
#find all the pieces that can move to block the check
list_pieces = []
for piece in self.iterate():
if piece != None and piece.team == king.team:
for move in piece.list_moves():
new_board = self.copy()
new_board.move(piece.pos, move, board = new_board)
if not self.is_check(new_board, king.team):
list_pieces.append(piece.pos)
if list_pieces == []:
checkmate = True
return checkmate
else:
return checkmate
class Vec2:
"""Helper to work with coordinates"""
def __init__(self, x, y=None):
if y is None:
x, y = x
self.x, self.y = x, y
def __add__(self, other):
if isinstance(other, tuple):
other = Vec2(other)
return Vec2(self.x+other.x, self.y+other.y)
def __sub__(self, other):
if isinstance(other, tuple):
other = Vec2(other)
return Vec2(self.x-other.x, self.y-other.y)
def __neg__(self):
return Vec2(-self.x, -self.y)
def __mul__(self, k):
return Vec2(self.x*k, self.y*k)
def __truediv__(self, k):
return Vec2(self.x/k, self.y/k)
def __repr__(self):
return f'({self.x}, {self.y})'
def __iter__(self):
return iter((self.x, self.y))
def __lt__(self, other):
if isinstance(other, tuple):
other = Vec2(other)
return self.x < other.x and self.y < other.y
def tuple(self):
return self.x, self.y
def copy(self):
return Vec2(self.x, self.y)