-
Notifications
You must be signed in to change notification settings - Fork 0
/
AlphaBeta.py
74 lines (68 loc) · 2.67 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
class AlphaBeta:
""" Simple Alpha Beta pruning used to determine a good move."""
def __init__(self, game):
self.game = game
def iterate(self, node, depth, alpha, beta, player):
""" Walk along the tree starting at node until a certain depth.
:param node: node to start with
:param depth: depth to stop at
:param alpha: initial alpha
:param beta: initial beta
:param player: player in turn at this node.
:return: best score.
"""
if depth == 0 or node.is_terminal():
return node.get_score(depth)
if player == self.game.max_player:
children = node.fetch_children(player)
for child in children:
eval = self.iterate(child, depth - 1, alpha, beta, self.game.opponent(player))
if eval > alpha:
alpha = eval
child.value = eval
child.alpha = eval
if alpha >= beta:
break
return alpha
else:
children = node.fetch_children(player)
for child in children:
eval = self.iterate(child, depth - 1, alpha, beta, self.game.opponent(player))
if eval < beta:
beta = eval
child.beta = eval
if alpha >= beta:
break
return beta
def iterate_2(self, node, depth, alpha, beta, player):
""" Walk along the tree starting at node until a certain depth.
:param node: node to start with
:param depth: depth to stop at
:param alpha: initial alpha
:param beta: initial beta
:param player: player in turn at this node.
:return: best score.
"""
if depth == 0 or node.is_terminal():
return node.get_score_2(depth)
if player == self.game.max_player:
children = node.fetch_children(player)
for child in children:
eval = self.iterate_2(child, depth - 1, alpha, beta, self.game.opponent(player))
if eval > alpha:
alpha = eval
child.value = eval
child.alpha = eval
if alpha >= beta:
break
return alpha
else:
children = node.fetch_children(player)
for child in children:
eval = self.iterate_2(child, depth - 1, alpha, beta, self.game.opponent(player))
if eval < beta:
beta = eval
child.beta = eval
if alpha >= beta:
break
return beta