-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAlphaBeta.py
45 lines (37 loc) · 1.37 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
from MancalaBoard import *
from Heuristics import *
import math
import random
def alpha_beta_decision(board: BoardState,alpha,beta,depth,heu_func):
if board.is_terminal() or depth==0:
return heu_dict.get(heu_func)(board), -1
if board.player==0:
best_val = -math.inf
best_move = -1
valid_moves = board.get_legal_moves()
#random.shuffle(valid_moves)
for m in valid_moves:
res_board = board.perform_move(m)
val,_ = alpha_beta_decision(res_board,alpha,beta,depth-1,heu_func)
if val>best_val:
best_val = val
best_move = m
if best_val>=beta:
return best_val, best_move
alpha = max(alpha,best_val)
return best_val, best_move
else:
best_val = math.inf
best_move = -1
valid_moves = board.get_legal_moves()
#random.shuffle(valid_moves)
for m in valid_moves:
res_board = board.perform_move(m)
val,_ = alpha_beta_decision(res_board,alpha,beta,depth-1,heu_func)
if val<best_val:
best_val = val
best_move = m
if best_val<=alpha:
return best_val, best_move
beta = min(beta,best_val)
return best_val, best_move