Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node:
- def __init__(self, nodeID, nodeData, nodeChilds=None, isTerminal=False):
- """
- Contains the basic information for a node.
- nodeData ---> Node value, it should be an integer.
- nodeID ---> Node index, a unique ID to identify every node.
- nodeChilds ---> Set of this node childs, empty by default.
- isTerminal ---> Boolean that tells the algorithm if this node is a terminal.
- """
- self.nodeID = nodeID
- self.nodeData = nodeData
- self.nodeChilds = set() if not nodeChilds else nodeChilds
- self.isTerminal = isTerminal
- def __int__(self): return self.nodeData
- def __len__(self): return len(self.nodeChilds)
- def __str__(self): return f'Node({self.nodeID}) = {self.nodeData} | {len(self)} Childs'
- N1 = Node(1, -3, isTerminal=True)
- N2 = Node(2, +7, isTerminal=True)
- N3 = Node(3, -2, isTerminal=True)
- N4 = Node(4, -1, isTerminal=True)
- N5 = Node(5, -7, isTerminal=True)
- N6 = Node(6, -3, isTerminal=True)
- N7 = Node(7, +8, isTerminal=True)
- N8 = Node(8, +4, isTerminal=True)
- N9 = Node(9, None, {N1, N2})
- N10 = Node(10, None, {N3, N4})
- N11 = Node(11, None, {N5, N6})
- N12 = Node(12, None, {N7, N8})
- N13 = Node(13, None, {N9, N10})
- N14 = Node(14, None, {N11, N12})
- Root = Node(15, None, {N13, N14})
- def AlphaBeta(fromNode, withPlayer, atDepth, alpha=float('-inf'), beta=float('inf')):
- if atDepth == 0 or fromNode.isTerminal:
- return fromNode.nodeData
- elif withPlayer == "MAX":
- v = float('-inf')
- for child in fromNode.nodeChilds:
- v = max(v, AlphaBeta(child, "MIN", atDepth-1, alpha, beta))
- if v >= beta: break
- alpha = max(alpha, v)
- elif withPlayer == "MIN":
- v = float('inf')
- for child in fromNode.nodeChilds:
- v = min(v, AlphaBeta(child, "MAX", atDepth-1, alpha, beta))
- if v <= alpha: break
- beta = min(beta, v)
- fromNode.nodeData = v
- return v
- vMax = AlphaBeta(Root, "MAX", 3)
- vMin = AlphaBeta(Root, "MIN", 3)
- print(f'Max: {vMax} | Min: {vMin}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement