-
Notifications
You must be signed in to change notification settings - Fork 0
/
Engine.py
178 lines (153 loc) · 5.87 KB
/
Engine.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
from kivy.clock import mainthread
from kivy.storage.dictstore import DictStore
from kivy.logger import Logger
from worker import WorkerThread
from sunfish.sunfish import (initial, parse, render, Position, Searcher, MATE_LOWER,MATE_UPPER)
import chess
import re
import time
#############################################################################
# Interface with the Sunfish engine directly, no xboard / uci
#############################################################################
class Engine:
def __init__(self, dispatch, resume=True):
self.__dispatch = dispatch
self.__worker = WorkerThread()
self.hist = [Position(initial, 0, (True,True), (True,True), 0, 0)]
self.board = chess.Board()
self.redo = []
self.searcher = Searcher()
self.store = DictStore('fisher.dat')
if resume:
self.load_game()
@mainthread
def dispatch(self, event, *args):
self.__dispatch(event, *args)
@property
def is_game_over(self):
return self.board.is_game_over()
@property
def moves(self):
return self.board.move_stack
# convert sunfish position into a list of pieces with their file and rank
def position(self, pos=None):
pos = pos or self.hist[-1]
pieces = []
for rank, row in enumerate(pos.board.split()):
for file, p in enumerate(row):
if p=='.':
continue
pieces.append('{}{}{}'.format(p, 'abcdefgh'[file], 8-rank))
return pieces
def validate(self, _move):
try:
move = chess.Move.from_uci(_move)
except:
return None
while True:
if move in self.board.legal_moves:
return move
if self.humans_turn:
break
# Sunfish move deemed illegal by python-chess? likely a promotion
assert not move.promotion
if not self.humans_turn:
move.promotion = chess.QUEEN
def apply_move(self, _move):
move = self.validate(self.decode(_move))
if move:
self.board.push(move)
self.hist.append(self.hist[-1].move(_move))
# after the machine's move, check if redo list still valid
if self.humans_turn:
self.check_redo()
self.dispatch('on_update', *self.status(), move.uci())
if not self.is_game_over:
return move
def input_move(self, move):
move = self.parse_and_validate(move)
if move and self.apply_move(move):
self.search_move()
def parse_and_validate(self, move):
if not self.is_game_over:
match = re.match('([a-h][1-8])'*2, move)
if match:
return parse(match.group(1)), parse(match.group(2))
def decode(self, move):
if not self.humans_turn:
move = [119 - m for m in move]
return '{}{}'.format(*(render(m) for m in move))
# Fire up the engine to look for a move -- in the background thread
def search_move(self):
def search():
start = time.time()
for _depth, move, _score in self.searcher.search(self.hist[-1], self.hist):
if time.time() - start > 1:
break
self.apply_move(move)
self.save_game()
self.__worker.send_message(search)
def status_message(self):
if self.board.is_stalemate():
return 'Stalemate'
if self.board.is_checkmate():
return 'Checkmate!'
if self.board.is_check():
return 'Check!'
return 'Your turn' if self.humans_turn else 'Thinking...'
@property
def humans_turn(self):
return self.board.turn == chess.WHITE
def status(self):
pos = self.hist[-1] if self.hist else None
if pos and not self.humans_turn:
pos = pos.rotate()
return self.position(pos), self.status_message()
def __can_use(self, moves_list):
return len(moves_list) > 0 and (self.humans_turn or self.is_game_over)
def can_undo(self):
return self.__can_use(self.moves)
def can_redo(self):
return self.__can_use(self.redo)
def check_redo(self):
if self.redo and self.last_move != self.redo[-1]:
# history took a different turn; redo list is invalid
self.redo.clear()
def undo_move(self):
assert self.can_undo()
assert len(self.hist) >= 2
# Assuming human plays white -- careful if/when implementing a "switch" feature
# Moves count should be even, unless we lost.
# Length of position history is odd because of initial empty position.
assert len(self.hist) % 2 or self.is_game_over
n = 1 if len(self.moves) % 2 else 2
self.hist = self.hist[:-n]
self.redo.append(self.moves[-n].uci())
while n > 0:
self.board.pop()
n -= 1
self.redo.append(self.last_move)
self.dispatch('on_update', *self.status(), self.last_move)
def redo_move(self):
assert self.redo
assert len(self.redo) % 2 == 0
move = self.redo.pop()
assert move == self.last_move
move = self.redo.pop()
self.input_move(move)
def start(self):
if not self.humans_turn:
self.search_move()
@property
def last_move(self):
return self.moves[-1].uci() if self.moves else None
def load_game(self):
Logger.debug('{}: load'.format(__name__))
if self.store.exists('game'):
data = self.store.get('game')
self.hist = data.get('hist', [])
for move in data.get('moves', []):
self.board.push(move)
def save_game(self):
Logger.debug('{}: save'.format(__name__))
self.store.put('game', hist=self.hist, moves=self.moves)