Skip to content

Commit 237053e

Browse files
committed
Just found itertools.compress
1 parent caaa30e commit 237053e

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

tools.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import itertools
12
import re
23

34
import sunfish
@@ -22,8 +23,9 @@ def gen_legal_moves(pos):
2223
Also the position after moving is included. '''
2324
for move in pos.gen_moves():
2425
pos1 = pos.move(move)
26+
# If we just checked for opponent moves capturing the king, we would miss
27+
# captures in case of illegal castling.
2528
if not any(pos1.value(m) >= sunfish.MATE_LOWER for m in pos1.gen_moves()):
26-
#if not any(pos1.board[j] == 'k' or j == pos1.kp for i,j in pos1.gen_moves()):
2729
yield move, pos1
2830

2931
def mrender(pos, m):
@@ -66,7 +68,7 @@ def renderSAN(pos, move):
6668
srcs = [a for (a,b),_ in gen_legal_moves(pos) if pos.board[a] == pos.board[i] and b == j]
6769
srcs_file = [a for a in srcs if (a - sunfish.A1) % 10 == (i - sunfish.A1) % 10]
6870
srcs_rank = [a for a in srcs if (a - sunfish.A1) // 10 == (i - sunfish.A1) // 10]
69-
assert len(srcs) > 0
71+
assert srcs, 'No moves compatible with {}'.format(move)
7072
if len(srcs) == 1: src = ''
7173
elif len(srcs_file) == 1: src = csrc[0]
7274
elif len(srcs_rank) == 1: src = csrc[1]
@@ -133,7 +135,7 @@ def renderFEN(pos, half_move_clock=0, full_move_clock=1):
133135
pos = pos.rotate()
134136
board = '/'.join(pos.board.split())
135137
board = re.sub(r'\.+', (lambda m: str(len(m.group(0)))), board)
136-
castling = ''.join(c for c, t in zip('KQkq', pos.wc[::-1]+pos.bc) if t) or '-'
138+
castling = ''.join(itertools.compress('KQkq', pos.wc[::-1]+pos.bc)) or '-'
137139
ep = sunfish.render(pos.ep) if not pos.board[pos.ep].isspace() else '-'
138140
clock = '{} {}'.format(half_move_clock, full_move_clock)
139141
return ' '.join((board, color, castling, ep, clock))

0 commit comments

Comments
 (0)