Beispiel #1
0
 def legal_moves_cmd(self, args):
     """
     list legal moves for current player
     """
     color = self.board.current_player
     legal_moves = GoBoardUtil.generate_legal_moves(self.board, color)
     self.respond(GoBoardUtil.sorted_point_string(legal_moves, self.board.NS))
Beispiel #2
0
    def genmove_cmd(self, args):
        """
        Generate a move for the color args[0] in {'b', 'w'}, for the game of gomoku.
        """
        board_color = args[0].lower()
        color = color_to_int(board_color)

        ans = self.solve(True)

        if ans != None:
            self.board.play_move(ans, color)
            move_coord = point_to_coord(ans, self.board.size)
            move_as_string = format_point(move_coord)
            self.respond(move_as_string.lower())
            return
        else:

            move = GoBoardUtil.generate_legal_moves(self.board, color)
            if move == []:
                self.respond("resign")
                return
            move_coord = point_to_coord(move[0], self.board.size)
            move_as_string = format_point(move_coord)

            self.board.play_move(move[0], color)
            self.respond(move_as_string.lower())
Beispiel #3
0
 def probabilitySimulation(board, WU):
     """
     Given a WeightUtil object, randomly generates moves according
     to the pattern-based probabilistic and returns the winning
     color when the game is over. Recalculates all patterns after
     every move, could be made more efficient by storing patterns
     and weights and only recalculating patterns that neighbour 
     previous moves.
     """
     timeout = len(board.get_empty_points())
     for i in range(timeout):
         color = board.current_player
         moves = GoBoardUtil.generate_legal_moves(board, color)
         if not moves:
             return GoBoardUtil.opponent(color)
         weights = []
         for move in moves:
             index = WU.getindex(board, move)
             weight = WU.getweight(index)
             weights.append(weight)
         npWeights = np.array(weights)
         # Normalize weights to sum to 1
         npWeights = npWeights * (1. / npWeights.sum())
         move = np.random.choice(moves, p=npWeights)
         board.play_move(move, color)
     print("Error: Played too many moves!")
Beispiel #4
0
 def gogui_rules_legal_moves_cmd(self, args):
     """ Implement this function for Assignment 1 """
     moves = GoBoardUtil.generate_legal_moves(self.board,
                                              self.board.current_player)
     moves = map(lambda m: point_to_coord(m, self.board.size), moves)
     moves = list(map(format_point, moves))
     self.respond(' '.join(moves))
Beispiel #5
0
    def negamax(self, board, color, depth, connection):
        timeElapsed = time.process_time() - self.startTime
        if timeElapsed > connection.timelimit:
            self.timedOut = True
            return False, None

        if depth == self.max_depth:
            winner, score = board.score(self.komi)
            if winner == color:
                return True, None
            else:
                return False, None
        if board.end_of_game():
            winner, score = board.score(self.komi)
            if winner == color:
                return True, None
            else:
                return False, None
        moves = GoBoardUtil.generate_legal_moves(board,
                                                 color).strip().split(' ')
        for _m in moves:
            m = GoBoardUtil.move_to_coord(_m, board.size)
            m = board._coord_to_point(m[0], m[1])
            if board.is_eye(m, color):
                continue
            board.move(m, color)
            value, _ = self.negamax(board, GoBoardUtil.opponent(color),
                                    depth + 1, connection)
            value = not value
            board.undo_move()
            if value:
                return True, m
        return False, None
Beispiel #6
0
 def legal_moves_for_toPlay_cmd(self, args):
     try:
         color = self.board.current_player
         moves = GoBoardUtil.generate_legal_moves(self.board, color)
         self.respond(moves)
     except Exception as e:
         self.respond('Error: {}'.format(str(e)))
    def getPatternMoveWeights(self, state, toPlay):
        weights = {}

        for move in GoBoardUtil.generate_legal_moves(state, toPlay):
            weight = self.isPattern(state, move, toPlay)
            weights[move] = weight

        return weights
 def get_random_move_prob(self, state, toPlay):
     legal_moves = GoBoardUtil.generate_legal_moves(state, toPlay)
     moves = []
     for move in legal_moves:
         moves.append(format_point(point_to_coord(move, self.board.size)))
     prob = str(round(1 / len(legal_moves), 3))
     moves.sort()
     probs = [prob] * len(legal_moves)
     return "" + " ".join(moves + probs)
Beispiel #9
0
 def get_winner(self):
     """
     Returns:
     winner: color of winner, if the game is over, or None if not
     """
     if len(GoBoardUtil.generate_legal_moves(self, self.to_play)) == 0:
         return GoBoardUtil.opponent(self.to_play)
     else:
         return None
Beispiel #10
0
 def gogui_rules_final_result_cmd(self, args):
     """ Implement this function for Assignment 1 """
     """ if legal moves are available to a player, then the game is not over """
     if GoBoardUtil.generate_legal_moves(self.board,
                                         self.board.current_player):
         self.respond("unknown")
     else:
         winner = "black" if self.board.current_player == WHITE else "white"
         self.respond(winner)
Beispiel #11
0
    def gogui_rules_legal_moves_cmd(self, args):
        """ Implement this function for Assignment 1 """
        finalResult = self.return_string(args)
        if finalResult != "unknown":
            self.respond("")
            return

        color = color_to_int('b')
        moves = GoBoardUtil.generate_legal_moves(self.board, color)
        color = color_to_int('w')
        moves2 = GoBoardUtil.generate_legal_moves(self.board, color)
        moves += list(set(moves2) - set(moves))
        gtp_moves = []
        for move in moves:
            coords = point_to_coord(move, self.board.size)
            gtp_moves.append(format_point(coords))
        sorted_moves = ' '.join(sorted(gtp_moves))
        self.respond(sorted_moves)
Beispiel #12
0
 def simulate(self, board, color):
     current_player = board.current_player
     moves = GoBoardUtil.generate_legal_moves(board, current_player)
     if len(moves) == 0:
         return 3 - current_player
     move = np.random.choice(moves)
     board.board[move] = current_player
     board.current_player = 3 - current_player
     return self.simulate(board, color)
Beispiel #13
0
    def gogui_rules_legal_moves_cmd(self, args):  #--------DONE----------------
        """ Implement this function for Assignment 1
            Produce a list of all legal moves for
            the current player, in alphabetic order. """
        colour = self.board.current_player
        if colour == 1:
            colour = 'b'
        else:
            colour = 'w'
        #print("#############:", colour)
        board_color = colour.lower()
        color = color_to_int(board_color)
        moves = GoBoardUtil.generate_legal_moves(self.board,
                                                 self.board.current_player)
        gtp_moves = []
        for move in moves:
            # check if a PASS
            if move == "PASS":
                continue
            coords = point_to_coord(move, self.board.size)
            if self.board.board[move] != 0:
                continue
            board_copy = self.board.copy()
            opp_color = GoBoardUtil.opponent(color)
            board_copy.board[move] = color
            capture = False
            single_captures = []
            neighbors = board_copy._neighbors(move)
            No = False
            for nb in neighbors:
                if board_copy.board[nb] == opp_color:
                    single_capture = None
                    opp_block = board_copy._block_of(nb)
                    if not board_copy._has_liberty(opp_block):
                        captures = list(where1d(opp_block))
                        board_copy.board[captures] = 0
                        if len(captures) == 1:
                            single_capture = nb
                        if len(captures) >= 1:
                            No = True
                            break
                    if single_capture != None:
                        # use single captures to detect suicide
                        single_captures.append(single_capture)
            if not No:
                if single_captures != []:
                    continue
                block = board_copy._block_of(move)
                if not board_copy._has_liberty(block):  # undo suicide move
                    continue

                gtp_moves.append(format_point(coords))

        # put it all in a list
        sorted_moves = ' '.join(sorted(gtp_moves))
        self.respond(sorted_moves)
 def gogui_rules_final_result_cmd(self, args):
     """ Implement this function for Assignment 1 """
     moves = GoBoardUtil.generate_legal_moves(self.board, BLACK) # should be same regardless of player
     if self.board.winner:
         winner = "black" if self.board.winner == BLACK else "white"
         self.respond(winner)
     elif len(moves) == 0:
         self.respond("draw")
     else:
         self.respond("unknown")
Beispiel #15
0
    def get_move(self, board, color):
        move = GoBoardUtil.generate_legal_moves(board, color)
        moves = GoBoardUtil.gen1_move(board, color, move)

        if moves != None:

            rand = random.randint(0, len(moves) - 1)
            return moves[rand]

        return None
Beispiel #16
0
 def gogui_rules_legal_moves_cmd(self, args):
     """ Implement this function for Assignment 1 """
     moves = GoBoardUtil.generate_legal_moves(self.board,
                                              self.board.current_player)
     gtp_moves = []
     for move in moves:
         coords = point_to_coord(move, self.board.size)
         gtp_moves.append(format_point(coords))
     sorted_moves = ' '.join(sorted(gtp_moves))
     self.respond(sorted_moves)
Beispiel #17
0
    def solve(self, return_val=False):

        try:
            self.hash = {}

            current_depth = 0

            color = self.board.current_player
            moves = GoBoardUtil.generate_legal_moves(self.board, color)

            tempboard = self.board.copy()
            tempboard.current_player = 3 - color

            signal.signal(signal.SIGALRM, self.handler)
            signal.alarm(self._timelimit)

            for move in moves:
                tempboard.board[move] = color

                # tempboard.play_move(move,color)
                # if self.minimax(tempboard,color,current_depth+1) == color:

                if not self.negamax(tempboard, 1):
                    signal.alarm(0)

                    move_coord = point_to_coord(move, tempboard.size)
                    move_as_string = format_point(move_coord)

                    if return_val == True:
                        return (move)

                    if self.board.current_player == 1:
                        self.respond("b " + move_as_string.lower())
                    else:
                        self.respond("w " + move_as_string.lower())

                    return None

                tempboard.board[move] = EMPTY
            signal.alarm(0)
            if return_val == True:
                return None

            if self.board.current_player == 1:
                self.respond("w")
            else:
                self.respond("b")

        except TimeoutError:
            self.respond("unknown")
            signal.alarm(0)
            return None

        signal.alarm(0)
        return None
Beispiel #18
0
 def legal_moves_cmd(self, args):
     #List legal moves for color args[0] in {'b','w'}
     board_color = args[0].lower()
     color = color_to_int(board_color)
     moves = GoBoardUtil.generate_legal_moves(self.board, color)
     gtp_moves = []
     for move in moves:
         coords = point_to_coord(move, self.board.size)
         gtp_moves.append(format_point(coords))
     sorted_moves = ' '.join(sorted(gtp_moves))
     self.respond(sorted_moves)
Beispiel #19
0
 def gogui_rules_final_result_cmd(self, args):
     """ Implement this function for Assignment 1 """
     if self.board.winner == 1:
         self.respond("black")
     elif self.board.winner == 2:
         self.respond("white")
     elif self.board.winner == None and len(
             GoBoardUtil.generate_legal_moves(self.board, 1)) == 0:
         self.respond("draw")
     else:
         self.respond("unknown")
Beispiel #20
0
    def search(self):
        '''
        Negamax with early stop + lookup table
        Return:
            1 if the current player can win
            0 timeout
            -1 if the opponent can win
        '''
        # if time.time() > self.timeout:
        if time.process_time() > self.timeout:
            return 0

        try:
            # hit cache, no need to search remaining children
            value, _ = self.tree_cache[self]
            self.hit += 1
            return value
        except KeyError:
            winner = self.get_winner()
            # if winner == self.to_play:
            # return 1
            # if winner == GoBoardUtil.opponent(self.to_play):
            # return -1
            if winner == None:
                legal_moves = GoBoardUtil.generate_legal_moves(
                    self, self.to_play).split()
                if len(legal_moves) == 0:
                    return -1
                for move in legal_moves:
                    coord = GoBoardUtil.move_to_coord(move, self.size)
                    point = self._coord_to_point(coord[0], coord[1])
                    self.move(point, self.to_play)
                    value = -self.search()
                    self.undo()
                    if value == 1:
                        # We know the max score is 1, so we can stop search.
                        # Save the current state with the best move to the
                        # lookup table.
                        self.save_states(self, value, move)

                        # We solved the main diagonal symmetry state
                        main_diag_symm = lambda y, x: (x, y)
                        symm, moveT = self.copy().transform(
                            main_diag_symm, coord)
                        # print(self.get_twoD_board())
                        # print(symm.get_twoD_board())
                        self.save_states(symm, value, moveT)
                        return value
                    if value == 0:
                        return 0
                return value
            else:
                return -1
 def legal_moves_for_toPlay_cmd(self, args):
     try:
         color = self.board.current_player
         moves = GoBoardUtil.generate_legal_moves(self.board, color)
         gtp_moves = []
         for move in moves:
             coords = point_to_coord(move, self.board.size)
             gtp_moves.append(format_point(coords))
         sorted_moves = ' '.join(sorted(gtp_moves))
         self.respond(sorted_moves)
     except Exception as e:
         self.respond('Error: {}'.format(str(e)))
Beispiel #22
0
def negamax(node, color, time, delta):
    if int(time.time() - time) > delta:
        return node.score
    children = GoBoardUtil.generate_legal_moves(
        node.state, GoBoardUtil.color_to_int(color))
    for child in children:
        nodecopy = copy.deepcopy(node)
        nodecopy.move(color + child)
        if color == "b":
            v = negamax(nodecopy, "w", time, delta)
        else:
            v = negamax(nodecopy, "b", time, delta)
Beispiel #23
0
    def search_alphabeta(self, alpha, beta):
        '''
        Negamax alpha-beta search + lookup table
        Return:
            1 if the current player can win
            0 timeout
            -1 if the opponent can win
        '''
        # if time.time() > self.timeout:
        if time.process_time() > self.timeout:
            return 0

        # print(self.get_twoD_board())
        try:
            # hit cache, no need to search remaining children
            value, _ = self.tree_cache[self]
            self.hit += 1
            return value
        except KeyError:

            winner = self.get_winner()
            if winner == self.to_play:
                return 1
            elif winner == GoBoardUtil.opponent(self.to_play):
                return -1
            else:
                legal_moves = GoBoardUtil.generate_legal_moves(
                    self, self.to_play).split()
                if len(legal_moves) == 0:
                    return -1
                for move in legal_moves:
                    coord = GoBoardUtil.move_to_coord(move, self.size)
                    point = self._coord_to_point(coord[0], coord[1])
                    self.move(point, self.to_play)
                    value = -self.search_alphabeta(-beta, -alpha)
                    self.undo()
                    if value > alpha:
                        alpha = value
                        # Save the current state with the best move to the
                        # lookup table.
                        self.save_states(self, value, move)

                        # We solved the main diagonal symmetry state
                        main_diag_symm = lambda y, x: (x, y)
                        symm, moveT = self.copy().transform(
                            main_diag_symm, coord)
                        # print(self.get_twoD_board())
                        # print(symm.get_twoD_board())
                        self.save_states(symm, value, moveT)
                    if value >= beta:
                        return beta
                return alpha
Beispiel #24
0
 def test_size_2_legal_moves(self):
     size = 2
     goboard = GoBoard(size)
     moves = GoBoardUtil.generate_legal_moves(goboard, BLACK)
     self.assertEqual(
         moves,
         [
             goboard.pt(1, 1),
             goboard.pt(1, 2),
             goboard.pt(2, 1),
             goboard.pt(2, 2)
         ],
     )
 def startSimulation(self, board, board_color, policy="random"):
     self.board = board
     color = self.color_to_int(board_color)
     legalMoves = GoBoardUtil.generate_legal_moves(self.board, color)
     numLegalMoves = len(legalMoves)
     scores = {}
     for i in range(len(legalMoves)):
         move = legalMoves[i]
         scores[i] = self.simulate(move, color, policy)
     print(scores)
     bestMove = max(scores, key=scores.get)
     print(bestMove)
     return bestMove
Beispiel #26
0
 def gogui_rules_final_result_cmd(self, args):
     """ Implement this function for Assignment 1 """
     color = self.board.check_win()
     if color == BLACK:
         self.respond("black")
     elif color == WHITE:
         self.respond("white")
     else:
         moves = GoBoardUtil.generate_legal_moves(self.board, self.board.current_player)
         if not moves:
             self.respond("draw")
         else:
             self.respond("unknown")
Beispiel #27
0
 def simulate_rule_based(self, board, color):
     #####Fill in here#####
     if len(GoBoardUtil.generate_legal_moves(board, color)) == 0:
         return 'PASS'
     temp_board = board.copy()
     rule, move = GoBoardUtil.generate_rule_move_gomoku(temp_board, color)
     if rule != "Random":
         np.random.shuffle(move)
         return rule, move[0]
         # return move
     else:
         move = self.simulate_random(board, color)
         return "Random", move
Beispiel #28
0
 def gogui_rules_legal_moves_cmd(self, args):
     """ Implement this function for Assignment 1 """
     #board_color = args[0].lower()
     #color = color_to_int(board_color)
     color = 1 if self.board.current_player == BLACK else 2
     moves = GoBoardUtil.generate_legal_moves(self.board, color)
     gtp_moves = []
     for move in moves:
         coords = point_to_coord(move, self.board.size)
         gtp_moves.append(format_point(coords))
     sorted_moves = ' '.join(sorted(gtp_moves))
     self.respond(sorted_moves)
     return
Beispiel #29
0
 def random_policy(self, args):
     #for printing all moves in policy moves
     color = args
     moves = GoBoardUtil.generate_legal_moves(self.board, color)
     np.random.shuffle(moves)
     gtp_moves = []
     for move in moves:
         coords = point_to_coord(move, self.board.size)
         gtp_moves.append(format_point(coords))
     sorted_moves = ' '.join(sorted(gtp_moves))
     if moves:
         self.respond("Random " + sorted_moves)
     else:
         self.respond()
    def negamax(self, pnode, color, curtime, delta):
        if int(time.time() - curtime) > delta:
            #If the timelimit is passed, just return the heuristic value of the move
            return pnode.state.score(self.go_engine.komi)

        #Generate all of the children of the current node
        children = GoBoardUtil.generate_legal_moves(
            pnode.state, GoBoardUtil.color_to_int(color))
        #Which value is the best? I dunno?
        best = float("-inf")
        #Children list comes out as a string for some reason.
        children = children.split(" ")
        children.append('')
        #Go through the children
        movew = ''
        for child in children:
            #If the time is expired, return the score and the child

            nodecopy = node(pnode.state.copy())
            if child == '':
                child = None
                val = nodecopy.state.move(child,
                                          GoBoardUtil.color_to_int(color))

            else:
                coord = GoBoardUtil.move_to_coord(child, self.board.size)
                point = self.board._coord_to_point(coord[0], coord[1])
                val = nodecopy.state.move(point,
                                          GoBoardUtil.color_to_int(color))

            if nodecopy.state.end_of_game():
                return pnode.state.score(self.go_engine.komi)

            if color == "b":
                moved, score = self.negamax(nodecopy, "w", curtime, delta)

            else:
                moved, score = self.negamax(nodecopy, "b", curtime, delta)

            #best = max(best, score)
            if (best < -score):
                best = -score
                movew = moved
            if int(time.time() - curtime) > delta:
                # return movew, best
                return pnode.state.score(self.go_engine.komi)

        #print("returning")
        print("movew", movew)
        return best, movew