Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
625
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.31 KB | None | 0 0
  1. # This is a very simple implementation of the UCT Monte Carlo Tree Search algorithm in Python 2.7.
  2. # The function UCT(rootstate, itermax, verbose = False) is towards the bottom of the code.
  3. # It aims to have the clearest and simplest possible code, and for the sake of clarity, the code
  4. # is orders of magnitude less efficient than it could be made, particularly by using a
  5. # state.GetRandomMove() or state.DoRandomRollout() function.
  6. #
  7. # Example GameState classes for Nim, OXO and Othello are included to give some idea of how you
  8. # can write your own GameState use UCT in your 2-player game. Change the game to be played in
  9. # the UCTPlayGame() function at the bottom of the code.
  10. #
  11. # Written by Peter Cowling, Ed Powley, Daniel Whitehouse (University of York, UK) September 2012.
  12. #
  13. # Licence is granted to freely use and distribute for any sensible/legal purpose so long as this comment
  14. # remains in any distributed code.
  15. #
  16. # For more information about Monte Carlo Tree Search check out our web site at www.mcts.ai
  17.  
  18.  
  19. from math import log, sqrt
  20. import random
  21. import numpy as np
  22. from copy import deepcopy
  23.  
  24.  
  25.  
  26.  
  27. class BigGameState:
  28.     def __init__(self):
  29.         self.board = np.zeros((10, 10), dtype="int8")
  30.         self.curr = 1
  31.         self.playerJustMoved = 2 # At the root pretend the player just moved is player 2 - player 1 has the first move
  32.        
  33.     def Clone(self):
  34.         """ Create a deep clone of this game state.
  35.        """
  36.         st = BigGameState()
  37.         st.playerJustMoved = self.playerJustMoved
  38.         st.curr = self.curr
  39.         st.board = deepcopy(self.board)
  40.         return st
  41.  
  42.     def DoMove(self, move):
  43.         """ Update a state by carrying out the given move.
  44.            Must update playerJustMoved.
  45.        """
  46.         self.playerJustMoved = 3 - self.playerJustMoved
  47.         if move >= 1 and move <= 9 and move == int(move) and self.board[self.curr][move] == 0:
  48.             self.board[self.curr][move] = self.playerJustMoved
  49.             self.curr = move
  50.  
  51.     def GetMoves(self):
  52.         """ Get all possible moves from this state.
  53.        """
  54.         return [i for i in range(1, 10) if self.board[self.curr][i] == 0]
  55.  
  56.     def GetResult(self, playerjm):
  57.         """ Get the game result from the viewpoint of playerjm.
  58.        """
  59.         for bo in self.board:
  60.             for (x,y,z) in [(1,2,3),(4,5,6),(7,8,9),(1,4,7),(2,5,8),(3,6,9),(1,5,9),(3,5,7)]:
  61.                 if bo[x] == [y] == bo[z]:
  62.                     if bo[x] == playerjm:
  63.                         return 1.0
  64.                     else:
  65.                         return 0.0
  66.         if self.GetMoves() == []: return 0.5 # draw
  67.  
  68.     def drawboard(self):
  69.         print_board_row(self.board, 1, 2, 3, 1, 2, 3)
  70.         print_board_row(self.board, 1, 2, 3, 4, 5, 6)
  71.         print_board_row(self.board, 1, 2, 3, 7, 8, 9)
  72.         print(" ------+-------+------")
  73.         print_board_row(self.board, 4, 5, 6, 1, 2, 3)
  74.         print_board_row(self.board, 4, 5, 6, 4, 5, 6)
  75.         print_board_row(self.board, 4, 5, 6, 7, 8, 9)
  76.         print(" ------+-------+------")
  77.         print_board_row(self.board, 7, 8, 9, 1, 2, 3)
  78.         print_board_row(self.board, 7, 8, 9, 4, 5, 6)
  79.         print_board_row(self.board, 7, 8, 9, 7, 8, 9)
  80.         print()
  81.  
  82.  
  83. def print_board_row(board, a, b, c, i, j, k):
  84.     # The marking script doesn't seem to like this either, so just take it out to submit
  85.     print("", board[a][i], board[a][j], board[a][k], end = " | ")
  86.     print(board[b][i], board[b][j], board[b][k], end = " | ")
  87.     print(board[c][i], board[c][j], board[c][k])
  88.  
  89.  
  90. class Node:
  91.     """ A node in the game tree. Note wins is always from the viewpoint of playerJustMoved.
  92.        Crashes if state not specified.
  93.    """
  94.     def __init__(self, move = None, parent = None, state = None):
  95.         self.move = move # the move that got us to this node - "None" for the root node
  96.         self.parentNode = parent # "None" for the root node
  97.         self.childNodes = []
  98.         self.wins = 0
  99.         self.visits = 0
  100.         self.untriedMoves = state.GetMoves() # future child nodes
  101.         self.playerJustMoved = state.playerJustMoved # the only part of the state that the Node needs later
  102.  
  103.        
  104.     def UCTSelectChild(self):
  105.         """ Use the UCB1 formula to select a child node. Often a constant UCTK is applied so we have
  106.            lambda c: c.wins/c.visits + UCTK * sqrt(2*log(self.visits)/c.visits to vary the amount of
  107.            exploration versus exploitation.
  108.        """
  109.         s = sorted(self.childNodes, key = lambda c: c.wins/c.visits + 0.2 * sqrt(2*log(self.visits)/c.visits))[-1]
  110.         return s
  111.    
  112.     def AddChild(self, m, s):
  113.         """ Remove m from untriedMoves and add a new child node for this move.
  114.            Return the added child node
  115.        """
  116.         n = Node(move = m, parent = self, state = s)
  117.         self.untriedMoves.remove(m)
  118.         self.childNodes.append(n)
  119.         return n
  120.    
  121.     def Update(self, result):
  122.         """ Update this node - one additional visit and result additional wins. result must be from the viewpoint of playerJustmoved.
  123.        """
  124.         self.visits += 1
  125.         self.wins += result
  126.  
  127.     def __repr__(self):
  128.         return "[M:" + str(self.move) + " W/V:" + str(self.wins) + "/" + str(self.visits) + " U:" + str(self.untriedMoves) + "]"
  129.  
  130.     def TreeToString(self, indent):
  131.         s = self.IndentString(indent) + str(self)
  132.         for c in self.childNodes:
  133.              s += c.TreeToString(indent+1)
  134.         return s
  135.  
  136.     def IndentString(self,indent):
  137.         s = "\n"
  138.         for i in range (1,indent+1):
  139.             s += "| "
  140.         return s
  141.  
  142.     def ChildrenToString(self):
  143.         s = ""
  144.         for c in self.childNodes:
  145.              s += str(c) + "\n"
  146.         return s
  147.  
  148.  
  149. def UCT(rootstate, itermax, verbose = False):
  150.     """ Conduct a UCT search for itermax iterations starting from rootstate.
  151.        Return the best move from the rootstate.
  152.        Assumes 2 alternating players (player 1 starts), with game results in the range [0.0, 1.0]."""
  153.  
  154.     rootnode = Node(state = rootstate)
  155.  
  156.     for i in range(itermax):
  157.         node = rootnode
  158.         state = rootstate.Clone()
  159.  
  160.         # Select
  161.         while node.untriedMoves == [] and node.childNodes != []: # node is fully expanded and non-terminal
  162.             node = node.UCTSelectChild()
  163.             state.DoMove(node.move)
  164.  
  165.         # Expand
  166.         if node.untriedMoves != []: # if we can expand (i.e. state/node is non-terminal)
  167.             m = random.choice(node.untriedMoves)
  168.             state.DoMove(m)
  169.             node = node.AddChild(m,state) # add child and descend tree
  170.  
  171.         # Rollout - this can often be made orders of magnitude quicker using a state.GetRandomMove() function
  172.         while state.GetMoves() != []: # while state is non-terminal
  173.             state.DoMove(random.choice(state.GetMoves()))
  174.  
  175.         # Backpropagate
  176.         while node != None: # backpropagate from the expanded node and work back to the root node
  177.             node.Update(state.GetResult(node.playerJustMoved)) # state is terminal. Update node with result from POV of node.playerJustMoved
  178.             node = node.parentNode
  179.  
  180.     # Output some information about the tree - can be omitted
  181.     if (verbose): print(rootnode.TreeToString(0))
  182.     else: print(rootnode.ChildrenToString())
  183.  
  184.     return sorted(rootnode.childNodes, key = lambda c: c.visits)[-1].move # return the move that was most visited
  185.                
  186. def UCTPlayGame():
  187.     """ Play a sample game between two UCT players where each player gets a different number
  188.        of UCT iterations (= simulations = tree nodes).
  189.    """
  190.  
  191.     state = BigGameState() # uncomment to play OXO
  192.  
  193.     while (state.GetMoves() != []):
  194.         state.drawboard()
  195.         m = UCT(rootstate = state, itermax = 1000, verbose = False) # play with values for itermax and verbose = True
  196.         print("Best Move: " + str(m) + "\n")
  197.         state.DoMove(m)
  198.     if state.GetResult(state.playerJustMoved) == 1.0:
  199.         print("Player " + str(state.playerJustMoved) + " wins!")
  200.     elif state.GetResult(state.playerJustMoved) == 0.0:
  201.         print("Player " + str(3 - state.playerJustMoved) + " wins!")
  202.     else: print("Nobody wins!")
  203.  
  204. if __name__ == "__main__":
  205.     """ Play a single game to the end using UCT for both players.
  206.    """
  207.     UCTPlayGame()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement