-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathai.py
83 lines (69 loc) · 2.5 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
import chess
from human import human
import random
# Iterative Deepening
# Quiescence Search
# Alpha Beta Pruning
# Zobrist Hashing
class ai:
def __init__(self):
self.max_depth = 3
def make_move(self, game):
# Initialize
moves = list(game.legal_moves)
max = [-10000,0]
# Go through possible moves and find their value
for i in range(len(moves)):
game.push(moves[i])
values = self.move_value(game, 1)
game.pop()
# If move is the best, remember
if values > max[0]:
max[0] = values
max[1] = moves[i]
# Return best move
return max[1]
def move_value(self, game, depth):
# Finds the inherent value of the move just played
value = 0
if game.is_game_over():
value = 9999 if game.turn else -9999
elif depth >= self.max_depth and not game.is_check():
'''Add Quiescence Search'''
value = self.evaluation(game)
elif game.turn:
# White to play
min = 10000
moves = list(game.legal_moves)
for i in range(len(moves)):
game.push(moves[i])
value_next = self.move_value(game, depth + 1)
game.pop()
if value_next < min:
min = value_next
value = min
else:
# Black to play
max = -10000
moves = list(game.legal_moves)
for i in range(len(moves)):
game.push(moves[i])
value_next = self.move_value(game, depth + 1)
game.pop()
if value_next > max:
max = value_next
value = max
return value
def evaluation(self, game):
# Evaluates the current game state, from -9999 to 9999
eval = random.random()
for (piece, value) in [(chess.PAWN, 1),
(chess.BISHOP, 4),
(chess.KING, 0),
(chess.QUEEN, 10),
(chess.KNIGHT, 5),
(chess.ROOK, 3)]:
eval += len(game.pieces(piece, False)) * value
eval -= len(game.pieces(piece, True)) * value
# can also check things about the pieces position here
return eval