-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChessBot.py
435 lines (372 loc) · 16.3 KB
/
ChessBot.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
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
import numpy as np
from termcolor import colored
import random
from copy import deepcopy as copy
import concurrent.futures
class ChessBot():
"""
Class Chatbot contains 2 key functions:
bot = ChessBot()
bot.user_move('A2', 'A2') # <- make your move
bot.next_move() # <- bot makes the move
"""
def __init__(self, depth = 0):
"""
Initialize code:
inputs:
depth: Only used for predictions, not to be specified by user
"""
self.depth = depth
self.color = 'white' # color that the user plays with, will be
# changable in future versions
self.color_user = None
# the board is an array with numbers that corresponds to the piece
# thats on it. Positive number is bot, negative is user
self.board = np.array([[2, 3, 4, 5, 6, 4, 3, 2],
[1, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]])
self.board -= self.board[::-1]
# convert_dict is used for the conversion of e.g. 'A1' to location on
# the matrix in self.board
self.convert_dict = {}
for i in range(0, 8):
self.convert_dict[chr(65+i)] = i
self.convert_dict[i] = chr(65+i)
def show_board(self):
"""
Prints the board in a way that is more-or-less understandable to humans
"""
print(colored(' A B C D E F G H'))
print(colored(' ---------------'))
pieces = ['', 'P', 'R', 'N', 'B', 'Q', 'K']
for i in range(8):
row = colored(str(8-i) + '| ')
for j in range(8):
if not pieces[abs(self.board[i, j])] == '':
if self.board[i, j] < 0:
color = self.color
else:
color = self.color_user
row += colored(str(pieces[abs(self.board[i, j])])+' ',
color)
else:
row += colored(pieces[0]+' ', self.color)
print(row)
def convert(self, x, user = 'self'):
"""
Converts board location (e.g. 'A1') to matrix index (e.g. [0,0])
inputs:
x: either string (e.g. 'A1' or array (e.g. [0,0])
user: either 'self' being bot, or 'user'
outputs:
y: either string (e.g. 'A1' or array (e.g. [0,0]), the other one
than the input
"""
if type(x) == str:
if user == 'self':
try:
return [8-int(x[1]), self.convert_dict[x[0]]]
except:
print(x)
return [8-int(x[1]), self.convert_dict[x[0]]]
elif user == 'user':
try:
return [1+int(x[1]), self.convert_dict[x[0]]]
except:
print(x)
return [1+int(x[1]), self.convert_dict[x[0]]]
elif type(x) == list and [8, 8] > x >= [0, 0]:
if user == 'self':
return self.convert_dict[x[1]] + str(8-x[0])
elif user == 'user':
return self.convert_dict[x[1]] + str(1+x[0])
else:
raise TypeError('Invalid type')
def get_available_moves(self, user):
"""
Show available moves
inputs:
user: either 'self' being bot, or 'user'
outputs:
moves [dict]: keys are the current locations that can be moved,
values are the locations that that key can move to.
TODO:
add casting
"""
moves = {}
if user == 'user':
board = -self.board[::-1]
elif user == 'self':
board = self.board
else:
raise TypeError('User not recognized, specify "user" or "self"')
for i in range(8):
for j in range(8):
move_curr = []
""" Pawn """
if board[i, j] == 1:
if i == 7:
continue
if board[i+1, j] == 0:
move_curr.append(self.convert([i+1, j], user))
if i == 1 and board[i+1, j] == 0 and board[i+2, j] == 0:
move_curr.append(self.convert([i+2, j], user))
if j > 0 and board[i+1, j-1] < 0:
move_curr.append(self.convert([i+1, j-1], user))
if j < 7 and board[i+1, j+1] < 0:
move_curr.append(self.convert([i+1, j+1], user))
""" Rook, Queen and King """
if board[i, j] in [2, 5, 6]:
ranges = [range(i+1, 8), range(i-1, -1, -1)]
for ran in ranges:
for ii in ran:
if board[ii, j] == 0:
move_curr.append(self.convert([ii, j], user))
if board[i, j] == 6:
break
elif board[ii, j] < 0:
move_curr.append(self.convert([ii, j], user))
break
else:
break
ranges = [range(j+1, 8), range(j-1, -1, -1)]
for ran in ranges:
for jj in ran:
if board[i, jj] == 0:
move_curr.append(self.convert([i, jj], user))
if board[i, j] == 6:
break
elif board[i, jj] < 0:
move_curr.append(self.convert([i, jj], user))
break
else:
break
""" Knight """
if board[i, j] == 3:
signs = [[1, 1], [-1, 1], [1, -1], [-1, -1]]
movess = [[2, 1], [1, 2]]
for move_i, move_j in movess:
for sign_i, sign_j in signs:
try:
if board[i+move_i*sign_i, j+move_j*sign_j] <= 0:
move_curr.append(self.convert([i+move_i*sign_i,
j+move_j*sign_j], user))
except:
continue
""" Bisshop, Queen and King """
if board[i, j] in [4, 5, 6]:
signs = [[1, 1], [-1, 1], [1, -1], [-1, -1]]
for sign_i, sign_j in signs:
for n in range(1, 8):
try:
if board[i+sign_i*n, j+sign_j*n] == 0:
move_curr.append(self.convert([i+sign_i*n,
j+sign_j*n],
user))
if board[i, j] == 6:
break
elif board[i+sign_i*n, j+sign_j*n] < 0:
move_curr.append(self.convert([i+sign_i*n,
j+sign_j*n],
user))
break
else:
break
except:
break
if move_curr:
moves[self.convert([i, j], user)] = move_curr
return moves
def check_for_check(self, user):
if user == 'user':
moves = self.get_available_moves('self')
else:
moves = self.get_available_moves('user')
for move in moves:
for end in moves[move]:
location = self.convert(end)
if np.abs(self.board[location[0], location[1]]) == 6:
if user == 'user':
self.message = 'You are in check'
return 1
if user == 'self':
self.message = 'Bot is in check'
return 1
return 0
def user_move(self, start, end, user = 'user', show = True):
"""
Request move
inputs:
start: piece to move (e.g. 'A2')
end: location to move to (e.g. 'A4')
user: either 'self' being bot, or 'user'
show [bool]: wether or not to show to board
outputs:
status: 0 - Move not possible
1 - Succes
"""
start = start.upper()
end = end.upper()
moves = self.get_available_moves(user = user)
try:
moves[start]
except KeyError:
start_c = self.convert(start)
if self.board[start_c[0], start_c[1]] < 0:
print(start + ' cannot move at this point')
self.message = start + ' cannot move at this point'
else:
print('No piece is found on the selected position')
self.message = 'No piece is found on '+end
return 0
except:
raise
if end in moves[start]:
end_c = self.convert(end)
start_c = self.convert(start)
self.board[end_c[0], end_c[1]] = self.board[start_c[0], start_c[1]]
self.board[start_c[0], start_c[1]] = 0
elif start == end:
self.message = 'You: .. to ..'
return 0
else:
print("This piece can't be moved there, available moves from " +
start + " are " + str(moves[start]))
self.message = start + ' can only move to ' + str(moves[start])
return 0
if np.any(self.board[0, :] == -1):
self.board[0, self.board[0,:] == -1] = -5
if np.any(self.board[-1, :] == 1):
self.board[-1, self.board[-1,:] == 1] = 5
if show:
self.show_board()
self.message = ''
return 1
def random_move(self):
"""
Make the bot do a random move
"""
moves = self.get_available_moves(user = 'self')
start, ends = random.choice(list(moves.items()))
end = random.choice(ends)
self.user_move(start, end, user='self')
def board_score(self, depth):
"""
Score the board for the bot to evaluate how its doing.
Inputs:
None
Output:
Score: Higher is better for bot
TODO:
Tweak score to improve the bot
"""
board = copy(self.board)
advantage = 1
board[board == 2] = 4*advantage
board[board == 3] = 4*advantage
board[board == 4] = 4*advantage
board[board == 5] = 8*advantage
board[board == 6] = 1000*advantage
board[board == -2] = -4
board[board == -3] = -4
board[board == -4] = -4
board[board == -5] = -8
board[board == -6] = -1000
score = np.sum(board)
if depth % 1:
moves = self.get_available_moves('user')
else:
moves = self.get_available_moves('user')
for move in moves:
for new_move in moves[move]:
location = self.convert(new_move)
score -= board[location[0], location[1]]/1.1
score += np.sum(np.where(self.board > 0)[0])/8
return score
def walk_board(self, depth = 0, board = None, s = '', user = 'self', score = 0):
"""
'Walk' the board. I.e. evaluate all possible moves upto a certain depth
Inputs:
DO NOT PASS ANY VARIABLE IN THIS FUNCTION
all parameters are used for backtracking
depth: used by bot to track how many
move deep it is evaluating
board: Provide board
s: list of moves
user: 'self' or 'user', used for alternating
score: score of the list of moves
Output:
s: list of possible moves with score attatched
"""
global _score, _speed_up
subbot = ChessBot(depth = self.depth+1)
if board is None:
subbot.board = copy(self.board)
else:
subbot.board = board
board_original = copy(subbot.board)
if user == 'self':
user_next = 'user'
else:
user_next = 'self'
if depth == 2:
return [score, s]
_score[depth] = max(_score[depth], score)
if score < _score[depth]/4*3 and depth > 0 and _speed_up:
return [-100, ""]
new_s = []
moves = subbot.get_available_moves(user)
for move in moves:
for next_move in moves[move]:
subbot.board = copy(board_original)
subbot.user_move(move, next_move, user=user, show=False)
if depth == 0:
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(subbot.walk_board,
depth = depth+1,
board = subbot.board,
s = s + move + next_move,
user = user_next,
score = score
+ subbot.board_score(depth))
new_s += future.result()
else:
new_s += subbot.walk_board(depth = depth+1,
board = subbot.board,
s = s + move + next_move,
user = user_next,
score = score
+ subbot.board_score(depth))
return new_s
def next_move(self):
"""
Make the bot do its next move
"""
global _score, _speed_up
s = self.walk_board()
_score = [0]*5
move = s[s.index(max(s[::2]))+1]
while np.random.rand()>.5:
try:
del s[s.index(max(s[::2])):s.index(max(s[::2]))+2]
if not any(s[s.index(max(s[::2]))+1]):
move = s[s.index(max(s[::2]))+1]
else:
break
except:
break
if not any(move):
_speed_up = 0
s = self.walk_board()
_score = [0]*5
move = s[s.index(max(s[::2]))+1]
_speed_up = 1
self.user_move(move[0:2], move[2:4], user = 'self', show=False)
return self.convert(move[0:2]), self.convert(move[2:4])
_score = [0]*5
_speed_up = 1