Esempio n. 1
0
    def negamaxBoolean(self, state, depth):
        result = False
        duration = time.process_time() - self.starttime

        #if duration > self.timelimit:
        #self.notdone = True
        #print("[Unknown]\n")
        #return

        if state.get_winner() != None:
            return (state.get_winner() == state.to_play)

        for m in (GoBoardUtil.generate_legal_moves(state,
                                                   state.to_play).split(' ')):
            point = GoBoardUtil.move_to_coord(m, state.size)
            point = state._coord_to_point(point[0], point[1])

            state.move(point, state.to_play)

            success = not self.negamaxBoolean(state, depth + 1)

            state.board[point] = EMPTY
            state.to_play = GoBoardUtil.opponent(state.to_play)

            if success:
                if depth == 0:
                    self.winMoves.append(m)
                result = True
            #if self.notdone:
            #return result
        return result
Esempio n. 2
0
    def play_cmd(self, args):
        """
        play a move as the given color

        Arguments
        ---------
        args[0] : {'b','w'}
            the color to play the move as
            it gets converted to  Black --> 1 White --> 2
            color : {0,1}
            board_color : {'b','w'}
        args[1] : str
            the move to play (e.g. A5)
        """
        try:
            board_color = args[0].lower()
            board_move = args[1]
            color = GoBoardUtil.color_to_int(board_color)
            move = GoBoardUtil.move_to_coord(args[1], self.board.size)
            if move:
                move = self.board._coord_to_point(move[0], move[1])
            else:
                return
            if not self.board.move(move, color):
                return
            self.respond()
        except Exception as e:
            self.respond("illegal move: {} {} {}".format(
                board_color, board_move, str(e)))
Esempio n. 3
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
Esempio n. 4
0
    def feature_move_cmd(self, args):
        
        move = None
        if args[0]=='PASS':
            move = 'PASS'
        else:
            move = GoBoardUtil.move_to_coord(args[0], self.board.size)
            if move:
                move = self.board._coord_to_point(move[0], move[1])
            else:
                self.error("Error in executing the move %s, check given move: %s"%(move,args[1]))
                return
        assert move != None
        response = []
        features = Feature.find_move_feature(self.board, move)
        if features == None:
            self.respond(response)
            return

        for f in features:
            fn = Feature.find_feature_name(f)
            if fn != None:
                response.append(Feature.find_feature_name(f))
            else:
                response.append(self.board.neighborhood_33_pattern_shape(move))
        r = '\n'.join(response)
        self.respond(r)
    def play_cmd(self, args):
        """
        play a move as the given color

        Arguments
        ---------
        args[0] : {'b','w'}
            the color to play the move as
            it gets converted to  Black --> 1 White --> 2
            color : {0,1}
            board_color : {'b','w'}
        args[1] : str
            the move to play (e.g. A5)
        """
        try:
            board_color = args[0].lower()
            board_move = args[1]
            color = GoBoardUtil.color_to_int(board_color)
            if args[1].lower() == 'pass':
                self.debug_msg("Player {} is passing\n".format(args[0]))
                self.respond("illegal move: {} wrong coordinate".format(
                    ' '.join(args)))
                return
            move = GoBoardUtil.move_to_coord(args[1], self.board.size)
            if move:
                move = self.board._coord_to_point(move[0], move[1])
            # move == None on pass
            else:
                self.error(
                    "Error in executing the move %s, check given move: %s" %
                    (move, args[1]))
                return

            #TODO
            check, msg = self.board.move(move, color)
            if not check:
                if msg[0] == "R":
                    self.respond("illegal move: {} occupied".format(
                        ' '.join(args)))
                    return
                if msg[0] == "C":
                    self.respond("illegal move: {} capture".format(
                        ' '.join(args)))
                    return
                if msg[0] == "S":
                    self.respond("illegal move: {} suicide".format(
                        ' '.join(args)))
                    return
            else:
                self.debug_msg("Move: {}\nBoard:\n{}\n".format(
                    board_move, str(self.board.get_twoD_board())))
            self.respond()
        except Exception as e:
            self.respond("illegal move: {} wrong coordinate".format(
                ' '.join(args)))
Esempio n. 6
0
    def genmove_cmd(self, args):
        """
        generate a move for the specified color

        Arguments
        ---------
        args[0] : {'b','w'}
            the color to generate a move for
            it gets converted to  Black --> 1 White --> 2
            color : {0,1}
            board_color : {'b','w'}
        """
        try:
            board_color = args[0].lower()
            color = GoBoardUtil.color_to_int(board_color)
            self.debug_msg("Board:\n{}\nko: {}\n".format(str(self.board.get_twoD_board()),
                                                          self.board.ko_constraint))

            # Assignment4 - policy probabilistic player
            # =========================================
            if color != self.board.current_player:
                self.respond("Opponent's turn")
                return

            move_prob_tuples = self.get_move_prob()
            if move_prob_tuples[0][0] == 'pass':
                self.respond("pass")
                self.go_engine.update('pass')
                self.board.move(None, color)
                return

            # based on
            # https://docs.python.org/3.5/library/random.html
            population = [val for val, cnt in move_prob_tuples for _ in range(int(cnt*1e5))]
            move = random.choice(population)
            move = GoBoardUtil.move_to_coord(move, self.board.size)
            move = self.board._coord_to_point(move[0], move[1])
            # =========================================

            if not self.board.check_legal(move, color):
                move = self.board._point_to_coord(move)
                board_move = GoBoardUtil.format_point(move)
                self.respond("Illegal move: {}".format(board_move))
                traceback.print_exc(file=sys.stdout)
                self.respond('Error: {}'.format(str(e)))
                raise RuntimeError("Illegal move given by engine")

            # move is legal; play it
            self.board.move(move, color)
            self.debug_msg("Move: {}\nBoard: \n{}\n".format(move, str(self.board.get_twoD_board())))
            move = self.board._point_to_coord(move)
            board_move = GoBoardUtil.format_point(move)
            self.respond(board_move)
        except Exception as e:
            self.respond('Error: {}'.format(str(e)))
Esempio n. 7
0
    def genmove_cmd(self, args):
        """
        generate a move for the specified color

        Arguments
        ---------
        args[0] : {'b','w'}
            the color to generate a move for
            it gets converted to  Black --> 1 White --> 2
            color : {0,1}
            board_color : {'b','w'}
        """
        try:
            board_color = args[0].lower()
            color = GoBoardUtil.color_to_int(board_color)

            # First try to solve the state and generate a best move
            to_play_bkp = self.board.to_play
            self.board.to_play = color
            score = self.board.call_search()
            if score == 1:
                # The player can win, make a move
                _, move = self.board.tree_cache[self.board]
                coord = GoBoardUtil.move_to_coord(move, self.board.size)
                point = self.board._coord_to_point(coord[0], coord[1])
                self.board.move(point, color)
                self.respond(GoBoardUtil.format_point(coord))
                return
            # Opponent can win or timeout, use the existing code to generate
            # a random move
            self.board.to_play = to_play_bkp

            move = self.go_engine.get_move(self.board, color)
            if move is None:
                # self.respond("pass")
                self.respond("resign")
                return

            if not self.board.check_legal(move, color):
                move = self.board._point_to_coord(move)
                board_move = GoBoardUtil.format_point(move)
                self.respond("Illegal move: {}".format(board_move))
                raise RuntimeError("Illegal move given by engine")

            # move is legal; play it
            self.board.move(move, color)
            self.debug_msg("Move: {}\nBoard: \n{}\n".format(
                move, str(self.board.get_twoD_board())))
            move = self.board._point_to_coord(move)
            board_move = GoBoardUtil.format_point(move)
            self.respond(board_move)
        except Exception as e:
            self.respond('Error: {}'.format(str(e)))
Esempio n. 8
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
Esempio n. 9
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
Esempio n. 10
0
    def genmove_cmd(self, args):
        """
        generate a move for the specified color

        Arguments
        ---------
        args[0] : {'b','w'}
            the color to generate a move for
            it gets converted to  Black --> 1 White --> 2
            color : {0,1}
            board_color : {'b','w'}
        """
        try:
            board_color = args[0].lower()
            color = GoBoardUtil.color_to_int(board_color)
            self.debug_msg("Board:\n{}\nko: {}\n".format(
                str(self.board.get_twoD_board()), self.board.ko_constraint))

            # Assignment4 - policy max player
            # =========================================
            if color != self.board.current_player:
                self.respond("Opponent's turn")
                return

            move = self.get_move_prob()[0][0]
            if move == 'pass':
                self.respond("pass")
                self.go_engine.update('pass')
                self.board.move(None, color)
                return
            move = GoBoardUtil.move_to_coord(move, self.board.size)
            move = self.board._coord_to_point(move[0], move[1])
            # =========================================

            if not self.board.check_legal(move, color):
                move = self.board._point_to_coord(move)
                board_move = GoBoardUtil.format_point(move)
                self.respond("Illegal move: {}".format(board_move))
                traceback.print_exc(file=sys.stdout)
                self.respond('Error: {}'.format(str(e)))
                raise RuntimeError("Illegal move given by engine")

            # move is legal; play it
            self.board.move(move, color)
            self.debug_msg("Move: {}\nBoard: \n{}\n".format(
                move, str(self.board.get_twoD_board())))
            move = self.board._point_to_coord(move)
            board_move = GoBoardUtil.format_point(move)
            self.respond(board_move)
        except Exception as e:
            self.respond('Error: {}'.format(str(e)))
Esempio n. 11
0
    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
Esempio n. 12
0
    def play_cmd(self, args):
        """
        play a move as the given color

        Arguments
        ---------
        args[0] : {'b','w'}
            the color to play the move as
            it gets converted to  Black --> 1 White --> 2
            color : {0,1}
            board_color : {'b','w'}
        args[1] : str
            the move to play (e.g. A5)
        """
        try:
            board_color = args[0].lower()
            board_move = args[1]
            color = GoBoardUtil.color_to_int(board_color)
            if args[1].lower() == 'pass':
                #GIVES RESPONSE, UNSURE IF ENFORCED AS IN TURN CHANGE=??
                self.debug_msg("Player {} is passing\n".format(args[0]))
                self.respond("Illegal Move: {} is passing".format(args[0]))
                return
            move = GoBoardUtil.move_to_coord(args[1], self.board.size)
            if move:
                move = self.board._coord_to_point(move[0], move[1])
            # move == None on pass
            else:
                self.error(
                    "Error in executing the move %s, check given move: %s" %
                    (move, args[1]))
                return
            if not self.board.move(move, color):
                self.respond("Illegal Move: {}".format(board_move))
                return
            else:
                self.debug_msg("Move: {}\nBoard:\n{}\n".format(
                    board_move, str(self.board.get_twoD_board())))
            self.respond()
            #CHECKS VALID MOVES OF OPPONENT, IF EMPTY WINNING
            if GoBoardUtil.generate_legal_moves(self.board, color) == '':
                if args[0].lower() == "b":
                    self.respond("Black Wins!!")
                if args[0].lower() == "w":
                    self.respond("White Wins!!")
                self.respond("Board has been cleared.")
                self.reset(self.board.size)
        except Exception as e:
            self.respond('Error: {}'.format(str(e)))
Esempio n. 13
0
 def set_free_handicap(self, args):
     """
     clear the board and set free handicap for the game
     Arguments
     ---------
     args[0] : str
         the move to handicap (e.g. B2)
     """
     self.board.reset(self.board.size)
     for point in args:
         move = GoBoardUtil.move_to_coord(point, self.board.size)
         point = self.board._coord_to_point(*move)
         if not self.board.move(point, BLACK):
             self.debug_msg("Illegal Move: {}\nBoard:\n{}\n".format(move, str(self.board.get_twoD_board())))
     self.respond()
Esempio n. 14
0
    def save_states(self, state, value, move):
        key = state.copy()
        self.tree_cache[key] = (value, move)

        # We also solved rotations of the current board state.
        # print(self.get_twoD_board())
        rotations = [
            lambda y, x: (self.rotate(y, x, pi/2)), # rotate 90 degree clockwise
            lambda y, x: (self.rotate(y, x, pi)),  # rotate 180 degree clockwise
            lambda y, x: (self.rotate(y, x, 3*pi/2)) # rotate 270 degree clockwise
        ]
        coord = GoBoardUtil.move_to_coord(move, self.size)
        for T in rotations:
            keyT, moveT = state.transform(T, coord)
            self.tree_cache[keyT] = (value, moveT)
Esempio n. 15
0
def get_dict(board):
    p_dict = dict()
    legal_moves = []
    color = board.current_player
    w = []
    m = []
    p = []
    sims = []
    winrate = []
    wins = []
    moves = board.get_empty_points()
    for move in moves:
        if board.check_legal(move, color) and not board.is_eye(move, color):
            legal_moves.append(move)
    legal_moves.append("PASS")
    for move in legal_moves:
        weight = get_the_prob(move, board)
        if move is not "PASS":
            i = board._point_to_coord(move)
            m.append(GoBoardUtil.format_point(i))
            w.append(weight)
        else:
            m.append("Pass")
            w.append(weight)
    length = len(m)
    gamma_sum = sum(w)
    for i in range(length):
        p.append(w[i] / gamma_sum)
    h_prob = max(p)
    for i in range(length):
        sims.append(int(round((p[i] / h_prob) * 10)))
        winrate.append((((p[i] / h_prob) + 1) * 0.5))
        wins.append(int(round(winrate[i] * ((p[i] / h_prob) * 10))))
    results = sort_function(m, sims, winrate, wins)
    results = split_list(results)
    results = sorted(sorted(results, key=lambda x: x[0]),
                     key=lambda x: x[3],
                     reverse=True)
    for result in results:
        if result[0] is not "Pass":
            move = GoBoardUtil.move_to_coord(result[0], board.size)
            m = board._coord_to_point(move[0], move[1])
            p_dict[m] = (int(result[1]), int(result[2]))
        else:
            p_dict["Pass"] = (int(result[1]), int(result[2]))
    return p_dict
Esempio n. 16
0
    def play_cmd(self, args):
        """
        play a move as the given color

        Arguments
        ---------
        args[0] : {'b','w'}
            the color to play the move as
            it gets converted to  Black --> 1 White --> 2
            color : {0,1}
            board_color : {'b','w'}
        args[1] : str
            the move to play (e.g. A5)
        """
        #  print("play_cmd")
        try:
            #  print("play_cmd try") # remove
            board_color = args[0].lower()
            board_move = args[1]
            color = GoBoardUtil.color_to_int(board_color)
            if args[1].lower() == 'pass':
                #print("play_cmd if #1")

                self.debug_msg("Player {} is passing\n".format(args[0]))
                self.respond()
                return
            move = GoBoardUtil.move_to_coord(args[1], self.board.size)
            if move:  # if move is a1, move is (1, 1). the numeric version of args[1]
                #   print("play_cmd if #2") # remove
                #    print("move: ", move) # remove
                #          print("args[1]: ", args[1]) # remove
                move = self.board._coord_to_point(move[0], move[1])
            # move == None on pass
            else:
                self.error(
                    "Error in executing the move %s, check given move: %s" %
                    (move, args[1]))
                return
            if not self.board.move(move, color):
                return
            else:
                self.debug_msg("Move: {}\nBoard:\n{}\n".format(
                    board_move, str(self.board.get_twoD_board())))
            self.respond()
        except Exception as e:  # illegal chars handled here
            self.respond('Error: {}'.format(str(e)))
Esempio n. 17
0
    def genmove(self, args):
        #original code from util
        """
        generate a move for the specified color

        Arguments
        ---------
        args[0] : {'b','w'}
            the color to generate a move for
            it gets converted to  Black --> 1 White --> 2
            color : {0,1}
            board_color : {'b','w'}
        """
        try:
            board_color = args[0].lower()
            color = GoBoardUtil.color_to_int(board_color)
            self.debug_msg("Board:\n{}\nko: {}\n".format(
                str(self.board.get_twoD_board()), self.board.ko_constraint))

            solver_color, solver_move = self.solve_genmove("1")
            move = self.go_engine.get_move(self.board, color)
            if move is None:
                self.respond("pass")
                return
            if (solver_color == self.color_convert(color)):
                moves = list(
                    GoBoardUtil.move_to_coord(solver_move, self.board.size))
                solver_move = self.board._coord_to_point(moves[0], moves[1])
                move = solver_move

            elif not self.board.check_legal(move, color):
                move = self.board._point_to_coord(move)
                board_move = GoBoardUtil.format_point(move)
                self.respond("Illegal move: {}".format(board_move))
                raise RuntimeError("Illegal move given by engine")

            # move is legal; play it
            self.board.move(move, color)

            self.debug_msg("Move: {}\nBoard: \n{}\n".format(
                move, str(self.board.get_twoD_board())))
            move = self.board._point_to_coord(move)
            board_move = GoBoardUtil.format_point(move)
            self.respond(board_move)
        except Exception as e:
            self.respond('Error: {}'.format(str(e)))
Esempio n. 18
0
    def play(self, args):
        """
        play a move as the given color

        Arguments
        ---------
        args[0] : {'b','w'}
            the color to play the move as
            it gets converted to  Black --> 1 White --> 2
            color : {0,1}
            board_color : {'b','w'}
        args[1] : str
            the move to play (e.g. A5)
        """
        # self.respond(args)
        try:
            board_color = args[0].lower()
            board_move = args[1]
            color = GoBoardUtil.color_to_int(board_color)
            if args[1].lower() == 'pass':
                self.debug_msg("Player {} is passing\n".format(args[0]))
                self.board.move(None, color)
                self.board.current_player = GoBoardUtil.opponent(color)

                return
            move = GoBoardUtil.move_to_coord(args[1], self.board.size)
            if move:
                move = self.board._coord_to_point(move[0], move[1])
            # move == None on pass
            else:
                self.error(
                    "Error in executing the move %s, check given move: %s" %
                    (move, args[1]))
                return
            if not self.board.move(move, color):
                pass
                # self.respond("Illegal Move: {}".format(board_move))
                return
            else:
                self.debug_msg("Move: {}\nBoard:\n{}\n".format(
                    board_move, str(self.board.get_twoD_board())))

        except Exception as e:
            # self.respond('Error: {}'.format(str(e)))
            pass
Esempio n. 19
0
    def negamaxBoolean(self, colour):
        time_spent = time.process_time() - self.entry_time
        if time_spent > self.timelimit:
            self.timed_out = True
            return False, None

        if self.board.end_of_game():
            col, score = self.board.score(self.go_engine.komi)
            # we don't need the score or the move. We are simply returning which colour has won from the perspective of this colour
            if col == colour:
                return True, None
            else:
                return False, None

        non_eye_moves = GoBoardUtil.generate_legal_moves(
            self.board, colour).strip().split(" ")
        if non_eye_moves[0] == '':
            # the game isn't over but this colour has no moves to take and will pass
            non_eye_moves = []
        non_eye_moves = [
            GoBoardUtil.move_to_coord(m, self.board.size)
            for m in non_eye_moves
        ]
        non_eye_moves = [
            self.board._coord_to_point(m[0], m[1]) for m in non_eye_moves
        ]
        non_eye_moves = [
            m for m in non_eye_moves if not self.board.is_eye(m, colour)
        ]
        non_eye_moves.sort(key=self.my_key, reverse=True)
        if non_eye_moves == []:
            # since the player has no moves, instead make it pass
            non_eye_moves = [None]
        for m in non_eye_moves:
            self.board.move(m, colour)
            opponent_success, move = self.negamaxBoolean(
                GoBoardUtil.opponent(colour))
            success = not opponent_success
            self.board.undo_move()
            if success:
                # most interested in obtaining the move that generated the win for the first iteration into this method, the other sequence of moves are lost
                return True, m
        # we don't need to know which move results in a loss
        return False, None
Esempio n. 20
0
    def play_cmd(self, args):
        """
        play a move as the given color

        Arguments
        ---------
        args[0] : {'b','w'}
            the color to play the move as
            it gets converted to  Black --> 1 White --> 2
            color : {0,1}
            board_color : {'b','w'}
        args[1] : str
            the move to play (e.g. A5)
        """
        try:
            board_color = args[0].lower()
            board_move = args[1]
            color = GoBoardUtil.color_to_int(board_color)
            if args[1].lower() == 'pass':
                ##                self.debug_msg("Player {} is passing\n".format(args[0]))		 +                self.debug_msg("Passing not allowed\n".format(args[0]))
                ##                self.respond()
                ##                return
                raise ValueError("wrong coordinate")
            move = GoBoardUtil.move_to_coord(args[1], self.board.size)
            if move:
                move = self.board._coord_to_point(move[0], move[1])
            # move == None on pass
            else:
                self.error(
                    "Error in executing the move %s, check given move: %s" %
                    (move, args[1]))
                return
            if not self.board.move(move, color):
                msg = self.board.getMsg(move, color)
                self.respond("illegal move: {} {} {}".format(
                    board_color, board_move, msg))
                return
            else:
                self.debug_msg("Move: {}\nBoard:\n{}\n".format(
                    board_move, str(self.board.get_twoD_board())))
            self.respond()
        except Exception as e:
            self.respond('illegal move: {} {} {}'.format(
                board_color, board_move, str(e)))
Esempio n. 21
0
    def alphabeta(self, state, alpha, beta, d):

        duration = time.process_time() - self.starttime

        if self.notdone or self.winMoves != []:
            return 'a'

        if duration > self.timelimit:
            self.notdone = True
            #print("[Unknown]\n")
            return 'a'

        if state.get_winner() != None:
            return state.staticallyEvaluateForToPlay()

        for m in (GoBoardUtil.generate_legal_moves(state,
                                                   state.to_play).split(' ')):
            point = GoBoardUtil.move_to_coord(m, state.size)
            point = state._coord_to_point(point[0], point[1])

            state.move(point, state.to_play)
            try:
                value = -int(self.alphabeta(state, -beta, -alpha, d + 1))
            except:
                state.board[point] = EMPTY
                state.to_play = GoBoardUtil.opponent(state.to_play)
                return 'a'

            state.board[point] = EMPTY
            state.to_play = GoBoardUtil.opponent(state.to_play)

            if value > alpha:
                alpha = value
                if d == 0 and value >= 0:
                    self.winMoves.append(m)
                    return 'a'

            if self.notdone or self.winMoves != []:
                return 'a'

            if value >= beta:
                return beta  # or value in failsoft (later)
        return alpha
Esempio n. 22
0
    def arg_error(self, cmd, argnum, args):
        """
        checker funciton for the number of arguments given to a command

        Arguments
        ---------
        cmd : str
            the command name
        argnum : int
            number of parsed argument

        Returns
        -------
        True if there was an argument error
        False otherwise
        """
        # Additional error handling:
        if cmd.lower() == 'play':
            if argnum != 2:
                self.respond('illegal move: %s wrong number of arguments' %(args[0]))
                return True
            elif args[0].lower() not in ['w', 'b']:
                self.respond('illegal move: %s %s wrong color' %(args[0], args[1]))
                return True
            else:
                try:
                    # print('\t', args[1], self.board.size)
                    move = GoBoardUtil.move_to_coord(
                            args[1], self.board.size)
                except ValueError:
                    self.respond(
                            'illegal move: %s %s wrong coordinate'
                            %(args[0], args[1]))
                    return True

        if cmd in self.argmap and self.argmap[cmd][0] > argnum:
                self.error(self.argmap[cmd][1])
                return True
        return False
Esempio n. 23
0
    def set_free_handicap(self, args):
        """
        clear the board and set free handicap for the game

        Arguments
        ---------
        args[0] : str
            the move to handicap (e.g. B2)
        """
        self.board.reset(self.board.size)
        for point in args:
            move = GoBoardUtil.move_to_coord(point, self.board.size)
            point = self.board._coord_to_point(*move)
            if not self.board.move(point, BLACK):
                self.debug_msg("Illegal Move: {}\nBoard:\n{}\n".format(move, str(self.board.get_twoD_board())))
        self.respond()

        """
        """
        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))

    def num_sim_cmd(self, args):
        self.go_engine.num_simulation = int(args[0])
        self.respond()

    def go_param_cmd(self, args):
        valid_values = [0,1]
        valid_params = ['selfatari','pattern']
        param = args[0]
        param_value = int(args[1])
        if param not in valid_params:
            self.error('Unkown parameters: {}'.format(param))
        if param_value not in valid_values:
            self.error('Argument 2 ({}) must be of type bool'.format(param_value))
        if param ==valid_params[1]:
            self.go_engine.pattern = param_value
        elif param == valid_params[0]:
            self.go_engine.selfatari = param_value
        self.param_options[param] = param_value
        self.respond()

    def policy_moves_cmd(self, args):
        """
            Return list of policy moves for the current_player of the board
        """
        policy_moves, type_of_move = GoBoardUtil.generate_all_policy_moves(self.board,
                                                self.go_engine.pattern,
                                                self.go_engine.selfatari,
                                                )
        if len(policy_moves) == 0:
            self.respond("Pass")
        else:
            response = type_of_move + " " + GoBoardUtil.sorted_point_string(policy_moves, self.board.NS)
            self.respond(response)

    def random_moves_cmd(self, args):
        """
            Return list of random moves (legal, but not eye-filling)
Esempio n. 24
0
    def genmove_cmd(self, args):
        """
        generate a move for the specified color

        Arguments
        ---------
        args[0] : {'b','w'}
            the color to generate a move for
            it gets converted to  Black --> 1 White --> 2
            color : {0,1}
            board_color : {'b','w'}
        """
        try:
            self.notdone = False
            board_color = args[0].lower()
            color = GoBoardUtil.color_to_int(board_color)
            #TODO
            if self.board.get_winner() != None:
                self.respond("resign")
                return
            self.winMoves = []
            self.genCall = True
            if args[0] != None:
                if args[0] == 'b':
                    self.board.to_play = BLACK
                else:
                    self.board.to_play = WHITE
            self.solve_cmd(args)

            self.genCall = False

            if len(self.winMoves) != 0:
                row, col = GoBoardUtil.move_to_coord(self.winMoves[0],
                                                     self.board.size)
                move = self.board._coord_to_point(row, col)
                #self.respond(self.winMoves[0])

            else:
                move = GoBoardUtil.generate_random_move(self.board, color)
                move = self.board._point_to_coord(move)
                move = GoBoardUtil.format_point(move)
                row, col = GoBoardUtil.move_to_coord(move, self.board.size)
                move = self.board._coord_to_point(row, col)
                #self.respond(move)

            if not self.board.check_legal(move, color):
                move = self.board._point_to_coord(move)
                board_move = GoBoardUtil.format_point(move)
                self.respond("Illegal move: {}".format(board_move))
                raise RuntimeError("Illegal move given by engine")

            # move is legal; play it

            self.board.move(move, color)
            self.debug_msg("Move: {}\nBoard: \n{}\n".format(
                move, str(self.board.get_twoD_board())))
            move = self.board._point_to_coord(move)
            board_move = GoBoardUtil.format_point(move)
            self.respond(board_move)
        except Exception as e:
            self.respond('Error: {}'.format(str(e)))