-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_chess.py
More file actions
executable file
·2424 lines (2197 loc) · 78.9 KB
/
reverse_chess.py
File metadata and controls
executable file
·2424 lines (2197 loc) · 78.9 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
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
"""play chess in reverse"""
from pyautogui import prompt
import time
import sys
import numpy as np
# pop-up box
from tkinter import *
from tkinter import messagebox
import tkinter
#Tk().wm_withdraw() #to hide the main window
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame
# modules
from givebox import givebox
from chessassets import IMAGES, PTYPES, offboard_count, onboard_count
from tenants import tenant_matching # check this
COMPUTER_ONLY = True # computer plays itself
COMPUTER_ONLY = False
ONLY_HUMAN = True # human v. human (on the same computer, no network play); useful for debugging
ONLY_HUMAN = False
DRAW = False
DRAW = True
GENETICS = True
GENETICS = False
if GENETICS:
import pygad
if COMPUTER_ONLY:
DRAW = False
DRAW = True
try:
PROFILE = profile # throws an exception when PROFILE isn't defined
except NameError:
def profile(arg2):
"""Line profiler default."""
return arg2
PROFILE = profile
# derived from:
# https://levelup.gitconnected.com/chess-python-ca4532c7f5a4
# TODO:
# features:
# menu (random ai) # https://pygame-menu.readthedocs.io/en/4.3.6/
# custom starting config
# show promoted on the icon
# bugs:
# highlighting is busted
# does the computer demote?
# two times it says legal when the move is not legal, which could cause a problem:
## pawn un-taking a piece, which then results in no legal moves
## general movement which results in no legal moves.
## general gifts which result in no legal moves
### In general the game assumes all your moves which are legal do not cause your opponent to have no legal moves. this just causes more draws, since the only time this mis-count causes a problem is if it results in no legal moves for you, which results in a draw. The general solution to this problem is a proof by construction that the other team can get their pieces home from the proposed board configuration. this seems to imply we would need to search the move tree deeper than may be feasible. The point of the rule is to prevent games with small numbers of moves. Given that draws resulting from this case seem to be small in number, it does not currently seem worth the trouble of implementing such a search. Even a small depth search of the move tree would probably decrease the number of draws a lot, so this may be added at some point depending on player feedback.
global BOARD
global SNAP
global REVERSE_CHECK
REVERSE_CHECK = None
BOARD = [[None for i in range(8)] for j in range(8)]
BOARD = np.array(BOARD)
SNAP = None
WIDTH = 800
NUM_GENES = 100
WIN = pygame.display.set_mode((WIDTH, WIDTH))
pygame.display.set_caption('Reverse Chess: "It\'s worse"')
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREY = (128, 128, 128)
YELLOW = (204, 204, 0)
BLUE = (50, 255, 255)
GREEN = (50, 164, 49)
## Creates a chess piece class that shows what team a piece is on, what type of piece it is and whether or not it can be killed by another selected piece.
class Piece:
def __init__(self, team, ptype, image, home, ontheboard=False):
"""init"""
# params used to check for draws:
self.ptype = ptype
self.team = team
self.locked = False
self.promoted = False
self.sq_color = None
# internal parameters
self.attribute_str = None
self.ontheboard = ontheboard
#self.pre_reverse_check = False
#self.reverse_check = False
self.image = image
self.pos = None
self.image = None
self.x = None
self.y = None
self.update_image()
self.home = home
@PROFILE
def attributes(self):
"""get a string describing the piece"""
attributes = [self.team, self.ptype, self.promoted, self.locked, self.sq_color]
encode_str = ''
for k in attributes:
encode_str += '@'+str(k)+'@'
self.attribute_str = encode_str
return self.attribute_str
def square_color(self):
"""set the square color (bishop identity)"""
assert self.pos is not None
assert self.ontheboard
self.sq_color = square_color(self.pos)
self.attributes()
return self.sq_color
def ident(self):
"""print identifying information"""
retstr = ('id:', self.team, self.ptype, self.pos, self.promoted, self.locked)
print(retstr)
return retstr
def is_home(self):
"""check if piece is home"""
row, col = self.pos
homerows, homecols = self.home
ret = row in homerows and col in homecols
chk = not self.promoted
ret = ret and chk
if not ret:
self.unlock()
return ret
def move_home(self):
"""sends the piece home (which should be unambiguous)"""
assert self.ptype in ('k', 'r'), self.ptype
assert self.ontheboard, "do not send pieces home from the void"
row, col = self.home
row = row[0]
col = col[0]
newpos = (row, col)
self.update(newpos)
def lock(self):
"""prevent the piece from moving"""
assert self.ontheboard, "sanity check"
assert not self.promoted, "sanity check"
self.locked = True
self.attributes()
def unlock(self):
"""prevent the piece from moving"""
assert self.ontheboard, "sanity check"
self.locked = False
self.attributes()
def update_image(self, promoted=False):
"""update image to reflect ptype"""
im1 = IMAGES[(self.team, self.ptype, promoted)]
self.image = pygame.image.load(im1)
def demote(self):
"""change promoted pawn back to pawn"""
if self.promoted:
self.ptype = 'p'
self.update_image()
self.promoted = False
self.update_image()
self.attributes()
def promote(self, ptype_new):
"""change promoted pawn back to pawn"""
if not self.promoted:
assert not ptype_new == 'p', ptype_new
assert ptype_new != self.ptype, ptype_new
self.ptype = ptype_new
self.update_image()
self.promoted = True
self.update_image(True)
self.unlock()
self.attributes()
def pawn_is_home(self):
"""is the piece a pawn that can no longer move?"""
ret = self.ptype == 'p'
chk = self.is_home()
ret = ret and chk
if ret:
self.lock()
else:
self.unlock()
return ret
@PROFILE
def update(self, newpos, ignore_lock=False):
"""update the position of a piece on the board"""
global BOARD
if not ignore_lock:
assert not self.locked, (self.ptype, self.pos, self.team)
if self.ontheboard:
assert not BOARD[newpos]
oldpos = (self.pos[0], self.pos[1])
self.pos = (newpos[0], newpos[1])
self.update_xy(newpos, ignore_lock=ignore_lock)
BOARD[newpos] = self
if oldpos != newpos:
BOARD[oldpos] = None
else:
self.place(newpos, ignore_lock=ignore_lock)
# check if the piece (pawn) is now locked
if not ignore_lock:
self.pawn_is_home()
@PROFILE
def place(self, pos, ignore_lock=False):
"""place the piece onto the board"""
global BOARD
if not ignore_lock:
assert not self.locked, (self.ptype, self.team)
assert not self.ontheboard, self.ident()
assert not BOARD[pos], (BOARD, pos)
self.ontheboard = True
self.pos = pos
self.update(pos, ignore_lock=ignore_lock)
self.draw()
self.square_color()
self.attributes()
@PROFILE
def remove(self):
"""remove piece from the board"""
global BOARD
assert self.ontheboard
assert self == BOARD[self.pos], (self, pos, BOARD[pos])
pos = self.pos
BOARD[pos] = None
self.ontheboard = False
self.pos = None
self.x = None
self.y = None
self.sq_color = None
self.locked = False
self.demote()
if not DRAW:
def draw(self):
pass
else:
def draw(self):
"""draws the piece onto the board"""
pos = (self.x, self.y)
assert pos[0] is not None, pos
WIN.blit(self.image, pos)
@PROFILE
def update_xy(self, pos, ignore_lock=False):
"""converts row, column -> x, y
(row, col -> position)"""
if not ignore_lock:
assert not self.locked, (self.ptype, self.pos, self.team)
width = WIDTH // 8 # width = 100
assert width == 100, (width, "sanity check")
row, col = pos
self.y = int(row * width)
self.x = int(col * width)
### DRAW
class Node: # chess squares
def __init__(self, row, col, width):
self.row = row
self.col = col
self.x = int(row * width)
self.y = int(col * width)
self.color = WHITE
#self.occupied = None
def draw(self):
"""draw the rectangle and piece"""
self.draw_rect()
self.draw_piece_here()
if not DRAW:
def draw_rect(self):
pass
def draw_piece_here(self):
pass
else:
def draw_rect(self):
"""draw rectangle of a certain fill color, node.color"""
pygame.draw.rect(WIN, self.color, (self.y, self.x, int(WIDTH / 8), int(WIDTH / 8)))
def draw_piece_here(self):
"""draw the piece occupying this node"""
global BOARD
piece = BOARD[(self.row, self.col)]
if piece is not None:
#print("drawing at node:", self.row, self.col, self.x, self.y)
#print(piece.ptype, piece.ontheboard, piece.pos)
piece.draw()
@PROFILE
def make_grid(rows, width):
"""creates the visual grid; run once"""
if not GENETICS:
assert not make_grid.hasrun, "sanity check"
grid = []
gap = WIDTH // rows
#print(gap)
for i in range(rows):
grid.append([])
for j in range(rows):
node = Node(i, j, gap)
grid[i].append(node)
if (i+j)%2 == 1:
grid[i][j].color = GREY
make_grid.hasrun = True
return grid
make_grid.hasrun = False
if not DRAW:
def draw_grid(rows, width):
pass
else:
def draw_grid(rows, width):
"""draws the outlines of the chess squares"""
gap = width // 8
for i in range(rows):
pygame.draw.line(WIN, BLACK, (0, i * gap), (width, i * gap))
for j in range(rows):
pygame.draw.line(WIN, BLACK, (j * gap, 0), (j * gap, width))
@PROFILE
def remove_highlight(grid, skip_color_pos=None):
"""reverts the grid square colors"""
for i in range(len(grid)):
for j in range(len(grid[0])):
if (i,j) == skip_color_pos:
continue
grid[i][j].color = square_color((i, j))
return grid
def square_color(pos):
"""get the color (white or grey) of the square
useful for checking bishop color"""
row, col = pos
return GREY if (row+col)%2 else WHITE
if not DRAW:
def highlight(pos, grid, color):
i, j = pos
node = grid[i][j]
node.color = color
else:
def highlight(pos, grid, color):
"""reverts the grid square colors"""
i, j = pos
node = grid[i][j]
node.color = color
instant_draw(node)
if not DRAW:
def instant_draw(node, rows=8, width=WIDTH):
pass
else:
def instant_draw(node, rows=8, width=WIDTH):
"""instantly re-draw the square"""
draw_grid(rows, width) # is this call necessary?
node.draw() # draw the rectangle, and piece
pygame.display.update()
if not DRAW:
def update_display(grid, rows, width):
pass
else:
def update_display(grid, rows, width):
"""update display"""
# loop over nodes in grid
for row in grid:
for node in row:
node.draw()
draw_grid(rows, width)
pygame.display.update()
### END DRAW
@PROFILE
def board_snapshot():
"""convert board to snapshot for
three/five fold repetition rule check"""
global BOARD
ret = [[0 for i in range(8)] for j in range(8)]
assert len(BOARD) == 8, len(BOARD)
for i, row in enumerate(BOARD):
#assert len(row) == 8, row
for j, piece in enumerate(row):
if piece is None:
ret[i][j] = 'None'
else:
ret[i][j] = piece.attribute_str
ret = str(ret)
return ret
### MOUSE LOGIC
def mouse():
"""get input from user via mouse;
convert to which part of chess grid user is clicking on"""
found = False
leftright = None
while not found or leftright not in ('l', 'r', None):
pygame.time.delay(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
shift = pygame.key.get_mods() & pygame.KMOD_SHIFT
xy = pygame.mouse.get_pos()
row, col = xy_to_rowcol(xy, WIDTH)
leftright = 'l' if event.button == 1 else leftright
leftright = 'r' if (event.button == 3 or shift) else leftright
found = True
break
return (row, col), leftright
@PROFILE
def xy_to_rowcol(xy, WIDTH):
"""converts screen position to row, column"""
interval = WIDTH / 8
x, y = xy
columns = x // interval
rows = y // interval
return int(rows), int(columns)
### END MOUSE LOGIC
def Pieces(team):
"""Create all the pieces for a team"""
ret = []
count = 0
for ptype in PTYPES:
if ptype == 'p':
for _ in range(8):
home = ((tuple([1]) if team == 'b' else tuple([6])),
tuple(range(8)))
piece = Piece(team, ptype, IMAGES[(team, ptype, False)], home)
ret.append(piece)
#piece = ret[-1]
#piece.place((3,3) if team == 'w' else (5,5))
elif ptype in ['r', 'b', 'n']:
for i in range(2):
if ptype == 'r':
home = (tuple([0 if team == 'b' else 7]), (0,7))
elif ptype == 'n':
home = (tuple([0 if team == 'b' else 7]), (1,6))
else:
home = (tuple([0 if team == 'b' else 7]), (2,5))
piece = Piece(team, ptype, IMAGES[(team, ptype, False)], home)
ret.append(piece)
elif ptype == 'k':
count += 1
home = (tuple([7 if team == 'w' else 0]), tuple([4]))
piece = Piece(team, ptype, IMAGES[(team, ptype, False)], home)
piece.place((3,5) if team == 'b' else (4,3))
assert piece.ontheboard
ret.append(piece)
else:
assert ptype == 'q', ptype
home = (tuple([7 if team == 'w' else 0]), tuple([3]))
piece = Piece(team, ptype, IMAGES[(team, ptype, False)], home)
ret.append(piece)
assert count == 1, count
return ret
## Creates instances of chess pieces, so far we got: pawn, king, rook and bishop
## The first parameter defines what team its on and the second, what type of piece it is
global bpieces
global wpieces
bpieces = Pieces('b')
wpieces = Pieces('w')
@PROFILE
def bishop_wall_check(team, ignore_lock=False):
"""weak check to see if the bishop can get home
"""
global BOARD
global wpieces
global bpieces
pieces = bpieces if team == 'b' else wpieces
left = [(6, 1), (6, 3)] if team == 'w' else [(1, 1), (1, 3)]
right = [(6, 4), (6, 6)] if team == 'w' else [(1, 4), (1, 6)]
lbishop = (7, 2) if team == 'w' else (0, 2)
rbishop = (7, 5) if team == 'w' else (0, 5)
legal = True
lhome = False # assume bishop is not on the board
rhome = False
home_count = 0
for piece in pieces:
if not piece.ontheboard:
continue
if not piece.ptype == 'b':
continue
if piece.promoted:
continue
# found a bishop
if piece.is_home():
_, col = piece.pos
if col == 2:
lhome = True
else:
rhome = True
problems = []
if not lhome:
count = 0
for pos in left:
piece = BOARD[pos]
if piece is None:
continue
if piece.team != team:
continue
if not piece.is_home():
continue
assert piece.ptype == 'p' and not piece.promoted, piece.ident()
if not ignore_lock:
assert piece.locked, piece.ident()
problems.append(pos)
count += 1
legal = count < 2
if legal and not rhome:
count = 0
for pos in right:
piece = BOARD[pos]
if piece is None:
continue
if piece.team != team:
continue
if not piece.is_home():
continue
problems.append(pos)
count += 1
assert piece.ptype == 'p' and not piece.promoted, piece.ident()
if not ignore_lock:
assert piece.locked, piece.ident()
legal = count < 2
if not legal:
print("rhome", rhome)
print("lhome", lhome)
print("problem positions:", problems, "for", team)
return legal
@PROFILE
def king_check_pawn_is_home(team, newpos=None):
"""pawns on their own home row should not be able to
check the king of the other team"""
global wpieces
global bpieces
oteam = other_team(team)
pieces = wpieces if oteam == 'w' else bpieces
legal = True
save = None
for piece in pieces:
if not legal:
break
if not piece.ontheboard or piece.ptype != 'p':
continue
pawn = piece
pawn.is_home() # set locked, if it hasn't been set already
attacking = newpos if newpos is not None else find_king(team).pos
if check_attacking(pawn, attacking):
legal = not pawn.locked
if not legal:
save = pawn
if save is not None:
pass
#print("check pawn debug:")
#save.ident()
return legal
@PROFILE
def other_team(team):
"""return the other team"""
assert team in ('w', 'b'), team
return 'w' if team == 'b' else 'b'
@PROFILE
def allonboard(pieces):
"""checks to see if all pieces in list are on the board"""
ret = True
for piece in pieces:
if not ret:
break
ret = ret and piece.ontheboard
return ret
@PROFILE
def allhome(pieces):
"""check to see if all pieces home"""
ret = None
for piece in pieces:
if not piece.ontheboard:
ret = False
else:
ret = piece.is_home()
if not ret:
break
assert ret is not None, pieces
return ret
@PROFILE
def check_winning(team_pieces):
"""Check board to see if team is winning
goal for team is to reset the board
to the starting chess position for team
also, all the pieces must be on the board
(you must give back all your opponent's pieces
before you can end the game)
"""
global wpieces
global bpieces
team = team_pieces[0].team
ret = allonboard(bpieces) and allonboard(wpieces)
ret = ret and allhome(team_pieces)
# redundant check, for safety
for piece in team_pieces:
if not ret:
break
if piece.promoted:
ret = False
break
row, col = piece.pos
ptype = piece.ptype
# pawn check
if pytpe == 'p':
if team == 'b' and row != 6:
ret = False
if team == 'w' and row != 1:
ret = False
continue
## check rest of pieces
# front/back row check
if team == 'b':
if row != 7:
ret = False
break
elif team == 'w':
if row != 0:
ret = False
break
# final type check, via columns
if ptype == 'r':
if col not in [0, 7]:
ret = False
break
elif ptype == 'n':
if col not in [1, 6]:
ret = False
break
elif ptype == 'b':
if col not in [2, 5]:
ret = False
break
elif ptype == 'q':
if col != 3:
ret = False
break
elif ptype == 'k':
if col != 4:
ret = False
break
return ret
@PROFILE
def pawn_spawn_home_check(pawn, spawn_pos, newpos=None):
"""pawn cannot spawn at on its home row attacking the opposite king
this would give that king's team an instant win, and wouldn't make sense
due to the king not being able to ever be checked by a pawn on its home row
in regular chess
"""
team = pawn.team
oteam = other_team(team)
king = find_king(oteam)
row = spawn_pos[0]
if team == 'b':
chk = row != 1
else:
chk = row != 6
if newpos == None:
legal = not pawn_attacking(team, spawn_pos, king.pos)
else:
legal = not pawn_attacking(team, spawn_pos, newpos)
return legal or chk
@PROFILE
def check_bishop_color(bishop, spawn_pos):
"""check the bishop's color"""
assert bishop.ptype == 'b'
team = bishop.team
global wpieces
global bpieces
pieces = bpieces if team == 'b' else wpieces
color = square_color(spawn_pos)
legal = True
for piece in pieces:
if not legal:
break
if not piece.ontheboard:
continue
if piece.ptype != 'b' or piece.promoted:
continue
legal = piece.sq_color != color
legal = legal or bishop.promoted
return legal
@PROFILE
def check_legal_give(give_params, piece_to_move, newpos):
"""Check that the piece given back is
a) placed properly and
b) comes from the available set"""
global BOARD
pos = piece_to_move.pos
spawn_pos = give_params.spawn_pos
reason = ""
# check that the space is unoccupied
legal = BOARD[spawn_pos] is None or spawn_pos == pos
# check that the piece to give back is not on the board
legal = legal and not give_params.spawn_piece.ontheboard
if give_params.spawn_piece.ptype == 'b':
legal = legal and check_bishop_color(give_params.spawn_piece, spawn_pos)
if not legal:
reason = "bishop color dupe"
# legal moves check; premove
legal_count, only_legal = count_legal(give_params.spawn_piece.team)
oldpos = piece_to_move.pos
promoted = give_params.spawn_piece.promoted
piece_to_move.update(newpos, ignore_lock=True)
give_params.spawn_piece.place(spawn_pos, ignore_lock=True)
legal_count2, only_legal2 = count_legal(give_params.spawn_piece.team)
if only_legal and not only_legal2:
legal = False
reason = 'no legal moves for '+full(give_params.spawn_piece.team)+"."
# bishop wall check
if legal:
legal = bishop_wall_check(give_params.spawn_piece.team, ignore_lock=True)
if not legal:
print("illegal gift: no walling off the other team's bishop squares.")
give_params.spawn_piece.remove()
give_params.spawn_piece.promoted = promoted
piece_to_move.update(oldpos, ignore_lock=True)
# can the pawns get home?
if give_params.spawn_piece.ptype == 'p' and legal and give_params.promote_type is None:
pawn = give_params.spawn_piece
legal = pawn_spawn_home_check(pawn, spawn_pos, newpos=(
newpos if piece_to_move.ptype=='k' else None))
if not legal:
reason = "locked pawn attacking king"
if legal:
legal = pawn_scan(pawn.team, spawn_pos)
if not legal:
reason = "pawn scan fail"
# don't allow pawn spawn on the same row as their king
if legal:
row_spawn = spawn_pos[0]
if pawn.team == 'b':
legal = row_spawn != 0
else:
legal = row_spawn != 7
if not legal:
reason = "no spawning pawns on back row"
if not legal and not GENETICS:
print("illegal gift:", reason)
return legal
@PROFILE
def pawn_scan(team, pos=None):
"""can the pawns of team get home?"""
global wpieces
global bpieces
pieces = bpieces if team == 'b' else wpieces
opieces = wpieces if team == 'b' else bpieces
pawn_list = []
locked_cols = []
oteam = other_team(team)
for piece in pieces:
if piece.ontheboard and piece.ptype == 'p' and not piece.promoted:
if piece.locked:
locked_cols.append(piece.pos[1])
else:
pawn_list.append(piece)
if not pawn_list:
return True # no need to check yet
count = 0
opencols = set(range(8))-set(locked_cols)
reachable = {}
col_diffs = {}
for idx, pawn in enumerate(pawn_list):
reachable[idx] = set()
row, col = pawn.pos
col_diffs[idx] = {}
for col1 in opencols:
cold = abs(col1-col)
home_row = pawn.home[0][0]
rowd = abs(row-home_row)
if rowd >= cold:
reachable[idx].add(col1)
col_diffs[idx][col1] = cold
# add the pawn we are just now spawning
if pos is not None:
reachable[len(pawn_list)] = set()
row, col = pos
home_row = 1 if team == 'b' else 6
col_diffs[len(pawn_list)] = {}
for col1 in opencols:
cold = abs(col1-col)
rowd = abs(row-home_row)
if rowd >= cold:
reachable[len(pawn_list)].add(col1)
col_diffs[len(pawn_list)][col1] = cold
# and now we brute force the solution using recursion
# we try solution columns in order of how far away they are
# closer first
#solution = tenant_matching(reachable, mins=col_diffs)
solution = tenant_matching(col_diffs)
if len(reachable) == 1 and reachable[list(reachable)[0]]:
assert solution, (solution, reachable)
# now we check to make sure there are enough pieces off the board
# do to our sorting, we can read off this minimum from the solution
if solution:
min_off_board = 0
for pawn in solution:
min_off_board += col_diffs[pawn][solution[pawn]]
if min_off_board > sum(offboard_count(opieces).values()):
if not GENETICS:
print("not enough pieces off board for pawns to get home")
print(min_off_board, sum(offboard_count(opieces).values()),
offboard_count(opieces))
solution = None
if not solution:
if not GENETICS:
print("no solution, pawn scan. pawn list:")
for idx, pawn in enumerate(pawn_list):
pawn.ident()
print("idx, reachable", idx, reachable[idx])
print("reachable", reachable, tenant_matching(col_diffs))
print("col diffs", col_diffs)
print("END no solution")
legal = bool(solution)
return legal
@PROFILE
def king_around(team, newpos):
"""check squares around newpos for king of other team
we aren't allowed to move our king next to the other king in chess,
so we aren't allowed to do so in reverse chess either.
"""
global BOARD
origin = (newpos[0]-1, newpos[1]-1)
origin = np.asarray(origin)
for col in range(3):
for row in range(3):
if col == 1 and row == 1: # skip the king's square
continue
around_pos = origin+np.array([row,col]) # square of other king
around_pos = tuple(around_pos)
piece = BOARD[around_pos]
if piece is None:
continue
if piece.team == other_team(team) and piece.ptype == 'k':
return False
return True
@PROFILE
def discovered_check_check(piece, newpos, demote=False):
"""checking the other king is not allowed,
as in reverse this would mean the other king
is moving into check.
"""
global BOARD
# pre-move the piece to perform check
assert piece.pos != newpos, (piece.pos, newpos)
oldpos = piece.pos
piece.update(newpos, ignore_lock=True)
old_ptype = piece.ptype
if demote:
piece.demote()
ret = False
for row in BOARD:
if ret:
break
for piece2 in row:
if piece2 is None:
continue
if piece2.team != piece.team:
continue
if ret:
break
ret = attacking_king(piece2)
discovery = piece2
if ret:
pass
#print("illegal discovery:", discovery.ptype, discovery.pos)
# undo pre-move
piece.update(oldpos, ignore_lock=True)
if demote and piece.ptype != old_ptype:
piece.promote(old_ptype)
return ret
@PROFILE
def attacking_king(piece, newpos=None):
"""Check if piece is attacking king of other team"""
global BOARD
assert piece is not None
team = piece.team
oteam = other_team(team)
# find other king
piece2 = find_king(oteam)
assert id(piece) != id(piece2), "sanity check"
assert piece.pos != piece2.pos, (piece.pos, piece.ident(), piece2.ident(), BOARD[piece.pos].ident())
return check_attacking(piece, piece2.pos, newpos=newpos)
@PROFILE
def find_king(team):
"""find king on board of given team"""
global BOARD
if team in find_king.cache:
return find_king.cache[team]
else:
for row in BOARD:
for piece in row:
if piece is None:
continue
if piece.ptype == 'k' and piece.team == team:
find_king.cache[team] = piece
return piece
assert None, "king not found on board"
find_king.cache = {}
@PROFILE
def rook_attacking(pos_qr, pos):
"""check if the rook is attacking pos"""
row, col = pos
row_qr, col_qr = pos_qr # position of attacking piece
ret = False
if row == row_qr or col == col_qr:
if not check_impinging(pos_qr, pos):
ret = True
return ret
@PROFILE