Example #1
0
    def mctsNormal(self, board):
        root = Node(None, None, None, self.opponent.color)
        # set initial child layer
        initial_moves = board.getAllValidMoves(self.pieces)
        if initial_moves == []:
            return None
        for move in initial_moves:
            #consider using piece size as first play urgency as initialVal
            child = Node(move,
                         root,
                         self.color,
                         initialVal=move[0].size() * 10)
            root.addChild(child)

        num_simulations = 0
        startTime = time.perf_counter()
        while (self.resourcesAvailable(startTime)):
            #selection phase
            currentNode = Node.getMctsLeaf(root)
            #make board accurate for current state
            board.makeMovesInStack(currentNode.moveStack)

            #expansion phase
            useable_pieces = []
            if currentNode.turnColor == self.color:
                # opponents turn, use their pieces
                useable_pieces = self.opponent.getPiecesNotIn(
                    currentNode.moveStack)

            else:
                #our turn, use our pieces
                useable_pieces = self.getPiecesNotIn(currentNode.moveStack)

            valid_moves = board.getAllValidMoves(useable_pieces)
            if valid_moves == []:
                #game in terminal moveStack for this player
                pass
            else:
                # add all substates
                for move in valid_moves:
                    child = Node(move,
                                 currentNode,
                                 move[0].color,
                                 initialVal=move[0].size() * 10)
                    currentNode.addChild(child)

            #simulation phase
            res = self.playoutRandomGame(currentNode, board)
            num_simulations += 1
            #board is returned to initial state

            #backpropogate
            currentNode.backpropogate(res)

        #select highest val node
        node = Node.getMaxFirstLayer(root)
        #Node.delTree(root)
        #print(num_simulations, " simulations executed")
        return node.move