Advertisement
EXTREMEXPLOIT

AlphaBeta Prunning

Dec 12th, 2021
785
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.08 KB | None | 0 0
  1. class Node:
  2.     def __init__(self, nodeID, nodeData, nodeChilds=None, isTerminal=False):
  3.         """
  4.        Contains the basic information for a node.
  5.        nodeData ---> Node value, it should be an integer.
  6.        nodeID ---> Node index, a unique ID to identify every node.
  7.        nodeChilds ---> Set of this node childs, empty by default.
  8.        isTerminal ---> Boolean that tells the algorithm if this node is a terminal.
  9.        """
  10.         self.nodeID = nodeID
  11.         self.nodeData = nodeData
  12.         self.nodeChilds = set() if not nodeChilds else nodeChilds
  13.         self.isTerminal = isTerminal
  14.  
  15.     def __int__(self): return self.nodeData
  16.     def __len__(self): return len(self.nodeChilds)
  17.     def __str__(self): return f'Node({self.nodeID}) = {self.nodeData} | {len(self)} Childs'
  18.  
  19. N1 = Node(1, -3, isTerminal=True)
  20. N2 = Node(2, +7, isTerminal=True)
  21. N3 = Node(3, -2, isTerminal=True)
  22. N4 = Node(4, -1, isTerminal=True)
  23. N5 = Node(5, -7, isTerminal=True)
  24. N6 = Node(6, -3, isTerminal=True)
  25. N7 = Node(7, +8, isTerminal=True)
  26. N8 = Node(8, +4, isTerminal=True)
  27.  
  28. N9 = Node(9, None, {N1, N2})
  29. N10 = Node(10, None, {N3, N4})
  30. N11 = Node(11, None, {N5, N6})
  31. N12 = Node(12, None, {N7, N8})
  32.  
  33. N13 = Node(13, None, {N9, N10})
  34. N14 = Node(14, None, {N11, N12})
  35.  
  36. Root = Node(15, None, {N13, N14})
  37.  
  38. def AlphaBeta(fromNode, withPlayer, atDepth, alpha=float('-inf'), beta=float('inf')):
  39.     if atDepth == 0 or fromNode.isTerminal:
  40.         return fromNode.nodeData
  41.     elif withPlayer == "MAX":
  42.         v = float('-inf')
  43.         for child in fromNode.nodeChilds:
  44.             v = max(v, AlphaBeta(child, "MIN", atDepth-1, alpha, beta))
  45.             if v >= beta: break
  46.             alpha = max(alpha, v)
  47.     elif withPlayer == "MIN":
  48.         v = float('inf')
  49.         for child in fromNode.nodeChilds:
  50.             v = min(v, AlphaBeta(child, "MAX", atDepth-1, alpha, beta))
  51.             if v <= alpha: break
  52.             beta = min(beta, v)
  53.     fromNode.nodeData = v
  54.     return v
  55.  
  56. vMax = AlphaBeta(Root, "MAX", 3)
  57. vMin = AlphaBeta(Root, "MIN", 3)
  58.  
  59. print(f'Max: {vMax} | Min: {vMin}')
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement