-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalphabetaHeuristic.py
More file actions
47 lines (43 loc) · 1.79 KB
/
alphabetaHeuristic.py
File metadata and controls
47 lines (43 loc) · 1.79 KB
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
import math
def alphaBetaDepthHeuristic(game, state, player, currDepth, maxDepth):
(value, move) = maxValueABDepthHeuristic(game, state, player, -math.inf, math.inf, currDepth, maxDepth)
return move
def maxValueABDepthHeuristic(game, state, player, alpha, beta, currDepth, maxDepth):
# Check if board is in terminal state or maximum depth reached
if game.isTerminal(state):
return (game.utility(state, player), None)
if currDepth == maxDepth:
return (game.heuristic(state, player), None)
value = -math.inf # value = -infinty
actions = game.getActions(state)
move = actions[0]
#find best move for AI
for a in actions:
v2, a2 = minValueABDepthHeuristic(game, game.result(state, a, player), player, alpha, beta, currDepth+1, maxDepth)
if v2 > value:
value = v2
move = a
alpha = max(alpha, value)
if value >= beta:
return (value, move)
return (value, move)
def minValueABDepthHeuristic(game, state, player, alpha, beta, currDepth, maxDepth):
oppositePlayers = {1:2, 2:1}
# Check if board is in terminal state or maximum depth reached
if game.isTerminal(state):
return (game.utility(state, player), None)
if currDepth == maxDepth:
return (game.heuristic(state, player), None)
value = math.inf # value = -infinty
actions = game.getActions(state)
move = actions[0]
#find best move for AI
for a in actions:
v2, a2 = maxValueABDepthHeuristic(game, game.result(state, a, oppositePlayers[player]), player, alpha, beta, currDepth+1, maxDepth)
if v2 < value:
value = v2
move = a
beta = min(beta, value)
if value <= alpha:
return (value, move)
return (value, move)