-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnewt.py
executable file
·276 lines (240 loc) · 6.47 KB
/
newt.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
#!/usr/bin/env python3
# A Python chess engine
from pst import pst
import chess as c
import os, sys, math, time
from random import choice
if sys.path[0]:
os.chdir(sys.path[0]) # change working directory to script directory so the opening book will be found
# computer plays as Black by default
COMPC = c.BLACK
PLAYC = c.WHITE
DEPTH = 4 # maximum search depth
QPLIES = 8 # additional maximum quiescence search plies
PSTAB = .1 # influence of piece-square table on moves, 0 = none
b = c.Board()
PV = [] # array for primary variation
def getpos(b):
"Get positional-play value for a board for both players"
ppv = 0
if not moves and b.is_checkmate():
if b.turn == c.WHITE:
ppv = -1000
else:
ppv = 1000
pm = b.piece_map()
for i in pm.keys():
mm = pm[i].piece_type
if mm == c.KING and (
len(b.pieces(c.PAWN, COMPC)) + len(b.pieces(c.PAWN, PLAYC)) ) <= 8: # endgame is different
mm = 8 # for the King
if pm[i].color == c.WHITE:
j, k = i // 8, i % 8
ppv += PSTAB * pst[mm][8 * (7 - j) + k] / 100
else:
ppv -= PSTAB * pst[mm][i] / 100
return ppv
def getval(b):
"Get total piece value of board"
return (
len(b.pieces(c.PAWN, c.WHITE)) - len(b.pieces(c.PAWN, c.BLACK))
+ 2.8 * (len(b.pieces(c.KNIGHT, c.WHITE)) - len(b.pieces(c.KNIGHT, c.BLACK)))
+ 3.2 * (len(b.pieces(c.BISHOP, c.WHITE)) - len(b.pieces(c.BISHOP, c.BLACK)))
+ 4.79 * (len(b.pieces(c.ROOK, c.WHITE)) - len(b.pieces(c.ROOK, c.BLACK)))
+ 9.29 * (len(b.pieces(c.QUEEN, c.WHITE)) - len(b.pieces(c.QUEEN, c.BLACK)))
)
def getneg(b):
"Board value in the Negamax framework, i.e. '+' means the side to move has the advantage"
if b.turn:
return getval(b) + getpos(b)
else:
return -getval(b) - getpos(b)
def isdead(b, p):
"Is the position dead? (quiescence) E.g., can the capturing piece be recaptured? Is there a check on this or the last move?"
if p <= -QPLIES or not moves: # when too many plies or checkmate
return True
if b.is_check():
return False
x = b.pop()
if (b.is_capture(x) and len(b.attackers(not b.turn, x.to_square))) or b.is_check():
b.push(x)
return False
else:
b.push(x)
return True
# https://chessprogramming.wikispaces.com/Alpha-Beta
def searchmax(b, ply, alpha, beta):
"Search moves and evaluate positions for player whose turn it is"
global moves
# This way is quite a bit faster than a simple "list(b.legal_moves)",
# because the LegalMoveGenerator's __len__ is not called, which would
# generate the moves *twice*. Thanks, SnakeViz team!
moves = [q for q in b.legal_moves]
if ply <= 0 and isdead(b, ply):
return getneg(b), [str(q) for q in b.move_stack]
o = order(b, ply)
if ply <= 0:
if not o:
return getneg(b), [str(q) for q in b.move_stack]
v = PV
for x in o:
b.push(x)
t, vv = searchmax(b, ply - 1, -beta, -alpha)
t = -t
b.pop()
if t >= beta:
return beta, vv
if t > alpha:
alpha = t
v = vv
return alpha, v
def order(b, ply):
"Move ordering"
if ply >= 0: # try moves from PV before others
am, bm = [], []
for x in moves:
if str(x) in PV:
am.append(x)
else:
bm.append(x)
return am + bm
# quiescence search (ply < 0), sort captures by MVV/LVA value
am, bm = [], []
for x in moves:
if b.is_capture(x):
if b.piece_at(x.to_square):
# MVV/LVA sorting (http://home.hccnet.nl/h.g.muller/mvv.html)
am.append((x, 10 * b.piece_at(x.to_square).piece_type
- b.piece_at(x.from_square).piece_type))
else: # to square is empty during en passant capture
am.append((x, 10 - b.piece_at(x.from_square).piece_type))
am.sort(key = lambda m: m[1])
am.reverse()
bm = [q[0] for q in am]
return bm
def pm():
if COMPC == c.WHITE:
return 1
else:
return -1
def pc(col):
if col == c.WHITE:
return 1
else:
return -1
def getnewmove(m, n):
if len(m) <= len(n):
return []
i = 0
for x, y in zip(m, n):
if x == y:
i += 1
else:
break
if i == len(n):
return m[i]
else:
return []
try:
ob = open("chess-eco.pos.txt").readlines()
except:
print("Opening book not found!")
ob = []
def getopen(b):
"Identify opening and get a book move if possible"
op = []
d = c.Board()
for x in b.move_stack:
op.append(d.san(x))
d.push(x)
played = '%s' % (' '.join(op))
hits = []
id = '', '', ''
sm = []
for l in ob:
h5 = l.split('"')
if len(h5) > 5:
eco, name, mv = h5[1], h5[3], h5[5]
if played[:len(mv)] == mv:
if len(mv) > len(id[1]):
id = name, mv, eco
sm1 = getnewmove(mv.split(), op)
try:
if sm1:
sm1 = str(b.parse_san(sm1))
except:
print("Illegal book move", sm1)
sm1 = []
if sm1 and sm1 not in sm:
sm.append(sm1)
print('# %s %s (%s)' % (id[2], id[0], id[1]))
return sm
def getmove(b, silent = False, usebook = True):
"Get value and primary variation for board"
global COMPC, PLAYC, MAXPLIES, PV
if b.turn == c.WHITE:
COMPC = c.WHITE
PLAYC = c.BLACK
else:
COMPC = c.BLACK
PLAYC = c.WHITE
if not silent:
print("FEN:", b.fen())
if usebook:
opening = getopen(b)
if opening:
return 0, [choice(opening)]
win = .25 # initial aspiration window bounds (https://chessprogramming.wikispaces.com/Aspiration+Windows)
aa, ab = -1e6, 1e6 # initial alpha and beta
for MAXPLIES in range(1, DEPTH + 1):
it = 0
while it < 100:
t, PV = searchmax(b, MAXPLIES, aa, ab)
PV = PV[len(b.move_stack):] # separate principal variation from moves already played
if not PV:
win *= 2
aa, ab = t - win, t + win
print("# fail", it, win)
sys.stdout.flush()
else:
break
it += 1
aa, ab = t - win, t + win
print('# %u %.2f %s' % (MAXPLIES, t, str(PV))) # negamax, so a positive score means the computer scores better
sys.stdout.flush()
if t < -500 or t > 500: # found a checkmate
break
return t, PV
if __name__ == '__main__':
while True: # game loop
while True:
print(b)
print()
#print(getopen(b))
if sys.version < '3':
move = raw_input("Your move? ")
else:
move = input("Your move? ")
if move == "quit":
sys.exit(0)
try:
try:
b.push_san(move)
except ValueError:
b.push_uci(move)
print(b)
except:
print("Sorry? Try again. (Or type quit to quit.)")
else:
break
if b.result() != '*':
print("Game result:", b.result())
break
tt = time.time()
t, ppp = getmove(b)
print("My move: %u. %s" % (b.fullmove_number, ppp[0]))
print(" ( calculation time spent: %u m %u s )" % ((time.time() - tt) // 60, (time.time() - tt) % 60))
b.push(c.Move.from_uci(ppp[0]))
if b.result() != '*':
print("Game result:", b.result())
break