This repository has been archived by the owner on Nov 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
alphabeta.py
118 lines (81 loc) · 2.59 KB
/
alphabeta.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
import time
import evaluate
import main
import copy
from main import Moves
tree_size = 0
def minimax(allowed_time: int, depth: int, board: main.Board):
global tree_size
tree_size = 0
board.copy_move()
maximize = board.side^1
best_value = -float("inf") if maximize else float("inf")
timer = time.time()
moves = Moves()
main.generate_move(moves, board)
if len(moves.moves) == 0:
return 0
for move in moves:
#if time.time() - timer > allowed_time:
# return moves.moves[1]
board_copy = copy.deepcopy(board)
if not main.make_move(move, board):
#print("ILLEGAL")
continue
main.print_board(board)
value = alpha_beta(depth - 1, not maximize, board)
board = copy.deepcopy(board_copy)
if maximize and value >= best_value:
best_value = value
best_move = move
elif not maximize and value <= best_value:
best_value = value
best_move = move
print(tree_size)
return best_move
def alpha_beta(depth: int, maximize: bool, board):
if maximize:
return alpha_beta_max(-float("inf"), float("inf"), depth, board)
else:
return alpha_beta_min(-float("inf"), float("inf"), depth, board)
def alpha_beta_max(alpha, beta, depth, board):
global tree_size
if depth == 0:
tree_size += 1
test1 = evaluate.evaluate(board, board.side)
#print(f"test1: max: {test1}")
return test1
moves = Moves()
main.generate_move(moves, board)
for move in moves:
board_copy = copy.deepcopy(board)
if not main.make_move(move, board):
continue
value = alpha_beta_min(alpha, beta, depth - 1, board)
board = copy.deepcopy(board_copy)
if value >= beta:
return beta
elif value > alpha:
alpha = value
return alpha
def alpha_beta_min(alpha, beta, depth, board):
global tree_size
if depth == 0:
tree_size += 1
test2 = evaluate.evaluate(board, board.side^1)
#print(f"test1: min: {test2}")
return test2
moves = Moves()
main.generate_move(moves, board)
for move in moves:
board_copy = copy.deepcopy(board)
if not main.make_move(move, board):
#print("ILLEGAL MOVE")
continue
value = alpha_beta_max(alpha, beta, depth - 1, board)
board = copy.deepcopy(board_copy)
if value <= alpha:
return alpha
elif value < beta:
beta = value
return beta