-
Notifications
You must be signed in to change notification settings - Fork 0
/
MiniMaxPlayer.py
95 lines (75 loc) · 3.03 KB
/
MiniMaxPlayer.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
import chess
from Player import Player
from ai import *
class MiniMaxPlayer(Player):
max_depth = 2
move_count = 0
def initHeuristics(self):
self.historyHeuristic = {}
self.killerHeuristic = {}
self.butterflyHeuristic = {}
for square in chess.SQUARES:
self.historyHeuristic[chess.square_name(square)] = 0
self.butterflyHeuristic[chess.square_name(square)] = 0
for i in range(0, self.max_depth):
self.killerHeuristic[i] = {}
for square in chess.SQUARES:
self.killerHeuristic[i][chess.square_name(square)] = 0
def evaluate(self, board: chess.Board) -> float:
total = 0
end_game = are_we_in_end_game(board)
value = 0
for square in chess.SQUARES:
piece = board.piece_at(square)
if not piece:
continue
value = piece_value[piece.piece_type] + evaluate_position(piece, square, end_game)
if piece.color == chess.WHITE:
total += value
else:
total -= value
return total
def move(self, board: chess.Board) -> chess.Move:
self.initHeuristics()
# c = 0
value = -float('inf') if self.player_color else float('inf')
alpha = -float('inf')
beta = float('inf')
best_move = None
temp = 0
legal_moves = list(board.legal_moves)
for move in legal_moves:
board.push(move)
if board.is_checkmate():
board.pop()
return move
if board.is_game_over():
value = max(value, self.evaluate(board)) if self.player_color else min(value, self.evaluate(board))
if self.player_color:
if temp >= value:
value = temp
best_move = move
else:
if temp <= value:
value = temp
best_move = move
board.pop()
continue
if board.can_claim_draw():
temp = 0
else:
# temp = minimizer(board, self.max_depth, alpha, beta, self.evaluate) if self.player_color else maximizer(board, self.max_depth, alpha, beta, self.evaluate)
temp = alphabeta(board, self.max_depth, alpha, beta,False, self.historyHeuristic, self.butterflyHeuristic, self.killerHeuristic, self.evaluate) if self.player_color else alphabeta(board, self.max_depth, alpha, beta, True, self.historyHeuristic, self.butterflyHeuristic, self.killerHeuristic, self.evaluate)
# c = c + 1
# print(c)
if self.player_color:
if temp >= value:
value = temp
best_move = move
else:
if temp <= value:
value = temp
best_move = move
board.pop()
self.move_count += 1
return best_move