alpha beta pruning
import matplotlib.pyplot as plt
import networkx as nx
import math
def alpha_beta(node, ismaximized, alpha, beta, G, parent=None):
# If node is a leaf node
if game_tree[node] is None:
G.add_node(node, value=leaf_values[node])
if parent:
G.add_edge(parent, node)
return leaf_values[node]
G.add_node(node, value=node)
if parent:
G.add_edge(parent, node)
if ismaximized:
bestScore = -math.inf
for child in game_tree[node]:
score = alpha_beta(child, False, alpha, beta, G, node)
bestScore = max(score, bestScore)
alpha = max(alpha, score)
if alpha >= beta:
break # Beta cut-off
G.nodes[node]['value'] = bestScore
return bestScore
else:
bestScore = math.inf
for child in game_tree[node]:
score = alpha_beta(child, True, alpha, beta, G, node)
bestScore = min(score, bestScore)
beta = min(beta, score)
if alpha >= beta:
break # Alpha cut-off
G.nodes[node]['value'] = bestScore
return bestScore
Define game tree and leaf values
game_tree = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F', 'G'],
'D': None, # Leaf
'E': None, # Leaf
'F': None, # Leaf
'G': None # Leaf
}
leaf_values = {
'D': -1,
'E': 3,
'F': 5,
'G': 2
}
G = nx.DiGraph()
Run alpha-beta pruning
result = alpha_beta('A', True, -math.inf, math.inf, G)
print("The optimal value is", result)
Visualization
pos = nx.spring_layout(G)
node_labels = {node: f"{node}\n{G.nodes[node]['value']}" for node in G.nodes}
plt.figure(figsize=(10, 10))
nx.draw(G, pos, with_labels=False, node_size=2000, font_size=10, font_weight='bold')
nx.draw_networkx_labels(G, pos, labels=node_labels, font_size=10)
plt.title("Alpha-Beta Pruning Game Tree", fontsize=16)
plt.show()