-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathai.py
445 lines (347 loc) · 10.1 KB
/
ai.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
436
437
438
439
440
441
442
443
import globals
from random import randint
from copy import deepcopy
def AI_Move(GameGrid,ABVal):
ChessGrid = deepcopy(GameGrid)
#static variable to keep track of depth of recursion
#increment by 1 if not yet set else set to 1
try:
AI_Move.depth += 1
# print("AI_move.depth = "+str(AI_Move.depth))
except AttributeError :
AI_Move.depth = 1
# print("setting AI_move.depth = "+str(AI_Move.depth))
#if max depth for recursion is reached then return
if(AI_Move.depth >= globals.MAX_DEPTH):
heuristic = getHeuristic(ChessGrid)
# print("returning "+str(heuristic) + " depth = "+str(AI_Move.depth)+"/"+str(globals.MAX_DEPTH))
return heuristic
if(AI_Move.depth % 2 == 0):
# print("AI TURN")
turn = "2" #AI
else:
# print("HUMAN TURN")
turn = "1" #human
moves = [] #stores available moves for a piece
heuristic = 0 #stores heuristic of board state of chosen move
if(turn == "2"):
heuristic = 10000
else:
heuristic = -10000
#heuristic = getHeuristic(ChessGrid)
makeMove = [0,0,0,0] #[fromRow,fromCol,toRow,toCol]
noMove = True #make sure one possible move gets chosen if no move gets chosen by minimax
checked = False #true if ai king is checked
#check if player is checked
if(kingChecked(ChessGrid,turn)):
checked = True
#if king not checked
for i in range(0,8):
for j in range(0,8):
if(ChessGrid[i][j][0] == turn ): # 1- human(white) , 2 - AI(black)
#get list of moves the piece can make
# print("ai.py - Getting moves for "+globals.ChessGrid[i][j] + " location : "+str(i)+","+str(j))
moves = getAllMoves(ChessGrid,i,j,ChessGrid[i][j][1],ChessGrid[i][j][0])
# print("moves are :")
# print(moves)
# print()
#for every possible move
for move in moves:
#copy grid status to new list
# print("playing move "+str(move))
NewChessGrid = deepcopy(ChessGrid)
NewChessGrid[i][j] = "0"
NewChessGrid[move[0]][move[1]] = ChessGrid[i][j]
#print("New Grid :")
#PrintGrid(NewChessGrid)
#if ai was previously checked and after the move is still checked then don't allow the move
if(checked and kingChecked(NewChessGrid,turn)):
continue;
#perform MINIMAX/ALPHA-BETA
moveHeuristic = AI_Move(NewChessGrid,ABVal)
#alpha beta pruning
if(turn == "2"): #AI's turn
if(moveHeuristic <= ABVal):
return min(moveHeuristic,heuristic)
if(turn == "1"): #Human's turn
if(moveHeuristic >= ABVal):
return max(moveHeuristic,heuristic)
#reduce depth value when returning from recursion
AI_Move.depth -= 1
# print("back checking "+ChessGrid[i][j] + " depth = "+str(AI_Move.depth))
#if heuristic is same chose generated move by a chance of chooseRandomMoveChance%
if(moveHeuristic == heuristic):
randomInt = randint(1,100)
if(randomInt > globals.chooseRandomMoveChance):
heuristic = moveHeuristic
ABVal = heuristic
makeMove = [i,j,move[0],move[1]]
#if better heuristic from move choose this move
#turn values AI - 1, HUMAN - 2
#AI will choose a larger heuristic value (MAX)
#human will choose a lower heuristic value (MIN)
if(moveHeuristic > heuristic and turn == "1"):
heuristic = moveHeuristic
ABVal = heuristic
if(moveHeuristic < heuristic and turn == "2"):
heuristic = moveHeuristic
ABVal = heuristic
return heuristic
def min(a,b):
if(a < b):
return a
return b
#calculate and return heuristic of the board
def getHeuristic(ChessGrid):
whiteVal = 0
blackVal = 0
for i in range(0,8):
for j in range(0,8):
#empty
if(ChessGrid[i][j] == "0"):
continue
#pawn
if(ChessGrid[i][j][1] == "1"):
if(ChessGrid[i][j][0] == "1"):
whiteVal += 1
else:
blackVal += 1
#rook
elif(ChessGrid[i][j][1] == "2"):
if(ChessGrid[i][j][0] == "1"):
whiteVal += 2
else:
blackVal += 2
#bishop
elif(ChessGrid[i][j][1] == "3"):
if(ChessGrid[i][j][0] == "1"):
whiteVal += 3
else:
blackVal += 3
#knight
elif(ChessGrid[i][j][1] == "4"):
if(ChessGrid[i][j][0] == "1"):
whiteVal += 4
else:
blackVal += 4
#queen
elif(ChessGrid[i][j][1] == "5"):
if(ChessGrid[i][j][0] == "1"):
whiteVal += 5
else:
blackVal += 5
#king
elif(ChessGrid[i][j][1] == "6"):
if(ChessGrid[i][j][0] == "1"):
whiteVal += 6
else:
blackVal += 6
if(kingChecked(ChessGrid,"1")):
blackVal += 100
if(kingChecked(ChessGrid,"2")):
whiteVal += 100
return whiteVal - blackVal
#check's if the location is empty or occupied by enemy
def CheckCell(ChessGrid,row,col,color):
if(row < 0 or col < 0 or row > 7 or col > 7):
return False
try:
#if cell is empty or occupied by opponent
if(ChessGrid[row][col][0] == "0" or ChessGrid[row][col][0] != color):
return True
#else space is occupied by own piece
return False
except IndexError: #catch IndexError
return False
def getAllMoves(ChessGrid,row,col,piece,color):
moves = []
#Pawn
if(piece == "1"):
#separate if else for black and white since black pawns will only go downwards
#and white pawns only upwards
if(color == "2"): #black
#initial 2 step
if( row == 1 and ChessGrid[row+2][col] == "0"):
moves.append([row+2,col])
#moving a step
if( ChessGrid[row+1][col] == "0" ):
moves.append([row+1,col])
#attacking
if( row+1 < 8 and col + 1 < 8 and ChessGrid[row+1][col+1][0] == "1" ):
moves.append([row+1,col+1])
if( row+1 < 8 and col - 1 >= 0 and ChessGrid[row+1][col-1][0] == "1" ):
moves.append([row+1,col-1])
else: #white
#initial 2 step
if( row == 6 and ChessGrid[row-2][col] == "0"):
moves.append([row-2,col])
#moving a step
if( ChessGrid[row-1][col] == "0" ):
moves.append([row-1,col])
#attacking
if( row-1 >= 0 and col + 1 < 8 and ChessGrid[row-1][col+1][0] == "2" ):
moves.append([row-1,col+1])
if( row-1 >= 0 and col - 1 >= 0 and ChessGrid[row-1][col-1][0] == "2" ):
moves.append([row-1,col-1])
#Rook or Queen
#Queen can move up/down/left/right like a Rook
if(piece == "2" or piece == "5"):
#going down
i = row + 1
while (i<=7):
#empty square in path
if(ChessGrid[i][col][0] == "0"):
moves.append([i,col])
#opponent in path
elif(ChessGrid[i][col][0] != color):
moves.append([i,col])
break
#own piece in path
elif(ChessGrid[i][col][0] == color):
break
i+=1
#going up
i = row - 1
while (i>=0):
if(ChessGrid[i][col][0] == "0"):
moves.append([i,col])
elif(ChessGrid[i][col][0] != color):
moves.append([i,col])
break
elif(ChessGrid[i][col][0] == color):
break
i-=1
#going left
j = col - 1
while (j>=0):
if(ChessGrid[row][j][0] == "0"):
moves.append([row,j])
elif(ChessGrid[row][j][0] != color):
moves.append([row,j])
break
elif(ChessGrid[row][j][0] == color):
break
j-=1
#going right
j = col + 1
while (j<=7):
if(ChessGrid[row][j][0] == "0"):
moves.append([row,j])
elif(ChessGrid[row][j][0] != color):
moves.append([row,j])
break
elif(ChessGrid[row][j][0] == color):
break
j+=1
#Bishop or Queen
#queen can move diagonally like the bishop
if(piece == "3" or piece == "5"):
#going up right
i = row - 1
j = col + 1
while (i>=0 and j<=7):
#empty space in path
if(ChessGrid[i][j][0] == "0"):
moves.append([i,j])
#opponent in path
elif(ChessGrid[i][j][0] != color):
moves.append([i,j])
break
#own piece in path
elif(ChessGrid[i][j][0] == color):
break
i-=1
j+=1
#going down right
i = row + 1
j = col + 1
while (i<=7 and j<=7):
if(ChessGrid[i][j][0] == "0"):
moves.append([i,j])
elif(ChessGrid[i][j][0] != color):
moves.append([i,j])
break
elif(ChessGrid[i][j][0] == color):
break
i+=1
j+=1
#going down left
i = row + 1
j = col - 1
while (i<=7 and j>=0 ):
if(ChessGrid[i][j][0] == "0"):
moves.append([i,j])
elif(ChessGrid[i][j][0] != color):
moves.append([i,j])
break
elif(ChessGrid[i][j][0] == color):
break
i+=1
j-=1
#going up left
i = row - 1
j = col - 1
while (i>=0 and j>=0 ):
if(ChessGrid[i][j][0] == "0"):
moves.append([i,j])
elif(ChessGrid[i][j][0] != color):
moves.append([i,j])
break
elif(ChessGrid[i][j][0] == color):
break
i-=1
j-=1
#Knight
if(piece == "4"):
if(CheckCell(ChessGrid,row+2,col+1,color)):
moves.append([row+2,col+1])
if(CheckCell(ChessGrid,row+2,col-1,color)):
moves.append([row+2,col-1])
if(CheckCell(ChessGrid,row-2,col+1,color)):
moves.append([row-2,col+1])
if(CheckCell(ChessGrid,row-2,col-1,color)):
moves.append([row-2,col-1])
if(CheckCell(ChessGrid,row+1,col+2,color)):
moves.append([row+1,col+2])
if(CheckCell(ChessGrid,row-1,col+2,color)):
moves.append([row-1,col+2])
if(CheckCell(ChessGrid,row+1,col-2,color)):
moves.append([row+1,col-2])
if(CheckCell(ChessGrid,row-1,col-2,color)):
moves.append([row-1,col-2])
#King
if(piece == "6"):
if(CheckCell(ChessGrid,row+1,col,color)):
moves.append([row+1,col])
if(CheckCell(ChessGrid,row+1,col+1,color)):
moves.append([row+1,col+1])
if(CheckCell(ChessGrid,row+1,col-1,color)):
moves.append([row+1,col-1])
if(CheckCell(ChessGrid,row,col-1,color)):
moves.append([row,col-1])
if(CheckCell(ChessGrid,row,col+1,color)):
moves.append([row,col+1])
if(CheckCell(ChessGrid,row-1,col-1,color)):
moves.append([row-1,col-1])
if(CheckCell(ChessGrid,row-1,col,color)):
moves.append([row-1,col])
if(CheckCell(ChessGrid,row-1,col+1,color)):
moves.append([row-1,col+1])
# print(moves)
return moves
def kingChecked(ChessGrid,color):
kingRow = None
kingCol = None
# print('color '+color)
for row in range(0,8) :
for col in range(0,8):
if(ChessGrid[row][col][0] == color and ChessGrid[row][col][1] == '6'): #locate black/white king's position
kingRow = row
kingCol = col
for row in range(0,8) :
for col in range(0,8):
if(ChessGrid[row][col][0] != color and ChessGrid[row][col] != '0'):
moves = getAllMoves(ChessGrid,row,col,ChessGrid[row][col][1],ChessGrid[row][col][0])
if([kingRow,kingCol] in moves):
return True
return False