-
Notifications
You must be signed in to change notification settings - Fork 159
/
play.py
257 lines (196 loc) · 7.07 KB
/
play.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
import load
import pickle
import theano
import theano.tensor as T
import math
import chess, chess.pgn
import heapq
import time
import re
import string
import numpy
import sunfish
import pickle
import random
import traceback
def get_model_from_pickle(fn):
f = open(fn)
Ws, bs = pickle.load(f)
Ws_s, bs_s = load.get_parameters(Ws=Ws, bs=bs)
x, p = load.get_model(Ws_s, bs_s)
predict = theano.function(
inputs=[x],
outputs=p)
return predict
strip_whitespace = re.compile(r"\s+")
translate_pieces = string.maketrans(".pnbrqkPNBRQK", "\x00" + "\x01\x02\x03\x04\x05\x06" + "\x08\x09\x0a\x0b\x0c\x0d")
def sf2array(pos, flip):
# Create a numpy array from a sunfish representation
pos = strip_whitespace.sub('', pos.board) # should be 64 characters now
pos = pos.translate(translate_pieces)
m = numpy.fromstring(pos, dtype=numpy.int8)
if flip:
m = numpy.fliplr(m.reshape(8, 8)).reshape(64)
return m
CHECKMATE_SCORE = 1e6
def negamax(pos, depth, alpha, beta, color, func):
moves = []
X = []
pos_children = []
for move in pos.gen_moves():
pos_child = pos.move(move)
moves.append(move)
X.append(sf2array(pos_child, flip=(color==1)))
pos_children.append(pos_child)
if len(X) == 0:
return Exception('eh?')
# Use model to predict scores
scores = func(X)
for i, pos_child in enumerate(pos_children):
if pos_child.board.find('K') == -1:
scores[i] = CHECKMATE_SCORE
child_nodes = sorted(zip(scores, moves), reverse=True)
best_value = float('-inf')
best_move = None
for score, move in child_nodes:
if depth == 1 or score == CHECKMATE_SCORE:
value = score
else:
# print 'ok will recurse', sunfish.render(move[0]) + sunfish.render(move[1])
pos_child = pos.move(move)
neg_value, _ = negamax(pos_child, depth-1, -beta, -alpha, -color, func)
value = -neg_value
# value += random.gauss(0, 0.001)
# crdn = sunfish.render(move[0]) + sunfish.render(move[1])
# print '\t' * (3 - depth), crdn, score, value
if value > best_value:
best_value = value
best_move = move
if value > alpha:
alpha = value
if alpha > beta:
break
return best_value, best_move
def create_move(board, crdn):
# workaround for pawn promotions
move = chess.Move.from_uci(crdn)
if board.piece_at(move.from_square).piece_type == chess.PAWN:
if int(move.to_square/8) in [0, 7]:
move.promotion = chess.QUEEN # always promote to queen
return move
class Player(object):
def move(self, gn_current):
raise NotImplementedError()
class Computer(Player):
def __init__(self, func, maxd=5):
self._func = func
self._pos = sunfish.Position(sunfish.initial, 0, (True,True), (True,True), 0, 0)
self._maxd = maxd
def move(self, gn_current):
assert(gn_current.board().turn == True)
if gn_current.move is not None:
# Apply last_move
crdn = str(gn_current.move)
move = (119 - sunfish.parse(crdn[0:2]), 119 - sunfish.parse(crdn[2:4]))
self._pos = self._pos.move(move)
# for depth in xrange(1, self._maxd+1):
alpha = float('-inf')
beta = float('inf')
depth = self._maxd
t0 = time.time()
best_value, best_move = negamax(self._pos, depth, alpha, beta, 1, self._func)
crdn = sunfish.render(best_move[0]) + sunfish.render(best_move[1])
print depth, best_value, crdn, time.time() - t0
self._pos = self._pos.move(best_move)
crdn = sunfish.render(best_move[0]) + sunfish.render(best_move[1])
move = create_move(gn_current.board(), crdn)
gn_new = chess.pgn.GameNode()
gn_new.parent = gn_current
gn_new.move = move
return gn_new
class Human(Player):
def move(self, gn_current):
bb = gn_current.board()
print bb
def get_move(move_str):
try:
move = chess.Move.from_uci(move_str)
except:
print 'cant parse'
return False
if move not in bb.legal_moves:
print 'not a legal move'
return False
else:
return move
while True:
print 'your turn:'
move = get_move(raw_input())
if move:
break
gn_new = chess.pgn.GameNode()
gn_new.parent = gn_current
gn_new.move = move
return gn_new
class Sunfish(Player):
def __init__(self, secs=1):
self._searcher = sunfish.Searcher()
self._pos = sunfish.Position(sunfish.initial, 0, (True,True), (True,True), 0, 0)
self._secs = secs
def move(self, gn_current):
import sunfish
assert(gn_current.board().turn == False)
# Apply last_move
crdn = str(gn_current.move)
move = (sunfish.parse(crdn[0:2]), sunfish.parse(crdn[2:4]))
self._pos = self._pos.move(move)
t0 = time.time()
move, score = self._searcher.search(self._pos, self._secs)
print time.time() - t0, move, score
self._pos = self._pos.move(move)
crdn = sunfish.render(119-move[0]) + sunfish.render(119 - move[1])
move = create_move(gn_current.board(), crdn)
gn_new = chess.pgn.GameNode()
gn_new.parent = gn_current
gn_new.move = move
return gn_new
def game(func):
gn_current = chess.pgn.Game()
maxd = random.randint(1, 2) # max depth for deep pink
secs = random.random() # max seconds for sunfish
print 'maxd %f secs %f' % (maxd, secs)
player_a = Computer(func, maxd=maxd)
player_b = Sunfish(secs=secs)
times = {'A': 0.0, 'B': 0.0}
while True:
for side, player in [('A', player_a), ('B', player_b)]:
t0 = time.time()
try:
gn_current = player.move(gn_current)
except KeyboardInterrupt:
return
except:
traceback.print_exc()
return side + '-exception', times
times[side] += time.time() - t0
print '=========== Player %s: %s' % (side, gn_current.move)
s = str(gn_current.board())
print s
if gn_current.board().is_checkmate():
return side, times
elif gn_current.board().is_stalemate():
return '-', times
elif gn_current.board().can_claim_fifty_moves():
return '-', times
elif s.find('K') == -1 or s.find('k') == -1:
# Both AI's suck at checkmating, so also detect capturing the king
return side, times
def play():
func = get_model_from_pickle('model.pickle')
while True:
side, times = game(func)
f = open('stats.txt', 'a')
f.write('%s %f %f\n' % (side, times['A'], times['B']))
f.close()
if __name__ == '__main__':
play()