Beispiel #1
0
    def __init__(self, go_engine, debug_mode=False):
        """
        object that plays Go using GTP

        Parameters
        ----------
        go_engine: GoPlayer
            a program that is capable of playing go by reading GTP commands
        komi : float
            komi used for the current game
        board: GoBoard
            SIZExSIZE array representing the current board state
        """
        self.stdout = sys.stdout
        self._debug_mode = debug_mode
        sys.stdout = self
        self.go_engine = go_engine
        self.go_engine.komi = 0
        self.go_engine.selfatari = 1
        self.go_engine.pattern = 1
        self.board = GoBoard(7)
        self.commands = {
            "protocol_version": self.protocol_version_cmd,
            "quit": self.quit_cmd,
            "name": self.name_cmd,
            "boardsize": self.boardsize_cmd,
            "showboard": self.showboard_cmd,
            "clear_board": self.clear_board_cmd,
            "komi": self.komi_cmd,
            "version": self.version_cmd,
            "known_command": self.known_command_cmd,
            "set_free_handicap": self.set_free_handicap,
            "genmove": self.genmove_cmd,
            "list_commands": self.list_commands_cmd,
            "play": self.play_cmd,
            "final_score": self.final_score_cmd,
            "legal_moves": self.legal_moves_cmd,
            "num_sim": self.num_sim_cmd,
            "showoptions": self.showoptions_cmd
        }

        # used for argument checking
        # values: (required number or arguments, error message on argnum failure)
        self.argmap = {
            "boardsize": (1, 'Usage: boardsize INT'),
            "komi": (1, 'Usage: komi FLOAT'),
            "known_command": (1, 'Usage: known_command CMD_NAME'),
            "set_free_handicap":
            (1, 'Usage: set_free_handicap MOVE (e.g. A4)'),
            "genmove": (1, 'Usage: genmove {w, b}'),
            "play": (2, 'Usage: play {b, w} MOVE'),
            "legal_moves": (1, 'Usage: legal_moves {w, b}'),
            "num_sim": (1, 'Usage: num_sim #(e.g. num_sim 100 )'),
            "showoptions": (0, 'showotions does not get arguments')
        }
Beispiel #2
0
    def __init__(self, go_engine, debug_mode=False):
        """
        object that plays Go using GTP

        Parameters
        ----------
        go_engine: GoPlayer
            a program that is capable of playing go by reading GTP commands
        debug_mode: prints debug messages
        """
        self.stdout = sys.stdout
        sys.stdout = self
        self._debug_mode = debug_mode
        self.go_engine = go_engine
        self.komi = 0
        self.board = GoBoard(7)
        self.commands = {
            "protocol_version": self.protocol_version_cmd,
            "quit": self.quit_cmd,
            "name": self.name_cmd,
            "boardsize": self.boardsize_cmd,
            "showboard": self.showboard_cmd,
            "clear_board": self.clear_board_cmd,
            "komi": self.komi_cmd,
            "version": self.version_cmd,
            "known_command": self.known_command_cmd,
            "set_free_handicap": self.set_free_handicap,
            "genmove": self.genmove_cmd,
            "list_commands": self.list_commands_cmd,
            "play": self.play_cmd,
            "final_score": self.final_score_cmd,
            "legal_moves": self.legal_moves_cmd,
            "solve": self.solve_cmd,
            "timelimit": self.timeout_cmd,
            "print_toplay": self.print_toplay_cmd
        }

        # used for argument checking
        # values: (required number or arguments, error message on argnum failure)
        self.argmap = {
            "boardsize": (1, 'Usage: boardsize INT'),
            "komi": (1, 'Usage: komi FLOAT'),
            "known_command": (1, 'Usage: known_command CMD_NAME'),
            "set_free_handicap":
            (1, 'Usage: set_free_handicap MOVE (e.g. A4)'),
            "genmove": (1, 'Usage: genmove {w, b}'),
            "play": (2, 'Usage: play {b, w} MOVE'),
            "legal_moves": (1, 'Usage: legal_moves {w, b}'),
            "solve":
            (0,
             'Usage: command takes no arguments, solves for current player.'),
            "timelimit":
            (1, 'Usage: sets maximum time solve and genmove functions may run')
            #"print_toplay":(0, "Usage: command to print current toplay")
        }
Beispiel #3
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)
         ],
     )
Beispiel #4
0
 def test_size_2(self):
     goboard = GoBoard(2)
     self.assertEqual(goboard.size, 2)
     self.assertEqual(goboard.NS, 3)
     self.assertEqual(goboard.WE, 1)
     self.assertEqual(goboard.ko_recapture, None)
     self.assertEqual(goboard.current_player, BLACK)
     self.assertEqual(goboard.maxpoint, 13)
     self.assertEqual(goboard.board[0], BORDER)
     self.assertEqual(goboard.board[goboard.pt(1, 1)], EMPTY)
     self.assertEqual(goboard.board[goboard.pt(1, 2)], EMPTY)
     self.assertEqual(goboard.board[goboard.pt(2, 1)], EMPTY)
     self.assertEqual(goboard.board[goboard.pt(2, 2)], EMPTY)
def run():
    """
    start the gtp connection and wait for commands.
    """
    board = GoBoard(7)
    con = GtpConnection(FlatMCSimPlayer(10, board), board)
    con.start_connection()
Beispiel #6
0
def run():
    """
    start the gtp connection and wait for commands.
    """
    board = GoBoard(7)
    con = GtpConnection(Gomoku(), board)
    con.start_connection()
Beispiel #7
0
def run(sim, sim_rule):
    """
    Start the gtp connection and wait for commands.
    """
    board = GoBoard(7)
    con = GtpConnection(Gomoku3(sim, sim_rule), board)
    con.start_connection()
Beispiel #8
0
 def do_test_pointsets(self, size):
     goboard = GoBoard(size)
     count = count_colors(goboard)
     self.assertEqual(count[EMPTY], size * size)
     self.assertEqual(count[BLACK], 0)
     self.assertEqual(count[WHITE], 0)
     num_border = 3 * (size + 1)
     self.assertEqual(count[BORDER], num_border)
Beispiel #9
0
def playGame(player1, player2):
    t = GoBoard(7)
    numMoves = 0
    while t.winner() == EMPTY and numMoves < 40:
        player = selectPlayer(numMoves, player1, player2)
        t.play_move(player.genMove(t), t.current_player)
        numMoves += 1
    #print("Game winner:", t.winner(), "Moves:", t.moves)
    return t.winner()
def init_pvp():
    #Initiates the pvp objects and variables
    global board
    global board_history
    global start_pva
    global start_pvp
    global turn
    global win
    global win_sequence

    board = GoBoard(15)
    board_history = Board_History()
    start_pva = 0
    start_pvp = 1
    turn = 0
    win = 0
    win_sequence = []
def reset_pvp():
    #resets the pvp objects and variables
    global board
    global board_history
    global last_black
    global last_white
    global start_pvp
    global turn
    global win
    global win_sequence

    board = GoBoard(15)
    board_history = Board_History()
    last_black = None
    last_white = None
    start_pvp = 1
    turn = 0
    win = 0
    win_sequence = []
def init_pva(difficulty):
    #Initiates the pva objects and variables
    global Ai
    global board
    global board_history
    global turn
    global start_pva
    global start_pvp
    global timer
    global win
    global win_sequence

    board = GoBoard()
    board_history = Board_History()
    start_pva = 1
    start_pvp = 0
    Ai = AI(difficulty)
    timer = 0
    turn = 0
    win = 0
    win_sequence = []
def reset_pva():
    #resets the pva objects and variables
    global Ai
    global board
    global board_history
    global last_black
    global last_white
    global start_pvp
    global timer
    global turn
    global win
    global win_sequence

    Ai = AI(difficulty)
    board = GoBoard()
    board_history = Board_History()
    last_black = None
    last_white = None
    start_pva = 1
    timer = 0
    turn = 0
    win = 0
    win_sequence = []
Beispiel #14
0
class GtpConnection():
    def __init__(self, go_engine, outfile='/tmp/gtp_log', debug_mode=False):
        """
        object that plays Go using GTP

        Parameters
        ----------
        go_engine : GoPlayer
            a program that is capable of playing go by reading GTP commands
        komi : float
            komi used for the current game
        board: GoBoard
            SIZExSIZE array representing the current board state
        """
        mode = 'w'
        self.stdout = sys.stdout
        #sys.stdout = outfile
        self._debug_mode = debug_mode
        self.file = open(outfile, mode)
        #self.stderr = sys.stderr
        sys.stdout = self
        self.go_engine = go_engine
        self.komi = 0
        self.board = GoBoard(7)
        self.commands = {
            "protocol_version": self.protocol_version_cmd,
            "quit": self.quit_cmd,
            "name": self.name_cmd,
            "boardsize": self.boardsize_cmd,
            "showboard": self.showboard_cmd,
            "clear_board": self.clear_board_cmd,
            "komi": self.komi_cmd,
            "version": self.version_cmd,
            "known_command": self.known_command_cmd,
            "set_free_handicap": self.set_free_handicap,
            "genmove": self.genmove_cmd,
            "list_commands": self.list_commands_cmd,
            "play": self.play_cmd,
            "final_score": self.final_score_cmd,
            "legal_moves": self.legal_moves_cmd
        }

        # used for argument checking
        # values: (required number or arguments, error message on argnum failure)
        self.argmap = {
            "boardsize": (1, 'Usage: boardsize INT'),
            "komi": (1, 'Usage: komi FLOAT'),
            "known_command": (1, 'Usage: known_command CMD_NAME'),
            "set_free_handicap":
            (1, 'Usage: set_free_handicap MOVE (e.g. A4)'),
            "genmove": (1, 'Usage: genmove {w,b}'),
            "play": (2, 'Usage: play {b,w} MOVE'),
            "legal_moves": (1, 'Usage: legal_moves {w,b}')
        }

    def __del__(self):
        sys.stdout = self.stdout
        self.file.close()

    def write(self, data):
        self.file.write(data)
        self.stdout.write(data)

    def flush(self, ):
        self.stdout.flush()
        self.file.flush()

    def start_connection(self):
        """
        start a GTP connection. This function is what continuously monitors the user's
        input of commands.
        """
        self.debug_msg("Start up successful...\n\n")
        line = sys.stdin.readline()
        while line:
            self.get_cmd(line)
            line = sys.stdin.readline()

    def get_cmd(self, command):
        """
        parse the command and execute it

        Arguments
        ---------
        command : str
            the raw command to parse/execute
        """
        if len(command.strip(' \r\t')) == 0:
            return
        if command[0] == '#':
            return
        # Strip leading numbers from regression tests
        if command[0].isdigit():
            command = re.sub("^\d+", "", command).lstrip()

        elements = command.split()
        if not elements:
            return
        command_name = elements[0]
        args = elements[1:]
        if self.arg_error(command_name, len(args)):
            return
        if command_name in self.commands:
            try:
                self.commands[command_name](args)
            except Exception as e:
                self.debug_msg("Error executing command {}\n".format(str(e)))
                self.debug_msg("Stack Trace:\n{}\n".format(
                    traceback.format_exc()))
                raise e
        else:
            self.debug_msg("Unknown command: {}\n".format(command_name))
            self.error('Unknown command')
            sys.stdout.flush()

    def arg_error(self, cmd, argnum):
        """
        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
        """
        if cmd in self.argmap and self.argmap[cmd][0] > argnum:
            self.error(self.argmap[cmd][1])
            return True
        return False

    def debug_msg(self, msg=''):
        """ Write a msg to the debug stream """
        if self._debug_mode:
            sys.stderr.write(msg)
            sys.stderr.flush()

    def error(self, error_msg=''):
        """ Send error msg to stdout and through the GTP connection. """
        sys.stdout.write('? {}\n\n'.format(error_msg))
        sys.stdout.flush()

    def respond(self, response=''):
        """ Send msg to stdout """
        sys.stdout.write('= {}\n\n'.format(response))
        sys.stdout.flush()

    def reset(self, size):
        """
        Resets the state of the GTP to a starting board

        Arguments
        ---------
        size : int
            the boardsize to reinitialize the state to
        """
        self.board.reset(size)

    def protocol_version_cmd(self, args):
        """ Return the GTP protocol version being used (always 2) """
        self.respond('2')

    def quit_cmd(self, args):
        """ Quit game and exit the GTP interface """
        self.respond()
        exit()

    def name_cmd(self, args):
        """ Return the name of the player """
        self.respond(self.go_engine.name)

    def version_cmd(self, args):
        """ Return the version of the player """
        self.respond(self.go_engine.version)

    def clear_board_cmd(self, args):
        """ clear the board """
        self.reset(self.board.size)
        self.respond()

    def boardsize_cmd(self, args):
        """
        Reset the game and initialize with a new boardsize

        Arguments
        ---------
        args[0] : int
            size of reinitialized board
        """
        self.reset(int(args[0]))
        self.respond()

    def showboard_cmd(self, args):
        self.respond('\n' + str(self.board.get_twoD_board()))

    def komi_cmd(self, args):
        """
        Set the komi for the game

        Arguments
        ---------
        args[0] : float
            komi value
        """
        self.komi = float(args[0])
        self.respond()

    def known_command_cmd(self, args):
        """
        Check if a command is known to the GTP interface

        Arguments
        ---------
        args[0] : str
            the command name to check for
        """
        if args[0] in self.commands:
            self.respond("true")
        else:
            self.respond("false")

    def list_commands_cmd(self, args):
        """ list all supported GTP commands """
        self.respond(' '.join(list(self.commands.keys())))

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

    def legal_moves_cmd(self, args):
        """
        list legal moves for 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'}
        """
        try:
            board_color = args[0].lower()
            color = GoBoardUtil.color_to_int(board_color)
            moves = GoBoardUtil.generate_legal_moves(self.board, color)
            self.respond(moves)
        except Exception as e:
            self.respond('Error: {}'.format(str(e)))

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

    def final_score_cmd(self, args):
        self.respond(self.board.final_score(self.komi))

    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))
            move = self.go_engine.get_move(self.board, color)
            if move is None:
                if args[0].lower() == "b":
                    self.respond("White Wins!!")
                if args[0].lower() == "w":
                    self.respond("Black Wins!!")
                #self.respond("pass")
                self.respond("Board has been cleared.")
                self.reset(self.board.size)
                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)))
Beispiel #15
0
    def __init__(
            self,
            parent,
            id=-1,
            title="围棋打谱 UJS GO",
            pos=wx.DefaultPosition,
            size=(1200, 700),
            style=wx.DEFAULT_FRAME_STYLE | wx.SYSTEM_MENU,
    ):

        wx.Frame.__init__(self, parent, id, title, pos, size, style)

        self._mgr = aui.AuiManager()

        # notify AUI which frame to use
        self._mgr.SetManagedWindow(self)

        # 创建设置
        self.mode = mine

        #
        self.createIcon()

        # 创建定时器
        self.clktime = 2000
        self.timer = wx.Timer(self)

        # 创建菜单
        self.createMenuBar()

        #创建状态条
        self.createStatusBar()

        # 创建面板
        self.history = wx.ListBox(self,
                                  -1,
                                  choices=self.mode.titles,
                                  size=wx.Size(550, 700))

        self.board = GoBoard(wx.Image("back.png"),
                             dataBoard,
                             parent=self,
                             size=(600,
                                   600))  #style=wx.FULL_REPAINT_ON_RESIZE)

        self.stones = wx.ListBox(self,
                                 -1,
                                 choices=dataBoard.strnodes,
                                 size=wx.Size(50, 700))

        # add the panes to the manager
        #self._mgr.AddPane(self.toolbar, aui.AuiPaneInfo().Top())
        self._mgr.AddPane(
            self.history,
            aui.AuiPaneInfo().Left().Caption("历史记录").Name('history'))
        self._mgr.AddPane(
            self.stones,
            aui.AuiPaneInfo().Right().Caption("下棋位置").Name('stone'))
        self._mgr.AddPane(self.board,
                          aui.AuiPaneInfo().CenterPane().Name('board'))
        #self._mgr.AddPane(self.toolbar, aui.AuiPaneInfo().Top())

        # tell the manager to "commit" all the changes just made
        self._mgr.Update()

        #Bind event
        self.stones.Bind(wx.EVT_LISTBOX, self.OnStones)
        self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
        self.Bind(wx.EVT_CLOSE, self.OnClose)

        #
        self.timer2 = wx.Timer(self)
        self.timer2.Start(100)
        self.Bind(wx.EVT_TIMER, self.OnTimer2, self.timer2)
Beispiel #16
0
class MyFrame(wx.Frame):
    def __init__(
            self,
            parent,
            id=-1,
            title="围棋打谱 UJS GO",
            pos=wx.DefaultPosition,
            size=(1200, 700),
            style=wx.DEFAULT_FRAME_STYLE | wx.SYSTEM_MENU,
    ):

        wx.Frame.__init__(self, parent, id, title, pos, size, style)

        self._mgr = aui.AuiManager()

        # notify AUI which frame to use
        self._mgr.SetManagedWindow(self)

        # 创建设置
        self.mode = mine

        #
        self.createIcon()

        # 创建定时器
        self.clktime = 2000
        self.timer = wx.Timer(self)

        # 创建菜单
        self.createMenuBar()

        #创建状态条
        self.createStatusBar()

        # 创建面板
        self.history = wx.ListBox(self,
                                  -1,
                                  choices=self.mode.titles,
                                  size=wx.Size(550, 700))

        self.board = GoBoard(wx.Image("back.png"),
                             dataBoard,
                             parent=self,
                             size=(600,
                                   600))  #style=wx.FULL_REPAINT_ON_RESIZE)

        self.stones = wx.ListBox(self,
                                 -1,
                                 choices=dataBoard.strnodes,
                                 size=wx.Size(50, 700))

        # add the panes to the manager
        #self._mgr.AddPane(self.toolbar, aui.AuiPaneInfo().Top())
        self._mgr.AddPane(
            self.history,
            aui.AuiPaneInfo().Left().Caption("历史记录").Name('history'))
        self._mgr.AddPane(
            self.stones,
            aui.AuiPaneInfo().Right().Caption("下棋位置").Name('stone'))
        self._mgr.AddPane(self.board,
                          aui.AuiPaneInfo().CenterPane().Name('board'))
        #self._mgr.AddPane(self.toolbar, aui.AuiPaneInfo().Top())

        # tell the manager to "commit" all the changes just made
        self._mgr.Update()

        #Bind event
        self.stones.Bind(wx.EVT_LISTBOX, self.OnStones)
        self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
        self.Bind(wx.EVT_CLOSE, self.OnClose)

        #
        self.timer2 = wx.Timer(self)
        self.timer2.Start(100)
        self.Bind(wx.EVT_TIMER, self.OnTimer2, self.timer2)

#定时函数

    def OnClk(self, event):
        '''定时的时间设置事件处理'''
        clktime = wx.GetNumberFromUser(message='ms为单位:',
                                       prompt='',
                                       caption="定时器的间隔时间",
                                       value=self.clktime,
                                       min=0,
                                       max=60000)
        if clktime >= 0:
            self.clktime = clktime
            if self.timer.IsRunning():
                self.timer.Start(self.clktime)

    def OnQuk(self, event):
        '''快速'''
        self.putstone(-1)

    def OnMan(self, event):
        '''手动'''
        self.timer.Stop()

    def OnAut(self, event):
        '''自动'''
        self.timer.Start(self.clktime)

    def OnTimer(self, event):

        self.putstone()

    def OnTimer2(self, event):

        self.board.Refresh(False)

#所有的创建函数

    def createMenuBar(self):

        menuMode = wx.Menu()
        mine = menuMode.AppendRadioItem(-1, "我的棋谱")
        expert = menuMode.AppendRadioItem(-1, "职业棋谱")
        dingsi = menuMode.AppendRadioItem(-1, "定式题")
        sihuo = menuMode.AppendRadioItem(-1, "死活题")

        self.Bind(wx.EVT_MENU, self.OnMine, mine)
        self.Bind(wx.EVT_MENU, self.OnExpert, expert)
        self.Bind(wx.EVT_MENU, self.OnDingsi, dingsi)
        self.Bind(wx.EVT_MENU, self.OnSihuo, sihuo)

        menuEdit = wx.Menu()
        newb = menuEdit.Append(-1, "新建")
        daka = menuEdit.Append(-1, "打开")
        dele = menuEdit.Append(-1, "删除")
        clea = menuEdit.Append(-1, "重新")
        save = menuEdit.Append(me_save, "保存")
        saveAs = menuEdit.Append(me_saveAs, "另存为")

        self.Bind(wx.EVT_MENU, self.OnNewb, newb)
        self.Bind(wx.EVT_MENU, self.OnSave, save)
        self.Bind(wx.EVT_MENU, self.OnSaveAs, saveAs)
        self.Bind(wx.EVT_MENU, self.OnDaka, daka)
        self.Bind(wx.EVT_MENU, self.OnDele, dele)
        self.Bind(wx.EVT_MENU, self.OnClea, clea)

        menuClok = wx.Menu()
        man = menuClok.Append(-1, "手动")
        aut = menuClok.Append(-1, "自动")
        quk = menuClok.Append(-1, "快速")
        clk = menuClok.Append(-1, "定时的时间")

        self.Bind(wx.EVT_MENU, self.OnQuk, quk)
        self.Bind(wx.EVT_MENU, self.OnMan, man)
        self.Bind(wx.EVT_MENU, self.OnAut, aut)
        self.Bind(wx.EVT_MENU, self.OnClk, clk)

        menuSets = wx.Menu()
        num = menuSets.AppendCheckItem(-1, "显示数字")
        num.Check(True)
        self.enableEdit = menuSets.AppendCheckItem(-1, "可写入")
        self.enableEdit.Check(True)
        resetHistory = menuSets.Append(-1, "显示历史记录")
        resetStones = menuSets.Append(-1, "显示下棋位置")

        self.Bind(wx.EVT_MENU, self.OnNum, num)
        self.Bind(wx.EVT_MENU, self.OnEnableEdit, self.enableEdit)
        self.Bind(wx.EVT_MENU, self.OnResetHistory, resetHistory)
        self.Bind(wx.EVT_MENU, self.OnResetStones, resetStones)

        menuOutIn = wx.Menu()
        imag = menuOutIn.Append(-1, "导出图片")
        outsgf = menuOutIn.Append(-1, "导出sgf文件")
        insgf = menuOutIn.Append(-1, "导入sgf文件")
        insgfs = menuOutIn.Append(-1, "导入sgf文件目录")

        self.Bind(wx.EVT_MENU, self.OnImag, imag)
        self.Bind(wx.EVT_MENU, self.OnOutsgf, outsgf)
        self.Bind(wx.EVT_MENU, self.OnInsgf, insgf)
        self.Bind(wx.EVT_MENU, self.OnInsgfs, insgfs)

        menuOthers = wx.Menu()
        tip = menuOthers.Append(-1, "提示")
        daan = menuOthers.Append(me_daan, "插入断点")

        self.Bind(wx.EVT_MENU, self.OnTip, tip)
        self.Bind(wx.EVT_MENU, self.OnPos, daan)

        menuAbout = wx.Menu()
        author = menuAbout.Append(-1, "联系作者")
        bangzhu = menuAbout.Append(-1, "在线使用帮助")

        self.Bind(wx.EVT_MENU, self.OnAuthor, author)
        self.Bind(wx.EVT_MENU, self.OnBangzhu, bangzhu)

        menuBar = wx.MenuBar()
        menuBar.Append(menuMode, "模式")
        menuBar.Append(menuEdit, "编辑")
        menuBar.Append(menuClok, "定时")
        menuBar.Append(menuSets, "设置")
        menuBar.Append(menuOutIn, "导入导出")
        menuBar.Append(menuOthers, "其他")
        menuBar.Append(menuAbout, "关于")
        self.SetMenuBar(menuBar)

    def createIcon(self):
        '''设置图标'''
        icon = wx.Icon(name='图标.jpg', type=wx.BITMAP_TYPE_JPEG)
        self.SetIcon(icon)

    def createStatusBar(self):

        self.statusBar = self.CreateStatusBar()
        self.statusBar.SetFieldsCount(4)
        self.statusBar.SetStatusWidths([-1, -1, -3, -3])
        self.statusBar.SetStatusText("编辑状态:", 0)
        self.statusBar.SetStatusText(str(self.enableEdit.IsChecked()), 1)

#所有的模式函数

    def OnMine(self, event):

        self._change_mode(mine)

    def OnExpert(self, event):

        self._change_mode(expert)

    def OnDingsi(self, event):

        self._change_mode(dingsi, False)

    def OnSihuo(self, event):

        self._change_mode(sihuo, False)

    def _change_mode(self, mode, enableClock=True):

        self.timer.Stop()
        self.mode = mode
        menuBar = self.GetMenuBar()
        menuBar.EnableTop(2, enableClock)
        self.history.Set(self.mode.titles)

#所有的编辑函数

    def OnNewb(self, event):
        '''新建操作处理'''
        self.clea()
        self.mode.id = None
        self.enableEdit.Check(True)
        self.statusBar.SetStatusText(str(self.enableEdit.IsChecked()), 1)

    def OnSave(self, event):
        '''保存事件处理'''
        self.mode.save(dataBoard.nodes)
        self.history.Set(self.mode.titles)

    def OnSaveAs(self, event):

        self.mode.id = None
        self.OnSave(event)

    def OnClea(self, event):
        '''重新事件处理'''
        self.clea()
        self.mode.open()

    def OnDaka(self, event):
        '''打开事件处理'''
        self.clea()
        self.enableEdit.Check(False)
        self.statusBar.SetStatusText(str(self.enableEdit.IsChecked()), 1)
        self.mode.open(self.selectedId)
        if hasattr(self.mode, 'pos'):
            self.putstone(self.mode.pos)
        self.SetTitle(self.mode.title)

    def OnDele(self, event):
        '''删除事件处理'''
        self.mode.delete(self.selectedId)
        self.history.Set(self.mode.titles)

#设置的函数

    def OnNum(self, event):
        '''数字显示'''
        self.board.setShowNumber(event.IsChecked())

    def OnEnableEdit(self, event):
        '''写入保护'''
        self.statusBar.SetStatusText(str(self.enableEdit.IsChecked()), 1)

    def OnResetHistory(self, event):
        '''重新显示历史记录'''
        pane = self._mgr.GetPane(self.history)
        if not pane.IsShown():
            pane.Show()
            self._mgr.Update()

    def OnResetStones(self, event):
        '''重新显示下棋位置'''
        pane = self._mgr.GetPane(self.stones)
        if not pane.IsShown():
            pane.Show()
            self._mgr.Update()

    def OnStones(self, event):

        num = self.stones.GetSelection() + 1
        if self.mode.id is None:
            self.mode.nodes = dataBoard.nodes[:num]
        else:
            self.mode.open()
        dataBoard.clear()
        self.putstone(num)

    @property
    def selectedId(self):

        num = self.history.GetSelection()
        id = self.history.GetString(num).strip('()').split(',')[0]
        return id

#导入导出的函数

    def OnImag(self, event):

        self.board.saveImage()

    def OnInsgf(self, event):
        '''导入sgf文件'''
        file_wildcard = '*.sgf'
        dlg = wx.FileDialog(self,
                            "选择sgf棋谱文件",
                            os.getcwd(),
                            wildcard=file_wildcard)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetPath()
            sgf.read(self.filename, self.mode)
            self.history.Set(self.mode.titles)
        dlg.Destroy()

    def OnInsgfs(self, event):
        '''导入sgf文件夹'''
        dlg = wx.DirDialog(self, "选择文件夹", style=wx.DD_DEFAULT_STYLE)
        if dlg.ShowModal() == wx.ID_OK:
            sgf.readdir(dlg.GetPath(), self.mode)
            self.history.Set(self.mode.titles)
        dlg.Destroy()

    def OnOutsgf(self, event):
        '''导出sgf文件'''
        sgf.write(self.mode)

#其他

    def OnTip(self, event):

        s = [node_str(*node) for node in self.mode.nodes]
        wx.MessageBox(str(s), caption="围棋记录", style=wx.OK)

    def OnPos(self, event):

        num = wx.GetNumberFromUser(message='',
                                   prompt='',
                                   caption="插入的断点",
                                   value=0,
                                   min=0,
                                   max=len(dataBoard.nodes))
        if num != -1:
            self.mode.pos = num

#关于

    def OnAuthor(self, event):

        wx.MessageBox("*****@*****.**", caption="作者邮箱", style=wx.OK)

    def OnBangzhu(self, event):

        webbrowser.open('https://sooheng.github.io')

##

    def OnLeftDown(self):

        if self.enableEdit.IsChecked(
        ) and self.board.xy and dataBoard.canPlace(*self.board.xy):
            #编辑写入
            dataBoard.place(*self.board.xy)
            self.stones.Set(dataBoard.strnodes)

            self.board.Refresh(False)
            statusText = str(self.board.xy)
            self.board.xy = None
        else:
            #只可以读取
            if self.mode in (mine, expert):
                self.putstone()
                statusText = str(dataBoard.hands)
            else:
                if self.mode.curentxy == self.board.xy:
                    if self.mode is dingsi:
                        self.putstone()
                    else:
                        self.putstone(2)
                    statusText = "正确的位置"
                else:
                    statusText = "错误的位置"
        self.statusBar.SetStatusText(statusText, 2)

    def OnClose(self, event):
        # deinitialize the frame manager
        self._mgr.UnInit()
        event.Skip()

    def clea(self):
        '''清空棋盘'''
        dataBoard.clear()
        self.board.Refresh(False)
        self.stones.Set(dataBoard.strnodes)

    def putstone(self, num=1):
        '''num 落子的数目,负数表示全部下完'''
        if num < 0:
            while self.mode.nodes:
                node = self.mode.nodes.pop(0)
                dataBoard.place(*node)
        else:
            for i in range(num):
                if self.mode.nodes:
                    node = self.mode.nodes.pop(0)
                    dataBoard.place(*node)
                else:
                    break
        self.board.Refresh(False)
        self.stones.Set(dataBoard.strnodes)

        if not self.mode.nodes:
            wx.MessageBox("已经完成", caption="UjsGo", style=wx.OK)
Beispiel #17
0
 def test_size_2_play_move(self):
     size = 2
     goboard = GoBoard(size)
     goboard.play_move(goboard.pt(1, 1), BLACK)
     count = count_colors(goboard)
     self.assertEqual(count, [size * size - 1, 1, 0, 3 * (size + 1)])
    font = pygame.font.SysFont("Crimson-Roman.ttf", 125)
    title = font.render(text, True, title_color)
    game_menu.blit(title, (150, 25))


#Global Variables
mode = 0  #The different displays
win = 0  #who won
back = 0  #which display to back button goes to
hover_pos = (-1, -1)  #For the example display
start_pvp = 0  #Did pvp start
start_pva = 0  #Did pvai start
difficulty = 0  #what difficulty ai
turn = 0  #whos turn is it
timer = 0  #delay for AI
board = GoBoard()  #The board the game is played on
win_sequence = []  #The sequence of the winning tiles
Ai = None  #The Ai object
board_history = None  #The board history object
last_black = None  #Location of the latest black tile
last_white = None  #Location of the latest white tile
is_crashed = False  #Did the program crash


def init_pvp():
    #Initiates the pvp objects and variables
    global board
    global board_history
    global start_pva
    global start_pvp
    global turn
Beispiel #19
0
    def __init__(self, go_engine, debug_mode = False):
        """
        Play Go over a GTP connection

        Parameters
        ----------
        go_engine: GoPlayer
            a program that is capable of playing go by reading GTP commands
        komi : float
            komi used for the current game
        board: GoBoard
            SIZExSIZE array representing the current board state
        """
        self.stdout = sys.stdout
        self._debug_mode = debug_mode
        sys.stdout = self
        self.go_engine = go_engine
        self.go_engine.komi = 6.5
        self.go_engine.selfatari = 1 
        self.go_engine.pattern = 1
        self.board = GoBoard(7)
        self.mm_file_name = "features_mm_training.dat"
        self.init_mm_file = False
        self.num_game = 0
        self.skip_counter = 0
        self.param_options = {
            "selfatari" :  self.go_engine.selfatari,
            "pattern" : self.go_engine.pattern
        }
        self.commands = {
            "protocol_version": self.protocol_version_cmd,
            "quit": self.quit_cmd,
            "name": self.name_cmd,
            "boardsize": self.boardsize_cmd,
            "showboard": self.showboard_cmd,
            "clear_board": self.clear_board_cmd,
            "komi": self.komi_cmd,
            "version": self.version_cmd,
            "known_command": self.known_command_cmd,
            "set_free_handicap": self.set_free_handicap,
            "genmove": self.genmove_cmd,
            "list_commands": self.list_commands_cmd,
            "play": self.play_cmd,
            "final_score": self.final_score_cmd,
            "legal_moves": self.legal_moves_cmd,
            "policy_moves": self.policy_moves_cmd,
            "random_moves": self.random_moves_cmd,
            "go_param": self.go_param_cmd,
            "gogui-analyze_commands": self.gogui_analyze_cmd,
            "num_sim": self.num_sim_cmd,
            "showoptions": self.showoptions_cmd,
            "feature_move": self.feature_move_cmd,
            "features_mm_file": self.feature_mm_cmd
        }

        # used for argument checking
        # values: (required number or arguments, error message on argnum failure)
        self.argmap = {
            "boardsize": (1, 'Usage: boardsize INT'),
            "komi": (1, 'Usage: komi FLOAT'),
            "known_command": (1, 'Usage: known_command CMD_NAME'),
            "set_free_handicap": (1, 'Usage: set_free_handicap MOVE (e.g. A4)'),
            "genmove": (1, 'Usage: genmove {w, b}'),
            "play": (2, 'Usage: play {b, w} MOVE'),
            "legal_moves": (0, 'Usage: legal_moves does not have arguments'),
            "go_param": (2,'Usage: goparam {{{0}}} {{0,1}}'.format(' '.join(list(self.param_options.keys())))),
            "num_sim":(1,'Usage: num_sim #(e.g. num_sim 100 )'),
            "showoptions":(0,'Usage: showoptions does not have arguments'),
            "feature_move":(1,'Usage: feature_move move')
        }
def p_verse_p():
    """
    Game logic for the pvp mode, also the logic for the buttons
    and board for displaying.
    """
    global back
    global board
    global hover_pos
    global last_black
    global last_white
    global mode
    global start_pvp
    global win

    if start_pvp == 0:
        init_pvp()
    start_pvp = 1
    pygame.display.set_caption('Versus a Friend.')
    draw_board()
    pygame.display.update()
    clock.tick(60)  # Frames per second.
    for event in pygame.event.get(
    ):  # Creates a list of events that the user does with cursor.
        coord = pygame.mouse.get_pos()  # Grabs the position of the mouse.

        if event.type == pygame.QUIT:
            crashed = True
            pygame.quit()
            quit()

        #on mouse releae
        if event.type == pygame.MOUSEBUTTONUP:
            if undo_button.hover(coord):
                if win == 0:
                    undo()
                    draw_board()
            elif play_help_button.hover(coord):
                back = 2
                mode = 1
            elif back_button.hover(coord):
                kill_pvp()
                mode = 0
            elif reset_button.hover(coord):
                reset_pvp()
            click_x = coord[0]
            click_y = coord[1]

            #If mouse is close to grid find a position snapped to the grid
            if 45 < coord[0] < 493 and 45 < coord[1] < 493 and win == 0:
                if 30 > click_x:
                    click_x = 30
                click_x = click_x + 15
                click_x = click_x - (click_x % 30)

                if 30 > click_y:
                    click_y = 30
                click_y = click_y + 15
                click_y = click_y - (click_y % 30)

                #play

                #change it to the index
                click_x = (click_x - 60) // 30
                click_y = (click_y - 60) // 30
            else:
                click_x = -1
                click_y = -1

            if click_x != -1 and click_y != -1:
                if board == None:
                    board = GoBoard()
                if board.set_token(click_x, click_y, turn + 1, get_colour(),
                                   board_history):
                    if turn == 0:
                        last_black = board.tokens_placed[
                            len(board.tokens_placed) - 1]
                    else:
                        last_white = board.tokens_placed[
                            len(board.tokens_placed) - 1]
                    check_win()
                    change_turn()
                    draw_board()
                    rand_int = random.randint(0, 2)
                    pygame.mixer.music.load('sounds/place_' + str(rand_int) +
                                            '.mp3')
                    pygame.mixer.music.set_volume(1.0)
                    pygame.mixer.music.play(0)
                else:
                    pygame.mixer.music.load('sounds/invalid.mp3')
                    pygame.mixer.music.set_volume(0.2)
                    pygame.mixer.music.play(0)

        #on mouse movement
        if event.type == pygame.MOUSEMOTION:
            if back_button.hover(coord):
                back_button.color = button_select_color
                play_help_button.color = button_color
                undo_button.color = button_color
                reset_button.color = button_color
            elif undo_button.hover(coord):
                undo_button.color = button_select_color
                back_button.color = button_color
                play_help_button.color = button_color
                reset_button.color = button_color
            elif play_help_button.hover(coord):
                play_help_button.color = button_select_color
                back_button.color = button_color
                undo_button.color = button_color
                reset_button.color = button_color
            elif reset_button.hover(coord):
                reset_button.color = button_select_color
                back_button.color = button_color
                play_help_button.color = button_color
                undo_button.color = button_color
            else:
                back_button.color = button_color
                play_help_button.color = button_color
                undo_button.color = button_color
                reset_button.color = button_color

            #if mouse near grid find a position snapped to the grid
            #This is saved for draw_board
            if 45 < coord[0] < 493 and 45 < coord[1] < 493 and win == 0:
                hov_x = coord[0]
                hov_y = coord[1]

                if 30 > hov_x:
                    hov_x = 30
                hov_x = hov_x + 15
                hov_x = hov_x - (hov_x % 30)

                if 30 > hov_y:
                    hov_y = 30
                hov_y = hov_y + 15
                hov_y = hov_y - (hov_y % 30)

                hover_pos = (hov_x - 13, hov_y - 13)
            else:
                hover_pos = (-1, -1)
class GtpConnection():
    def __init__(self, go_engine, debug_mode=False):
        """
        object that plays Go using GTP

        Parameters
        ----------
        go_engine: GoPlayer
            a program that is capable of playing go by reading GTP commands
        debug_mode: prints debug messages
        """
        self.stdout = sys.stdout
        sys.stdout = self
        self._debug_mode = debug_mode
        self.go_engine = go_engine
        self.komi = 0
        self.board = GoBoard(7)
        self.commands = {
            "protocol_version": self.protocol_version_cmd,
            "quit": self.quit_cmd,
            "name": self.name_cmd,
            "boardsize": self.boardsize_cmd,
            "showboard": self.showboard_cmd,
            "clear_board": self.clear_board_cmd,
            "komi": self.komi_cmd,
            "version": self.version_cmd,
            "known_command": self.known_command_cmd,
            "set_free_handicap": self.set_free_handicap,
            "genmove": self.genmove_cmd,
            "list_commands": self.list_commands_cmd,
            "play": self.play_cmd,
            "final_score": self.final_score_cmd,
            "legal_moves": self.legal_moves_cmd,
            ###
            "timelimit": self.timelimit_cmd,
            "solve": self.solve_cmd,
        }

        # used for argument checking
        # values: (required number or arguments, error message on argnum failure)
        self.argmap = {
            "boardsize": (1, 'Usage: boardsize INT'),
            "komi": (1, 'Usage: komi FLOAT'),
            "known_command": (1, 'Usage: known_command CMD_NAME'),
            "set_free_handicap":
            (1, 'Usage: set_free_handicap MOVE (e.g. A4)'),
            "genmove": (1, 'Usage: genmove {w, b}'),
            "play": (2, 'Usage: play {b, w} MOVE'),
            "legal_moves": (1, 'Usage: legal_moves {w, b}'),
            "timelimit": (1, 'Usage: timelimit seconds')
        }

    def __del__(self):
        sys.stdout = self.stdout

    def write(self, data):
        self.stdout.write(data)

    def flush(self):
        self.stdout.flush()

    def start_connection(self):
        """
        start a GTP connection. This function is what continuously monitors
        the user's input of commands.
        """
        self.debug_msg("Start up successful...\n\n")
        line = sys.stdin.readline()
        while line:
            self.get_cmd(line)
            line = sys.stdin.readline()

    def get_cmd(self, command):
        """
        parse the command and execute it

        Arguments
        ---------
        command : str
            the raw command to parse/execute
        """
        if len(command.strip(' \r\t')) == 0:
            return
        if command[0] == '#':
            return
        # Strip leading numbers from regression tests
        if command[0].isdigit():
            command = re.sub("^\d+", "", command).lstrip()

        elements = command.split()
        if not elements:
            return
        command_name = elements[0]
        args = elements[1:]

        if command_name == "play" and self.argmap[command_name][0] != len(
                args):
            self.respond('illegal move: {} wrong number of arguments'.format(
                args[0]))
            return

        if self.arg_error(command_name, len(args)):
            return
        if command_name in self.commands:
            try:
                self.commands[command_name](args)
            except Exception as e:
                self.debug_msg("Error executing command {}\n".format(str(e)))
                self.debug_msg("Stack Trace:\n{}\n".format(
                    traceback.format_exc()))
                raise e
        else:
            self.debug_msg("Unknown command: {}\n".format(command_name))
            self.error('Unknown command')
            sys.stdout.flush()

    def arg_error(self, cmd, argnum):
        """
        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
        """
        if cmd in self.argmap and self.argmap[cmd][0] > argnum:
            self.error(self.argmap[cmd][1])
            return True
        return False

    def debug_msg(self, msg=''):
        """ Write a msg to the debug stream """
        if self._debug_mode:
            sys.stderr.write(msg)
            sys.stderr.flush()

    def error(self, error_msg=''):
        """ Send error msg to stdout and through the GTP connection. """
        sys.stdout.write('? {}\n\n'.format(error_msg))
        sys.stdout.flush()

    def respond(self, response=''):
        """ Send msg to stdout """
        sys.stdout.write('= {}\n\n'.format(response))
        sys.stdout.flush()

    def reset(self, size):
        """
        Resets the state of the GTP to a starting board

        Arguments
        ---------
        size : int
            the boardsize to reinitialize the state to
        """
        self.board.reset(size)

    def protocol_version_cmd(self, args):
        """ Return the GTP protocol version being used (always 2) """
        self.respond('2')

    def quit_cmd(self, args):
        """ Quit game and exit the GTP interface """
        self.respond()
        exit()

    def name_cmd(self, args):
        """ Return the name of the player """
        self.respond(self.go_engine.name)

    def version_cmd(self, args):
        """ Return the version of the player """
        self.respond(self.go_engine.version)

    def clear_board_cmd(self, args):
        """ clear the board """
        self.reset(self.board.size)
        self.respond()

    def boardsize_cmd(self, args):
        """
        Reset the game and initialize with a new boardsize

        Arguments
        ---------
        args[0] : int
            size of reinitialized board
        """
        self.reset(int(args[0]))
        self.respond()

    def showboard_cmd(self, args):
        self.respond('\n' + str(self.board.get_twoD_board()))

    def komi_cmd(self, args):
        """
        Set the komi for the game

        Arguments
        ---------
        args[0] : float
            komi value
        """
        self.komi = float(args[0])
        self.respond()

    def known_command_cmd(self, args):
        """
        Check if a command is known to the GTP interface

        Arguments
        ---------
        args[0] : str
            the command name to check for
        """
        if args[0] in self.commands:
            self.respond("true")
        else:
            self.respond("false")

    def list_commands_cmd(self, args):
        """ list all supported GTP commands """
        self.respond(' '.join(list(self.commands.keys())))

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

    def legal_moves_cmd(self, args):
        """
        list legal moves for 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'}
        """
        try:
            board_color = args[0].lower()
            color = GoBoardUtil.color_to_int(board_color)
            moves = GoBoardUtil.generate_legal_moves(self.board, color)
            self.respond(moves)
        except Exception as e:
            self.respond('Error: {}'.format(str(e)))

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

    def final_score_cmd(self, args):
        self.respond(self.board.final_score(self.komi))

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

    def timelimit_cmd(self, args):
        self.board.timelimit = int(args[0])
        self.respond()

    def solve_cmd(self, args):
        self.board.hit = 0
        score = self.board.call_search()
        # print('hit=', self.board.hit)
        if score == 0:
            # Timeout
            self.respond('unknown')
        elif score == 1:
            # The player can win
            _, move = self.board.tree_cache[self.board]
            self.respond('{} {}'.format(
                GoBoardUtil.int_to_color(self.board.to_play), move))
        else:
            # The opponent can win
            self.respond(
                GoBoardUtil.int_to_color(
                    GoBoardUtil.opponent(self.board.to_play)))
        sys.stderr.write('{} sec\n'.format(self.board.duration))
        sys.stderr.flush()
Beispiel #22
0
def run():
    """
    start the gtp connection and wait for commands.
    """
    board = GoBoard(7)
Beispiel #23
0
class GtpConnection():

    def __init__(self, go_engine, debug_mode = False):
        """
        Play Go over a GTP connection

        Parameters
        ----------
        go_engine: GoPlayer
            a program that is capable of playing go by reading GTP commands
        komi : float
            komi used for the current game
        board: GoBoard
            SIZExSIZE array representing the current board state
        """
        self.stdout = sys.stdout
        self._debug_mode = debug_mode
        sys.stdout = self
        self.go_engine = go_engine
        self.go_engine.komi = 6.5
        self.go_engine.selfatari = 1 
        self.go_engine.pattern = 1
        self.board = GoBoard(7)
        self.mm_file_name = "features_mm_training.dat"
        self.init_mm_file = False
        self.num_game = 0
        self.skip_counter = 0
        self.param_options = {
            "selfatari" :  self.go_engine.selfatari,
            "pattern" : self.go_engine.pattern
        }
        self.commands = {
            "protocol_version": self.protocol_version_cmd,
            "quit": self.quit_cmd,
            "name": self.name_cmd,
            "boardsize": self.boardsize_cmd,
            "showboard": self.showboard_cmd,
            "clear_board": self.clear_board_cmd,
            "komi": self.komi_cmd,
            "version": self.version_cmd,
            "known_command": self.known_command_cmd,
            "set_free_handicap": self.set_free_handicap,
            "genmove": self.genmove_cmd,
            "list_commands": self.list_commands_cmd,
            "play": self.play_cmd,
            "final_score": self.final_score_cmd,
            "legal_moves": self.legal_moves_cmd,
            "policy_moves": self.policy_moves_cmd,
            "random_moves": self.random_moves_cmd,
            "go_param": self.go_param_cmd,
            "gogui-analyze_commands": self.gogui_analyze_cmd,
            "num_sim": self.num_sim_cmd,
            "showoptions": self.showoptions_cmd,
            "feature_move": self.feature_move_cmd,
            "features_mm_file": self.feature_mm_cmd
        }

        # used for argument checking
        # values: (required number or arguments, error message on argnum failure)
        self.argmap = {
            "boardsize": (1, 'Usage: boardsize INT'),
            "komi": (1, 'Usage: komi FLOAT'),
            "known_command": (1, 'Usage: known_command CMD_NAME'),
            "set_free_handicap": (1, 'Usage: set_free_handicap MOVE (e.g. A4)'),
            "genmove": (1, 'Usage: genmove {w, b}'),
            "play": (2, 'Usage: play {b, w} MOVE'),
            "legal_moves": (0, 'Usage: legal_moves does not have arguments'),
            "go_param": (2,'Usage: goparam {{{0}}} {{0,1}}'.format(' '.join(list(self.param_options.keys())))),
            "num_sim":(1,'Usage: num_sim #(e.g. num_sim 100 )'),
            "showoptions":(0,'Usage: showoptions does not have arguments'),
            "feature_move":(1,'Usage: feature_move move')
        }
    def __del__(self):
        sys.stdout = self.stdout

    def write(self, data):
        self.stdout.write(data)

    def flush(self):
        self.stdout.flush()

    def start_connection(self):
        """
        start a GTP connection. This function is what continuously monitors
        the user's input of commands.
        """
        self.debug_msg("Start up successful...\n\n")
        line = sys.stdin.readline()
        while line:
            self.get_cmd(line)
            line = sys.stdin.readline()

    def get_cmd(self, command):
        """
        parse the command and execute it

        Arguments
        ---------
        command : str
            the raw command to parse/execute
        """
        if len(command.strip(' \r\t')) == 0:
            return
        if command[0] == '#':
            return
        # Strip leading numbers from regression tests
        if command[0].isdigit():
            command = re.sub("^\d+", "", command).lstrip()

        elements = command.split()
        if not elements:
            return
        command_name = elements[0]; args = elements[1:]
        if self.arg_error(command_name, len(args)):
            return
        if command_name in self.commands:
            try:
                self.commands[command_name](args)
            except Exception as e:
                self.debug_msg("Error executing command {}\n".format(str(e)))
                self.debug_msg("Stack Trace:\n{}\n".format(traceback.format_exc()))
                traceback.print_exc(file=sys.stdout)
                raise e
        else:
            self.debug_msg("Unknown command: {}\n".format(command_name))
            self.error('Unknown command')
            sys.stdout.flush()

    def arg_error(self, cmd, argnum):
        """
        checker function 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
        """
        if cmd in self.argmap and self.argmap[cmd][0] != argnum:
            self.error(self.argmap[cmd][1])
            return True
        return False

    def debug_msg(self, msg = ''):
        """ Write a msg to the debug stream """
        if self._debug_mode:
            sys.stderr.write(msg); sys.stderr.flush()

    def error(self, error_msg = ''):
        """ Send error msg to stdout and through the GTP connection. """
        sys.stdout.write('? {}\n\n'.format(error_msg)); sys.stdout.flush()

    def respond(self, response = ''):
        """ Send msg to stdout """
        sys.stdout.write('= {}\n\n'.format(response)); sys.stdout.flush()

    def reset(self, size):
        """
        Resets the state of the GTP to a starting board

        Arguments
        ---------
        size : int
            the boardsize to reinitialize the state to
        """
        self.board.reset(size)
        self.go_engine.reset()

    def protocol_version_cmd(self, args):

        """ Return the GTP protocol version being used (always 2) """
        self.respond('2')

    def quit_cmd(self, args):
        """ Quit game and exit the GTP interface """
        self.respond()
        exit()

    def name_cmd(self, args):
        """ Return the name of the player """
        self.respond(self.go_engine.name)

    def version_cmd(self, args):
        """ Return the version of the player """
        self.respond(self.go_engine.version)

    def clear_board_cmd(self, args):
        """ clear the board """
        self.reset(self.board.size)
        self.respond()

    def boardsize_cmd(self, args):
        """
        Reset the game and initialize with a new boardsize

        Arguments
        ---------
        args[0] : int
            size of reinitialized board
        """
        self.reset(int(args[0]))
        self.respond()

    def showboard_cmd(self, args):
        self.respond('\n' + str(self.board.get_twoD_board()))
    
    def showoptions_cmd(self,args):
        options = dict()
        options['komi'] = self.go_engine.komi
        options['pattern'] = self.go_engine.pattern
        options['selfatari'] = self.go_engine.selfatari
        options['num_sim'] = self.go_engine.num_simulation
        self.respond(options)
        
    def komi_cmd(self, args):
        """
        Set the komi for the game

        Arguments
        ---------
        args[0] : float
            komi value
        """
        self.go_engine.komi = float(args[0])
        self.respond()

    def known_command_cmd(self, args):
        """
        Check if a command is known to the GTP interface

        Arguments
        ---------
        args[0] : str
            the command name to check for
        """
        if args[0] in self.commands:
            self.respond("true")
        else:
            self.respond("false")

    def list_commands_cmd(self, args):
        """ list all supported GTP commands """
        self.respond(' '.join(list(self.commands.keys())))

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

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

    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
        """
        # Assignment4 - policy moves
        # =========================================
        move_prob_tuples = self.get_move_prob()
        response = ' '.join([' '.join([t[0], '{:.5f}'.format(t[1])]) for t in move_prob_tuples])
        self.respond(response)
        # =========================================

    def random_moves_cmd(self, args):
        """
            Return list of random moves (legal, but not eye-filling)
        """
        moves = GoBoardUtil.generate_random_moves(self.board)
        if len(moves) == 0:
            self.respond("Pass")
        else:
            self.respond(GoBoardUtil.sorted_point_string(moves, self.board.NS))

    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 init_mm_file_header(self):
        with open(self.mm_file_name ,'w') as header_writer:
            header_writer.write('! 1080\n')
            header_writer.write('8\n')
            header_writer.write('2 Feature_Pass\n')
            header_writer.write('1 Feature_Capture\n')
            header_writer.write('2 Feature_Atari\n')
            header_writer.write('1 Feature_SelfAtari\n')
            header_writer.write('3 Feature_DistanceLine\n')
            header_writer.write('8 Feature_DistancePrev\n')
            header_writer.write('9 Feature_DistancePrevOwn\n')
            header_writer.write('1054 Feature_Pattern\n')
            header_writer.write('!\n')
        header_writer.close()
        self.init_mm_file = True

    def feature_mm_cmd(self, args):
        if self.init_mm_file == False:
            self.init_mm_file_header()
        assert self.init_mm_file == True
        if len(self.board.moves) == 0:
            with open('game_num.txt', 'a') as file:
                self.num_game = self.num_game + 1
                file.write('{}\n'.format(self.num_game))
            file.close()
            self.respond()
            self.skip_counter = 0
            return
        # skip the first five moves in the game records, since they are randomly selected
        if self.skip_counter <= 5:
            self.skip_counter += 1
            self.respond()
            return
        chosenMove = self.board.last_move
        bd = self.board.copy()
        if chosenMove != -1:
            if chosenMove == None:
                chosenMove = 'PASS'
            bd.partial_undo_move()
            Feature.write_mm_file(bd, chosenMove, self.mm_file_name)
            if chosenMove == 'PASS':
                bd.move(None, bd.current_player)
            else:
                bd.move(chosenMove, bd.current_player)
        self.respond()

    def gogui_analyze_cmd(self, args):
        try:
            self.respond("pstring/Legal Moves/legal_moves\n"
                         "pstring/Policy Moves/policy_moves\n"
                         "pstring/Random Moves/random_moves\n"
                         "none/Feature Move/feature_move %p\n"
                         "none/Features MM File/features_mm_file\n"
                        )
        except Exception as e:
            self.respond('Error: {}'.format(str(e)))

    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.go_engine.update('pass')
                #self.board.current_player = GoBoardUtil.opponent(color)
                self.board.move(None, color)
                self.respond()
                return
            move = GoBoardUtil.move_to_coord(args[1], 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
            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.go_engine.update(move)
            self.respond()
        except Exception as e:
            self.respond("illegal move: {} {} {}".format(board_color, board_move, str(e)))

    def final_score_cmd(self, args):
        self.respond(self.board.final_score(self.go_engine.komi))

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


    # Assignment4
    # =========================================
    def get_move_prob(self):
        moves = GoBoardUtil.generate_random_moves(self.board) # legal and not eye-filling
        features = Feature.find_all_features(self.board)
        gammas_sum = 0
        move_gammas = dict()
        if len(Features_weight) != 0:
            for move in moves:
                move_gammas[move] = Feature.compute_move_gamma(Features_weight, features[move])
                gammas_sum += move_gammas[move]

            # normalize to get probability
            if gammas_sum:
                for move in move_gammas.keys():
                    move_gammas[move] /= gammas_sum

        if move_gammas and gammas_sum:
            move_prob_tuples = [(self.board.point_to_string(k), v) for (k, v) in move_gammas.items()]

            # sort list by probability and alphabetic order
            # based on
            # http://stackoverflow.com/questions/5212870/sorting-a-python-list-by-two-criteria
            # answered by jaap on Stack Overflow http://stackoverflow.com/users/1186954/jaap
            move_prob_tuples = sorted(move_prob_tuples, key=lambda k:(-k[1], k[0][0], k[0][1]))
        else:
            move_prob_tuples = list()
            move_prob_tuples.append(('pass', 1))

        return move_prob_tuples
 def __init__(self):
     empty_board = GoBoard()
     self.boards = [empty_board]
Beispiel #25
0
class GtpConnection():
    def __init__(self, go_engine, debug_mode=False):
        """
        object that plays Go using GTP

        Parameters
        ----------
        go_engine: GoPlayer
            a program that is capable of playing go by reading GTP commands
        debug_mode: prints debug messages
        """
        self.stdout = sys.stdout
        sys.stdout = self
        self._debug_mode = debug_mode
        self.go_engine = go_engine
        self.komi = 0
        self.board = GoBoard(7)
        self.notdone = False
        self.timelimit = 1
        self.starttime = 0
        self.winMoves = []
        self.genCall = False
        self.commands = {
            "protocol_version": self.protocol_version_cmd,
            "quit": self.quit_cmd,
            "name": self.name_cmd,
            "boardsize": self.boardsize_cmd,
            "showboard": self.showboard_cmd,
            "clear_board": self.clear_board_cmd,
            "komi": self.komi_cmd,
            "version": self.version_cmd,
            "known_command": self.known_command_cmd,
            "set_free_handicap": self.set_free_handicap,
            "genmove": self.genmove_cmd,
            "list_commands": self.list_commands_cmd,
            "play": self.play_cmd,
            "final_score": self.final_score_cmd,
            "legal_moves": self.legal_moves_cmd,
            "timelimit": self.timelimit_cmd,
            "solve": self.solve_cmd
        }

        # used for argument checking
        # values: (required number or arguments, error message on argnum failure)
        self.argmap = {
            "boardsize": (1, 'Usage: boardsize INT'),
            "komi": (1, 'Usage: komi FLOAT'),
            "known_command": (1, 'Usage: known_command CMD_NAME'),
            "set_free_handicap":
            (1, 'Usage: set_free_handicap MOVE (e.g. A4)'),
            "genmove": (1, 'Usage: genmove {w, b}'),
            "play": (2, 'Usage: play {b, w} MOVE'),
            "legal_moves": (1, 'Usage: legal_moves {w, b}'),
            "timelimit": (1, 'Usage: timelimit seconds (1 <= seconds <= 100)')
        }

    def __del__(self):
        sys.stdout = self.stdout

    def write(self, data):
        self.stdout.write(data)

    def flush(self):
        self.stdout.flush()

    def start_connection(self):
        """
        start a GTP connection. This function is what continuously monitors
        the user's input of commands.
        """
        self.debug_msg("Start up successful...\n\n")
        line = sys.stdin.readline()
        while line:
            self.get_cmd(line)
            line = sys.stdin.readline()

    def get_cmd(self, command):
        """
        parse the command and execute it

        Arguments
        ---------
        command : str
            the raw command to parse/execute
        """
        if len(command.strip(' \r\t')) == 0:
            return
        if command[0] == '#':
            return
        # Strip leading numbers from regression tests
        if command[0].isdigit():
            command = re.sub("^\d+", "", command).lstrip()

        elements = command.split()
        if not elements:
            return
        command_name = elements[0]
        args = elements[1:]

        if command_name == "play" and self.argmap[command_name][0] != len(
                args):
            self.respond('illegal move: {} wrong number of arguments'.format(
                args[0]))
            return

        if self.arg_error(command_name, len(args)):
            return
        if command_name in self.commands:
            try:
                self.commands[command_name](args)
            except Exception as e:
                self.debug_msg("Error executing command {}\n".format(str(e)))
                self.debug_msg("Stack Trace:\n{}\n".format(
                    traceback.format_exc()))
                raise e
        else:
            self.debug_msg("Unknown command: {}\n".format(command_name))
            self.error('Unknown command')
            sys.stdout.flush()

    def arg_error(self, cmd, argnum):
        """
        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
        """
        if cmd in self.argmap and self.argmap[cmd][0] > argnum:
            self.error(self.argmap[cmd][1])
            return True
        return False

    def debug_msg(self, msg=''):
        """ Write a msg to the debug stream """
        if self._debug_mode:
            sys.stderr.write(msg)
            sys.stderr.flush()

    def error(self, error_msg=''):
        """ Send error msg to stdout and through the GTP connection. """
        sys.stdout.write('? {}\n\n'.format(error_msg))
        sys.stdout.flush()

    def respond(self, response=''):
        """ Send msg to stdout """
        sys.stdout.write('= {}\n\n'.format(response))
        sys.stdout.flush()

    def reset(self, size):
        """
        Resets the state of the GTP to a starting board

        Arguments
        ---------
        size : int
            the boardsize to reinitialize the state to
        """
        self.board.reset(size)

    def protocol_version_cmd(self, args):
        """ Return the GTP protocol version being used (always 2) """
        self.respond('2')

    def quit_cmd(self, args):
        """ Quit game and exit the GTP interface """
        self.respond()
        exit()

    def name_cmd(self, args):
        """ Return the name of the player """
        self.respond(self.go_engine.name)

    def version_cmd(self, args):
        """ Return the version of the player """
        self.respond(self.go_engine.version)

    def clear_board_cmd(self, args):
        """ clear the board """
        self.reset(self.board.size)
        self.respond()

    def boardsize_cmd(self, args):
        """
        Reset the game and initialize with a new boardsize

        Arguments
        ---------
        args[0] : int
            size of reinitialized board
        """
        self.reset(int(args[0]))
        self.respond()

    def showboard_cmd(self, args):
        self.respond('\n' + str(self.board.get_twoD_board()))

    def komi_cmd(self, args):
        """
        Set the komi for the game

        Arguments
        ---------
        args[0] : float
            komi value
        """
        self.komi = float(args[0])
        self.respond()

    def known_command_cmd(self, args):
        """
        Check if a command is known to the GTP interface

        Arguments
        ---------
        args[0] : str
            the command name to check for
        """
        if args[0] in self.commands:
            self.respond("true")
        else:
            self.respond("false")

    def list_commands_cmd(self, args):
        """ list all supported GTP commands """
        self.respond(' '.join(list(self.commands.keys())))

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

    def legal_moves_cmd(self, args):
        """
        list legal moves for 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'}
        """
        try:
            board_color = args[0].lower()
            color = GoBoardUtil.color_to_int(board_color)
            moves = GoBoardUtil.generate_legal_moves(self.board, color)
            self.respond(moves)
        except Exception as e:
            self.respond('Error: {}'.format(str(e)))

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

    def final_score_cmd(self, args):
        self.respond(self.board.final_score(self.komi))

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

    def timelimit_cmd(self, args):
        #TODO
        self.timelimit = int(args[0])
        self.respond()

    def solve_cmd(self, args):
        #TODO
        self.winMoves = []
        self.notdone = False
        state = self.board
        self.starttime = time.process_time()
        #win = self.negamaxBoolean(state,0)
        win = self.alphabeta(state, -100000, 100000, 0)
        stone = ['', 'b', 'w']

        i = 1
        if not self.genCall:

            if len(self.winMoves) != 0:
                s = stone[state.to_play]
                self.respond("{} {}".format(s, self.winMoves[0]))
            else:
                if self.notdone:
                    self.respond("unknown")
                else:
                    s = stone[GoBoardUtil.opponent(state.to_play)]
                    self.respond(s)

    # helper function for solve
    # Success means: either a win, or toPlay is the DRAW_WINNER when its a draw

    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

    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
Beispiel #26
0
class GtpConnection():
    def __init__(self, go_engine, debug_mode=False):
        """
        object that plays Go using GTP

        Parameters
        ----------
        go_engine: GoPlayer
            a program that is capable of playing go by reading GTP commands
        debug_mode: prints debug messages
        """
        self.stdout = sys.stdout
        sys.stdout = self
        self._debug_mode = debug_mode
        self.go_engine = go_engine
        self.komi = 0
        self.board = GoBoard(7)
        #added timelimit default here
        self.timelimit = 1

        self.commands = {
            "protocol_version": self.protocol_version_cmd,
            "quit": self.quit_cmd,
            "name": self.name_cmd,
            "boardsize": self.boardsize_cmd,
            "showboard": self.showboard_cmd,
            "clear_board": self.clear_board_cmd,
            "komi": self.komi_cmd,
            "version": self.version_cmd,
            "known_command": self.known_command_cmd,
            "set_free_handicap": self.set_free_handicap,
            "genmove": self.genmove_cmd,
            "list_commands": self.list_commands_cmd,
            "play": self.play_cmd,
            "final_score": self.final_score_cmd,
            "timelimit": self.time_limit_cmd,
            "solve": self.solve_cmd,
            "legal_moves": self.legal_moves_cmd
        }

        # used for argument checking
        # values: (required number or arguments, error message on argnum failure)
        self.argmap = {
            "boardsize": (1, 'Usage: boardsize INT'),
            "komi": (1, 'Usage: komi FLOAT'),
            "known_command": (1, 'Usage: known_command CMD_NAME'),
            "set_free_handicap":
            (1, 'Usage: set_free_handicap MOVE (e.g. A4)'),
            "genmove": (1, 'Usage: genmove {w, b}'),
            "play": (2, 'Usage: play {b, w} MOVE'),
            "legal_moves": (1, 'Usage: legal_moves {w, b}')
        }

    def __del__(self):
        sys.stdout = self.stdout

    def write(self, data):
        self.stdout.write(data)

    def flush(self):
        self.stdout.flush()

    def start_connection(self):
        """
        start a GTP connection. This function is what continuously monitors
        the user's input of commands.
        """
        self.debug_msg("Start up successful...\n\n")
        line = sys.stdin.readline()
        while line:
            self.get_cmd(line)
            line = sys.stdin.readline()

    def get_cmd(self, command):
        """
        parse the command and execute it

        Arguments
        ---------
        command : str
            the raw command to parse/execute
        """
        if len(command.strip(' \r\t')) == 0:
            return
        if command[0] == '#':
            return
        # Strip leading numbers from regression tests
        if command[0].isdigit():
            command = re.sub("^\d+", "", command).lstrip()

        elements = command.split()
        if not elements:
            return
        command_name = elements[0]
        args = elements[1:]

        if command_name == "play" and self.argmap[command_name][0] != len(
                args):
            self.respond('illegal move: {} wrong number of arguments'.format(
                args[0]))
            return

        if self.arg_error(command_name, len(args)):
            return
        if command_name in self.commands:
            try:
                self.commands[command_name](args)
            except Exception as e:
                self.debug_msg("Error executing command {}\n".format(str(e)))
                self.debug_msg("Stack Trace:\n{}\n".format(
                    traceback.format_exc()))
                raise e
        else:
            self.debug_msg("Unknown command: {}\n".format(command_name))
            self.error('Unknown command')
            sys.stdout.flush()

    def arg_error(self, cmd, argnum):
        """
        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
        """
        if cmd in self.argmap and self.argmap[cmd][0] > argnum:
            self.error(self.argmap[cmd][1])
            return True
        return False

    def debug_msg(self, msg=''):
        """ Write a msg to the debug stream """
        if self._debug_mode:
            sys.stderr.write(msg)
            sys.stderr.flush()

    def error(self, error_msg=''):
        """ Send error msg to stdout and through the GTP connection. """
        sys.stdout.write('? {}\n\n'.format(error_msg))
        sys.stdout.flush()

    def respond(self, response=''):
        """ Send msg to stdout """
        sys.stdout.write('= {}\n\n'.format(response))
        sys.stdout.flush()

    def reset(self, size):
        """
        Resets the state of the GTP to a starting board

        Arguments
        ---------
        size : int
            the boardsize to reinitialize the state to
        """
        self.board.reset(size)

    def protocol_version_cmd(self, args):
        """ Return the GTP protocol version being used (always 2) """
        self.respond('2')

    def quit_cmd(self, args):
        """ Quit game and exit the GTP interface """
        self.respond()
        exit()

    def name_cmd(self, args):
        """ Return the name of the player """
        self.respond(self.go_engine.name)

    def version_cmd(self, args):
        """ Return the version of the player """
        self.respond(self.go_engine.version)

    def clear_board_cmd(self, args):
        """ clear the board """
        self.reset(self.board.size)
        self.respond()

    def boardsize_cmd(self, args):
        """
        Reset the game and initialize with a new boardsize

        Arguments
        ---------
        args[0] : int
            size of reinitialized board
        """
        self.reset(int(args[0]))
        self.respond()

    def showboard_cmd(self, args):
        self.respond('\n' + str(self.board.get_twoD_board()))

    def komi_cmd(self, args):
        """
        Set the komi for the game

        Arguments
        ---------
        args[0] : float
            komi value
        """
        self.komi = float(args[0])
        self.respond()

    def handler(signum, frame):
        print("Alarm went off, too slow")

    #JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJASON & DAVID NEW CODE STARTS HEREEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
    #adding solve command, going to be using the signals
    def solve_cmd(self, args):
        try:
            signal.signal(signal.SIGALRM, self.handler)
            signal.alarm(self.timelimit)
            #get playmove colour somehow, pass it into solution function
            state, moves = self.board.negamaxBoolean()
            signal.alarm(0)
            if state == True:
                if self.board.to_play == 1:
                    winner = "w"
                else:
                    winner = "b"
            else:
                if self.board.to_play == 1:
                    winner = "w"
                else:
                    winner = "b"

            if moves != -1:
                moves = self.board._point_to_coord(moves)
                boob = self.format_point(moves)
                self.respond(winner + " " + boob)
            else:
                self.respond(winner)

        except (RuntimeError, TypeError, ValueError):
            self.respond("unknown")

    #adding timelimit set command, pretty self explanitory(done)
    def time_limit_cmd(self, args):
        self.timelimit = int(args[0])
        #print("time set",args[0])
        self.respond()

    def format_point(self, move):
        """
        Return coordinates as a string like 'a1', or 'pass'.

        Arguments
        ---------
        move : (row, col), or None for pass

        Returns
        -------
        The move converted from a tuple to a Go position (e.g. d4)
        """
        column_letters = "abcdefghjklmnopqrstuvwxyz"
        if move is None:
            return "pass"
        row, col = move
        if not 0 <= row < 25 or not 0 <= col < 25:
            raise ValueError
        return column_letters[col - 1] + str(row)

    def known_command_cmd(self, args):
        """
        Check if a command is known to the GTP interface

        Arguments
        ---------
        args[0] : str
            the command name to check for
        """
        if args[0] in self.commands:
            self.respond("true")
        else:
            self.respond("false")

    def list_commands_cmd(self, args):
        """ list all supported GTP commands """
        self.respond(' '.join(list(self.commands.keys())))

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

    def legal_moves_cmd(self, args):
        """
        list legal moves for 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'}
        """
        try:
            board_color = args[0].lower()
            color = GoBoardUtil.color_to_int(board_color)
            moves = GoBoardUtil.generate_legal_moves(self.board, color)
            self.respond(moves)
        except Exception as e:
            self.respond('Error: {}'.format(str(e)))

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

    def final_score_cmd(self, args):
        self.respond(self.board.final_score(self.komi))

    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)
            move = self.go_engine.get_move(self.board, color)
            if move is None:
                #resign here
                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)))
Beispiel #27
0
#!/usr/bin/python3
from board import GoBoard
from board_util import GoBoardUtil, BLACK, WHITE, EMPTY, BORDER, FLOODFILL
import numpy as np
from Go5 import Go5Player
import time
board = GoBoard(4)
player = Go5Player(num_simulation=200, limit=100, exploration=np.sqrt(2))
player.MCTS.komi = 6.5
player.num_nodes = 5

cboard = board.copy()
print("\nrunning playout 200 times\n")
player.run(cboard, BLACK, print_info=True)

#time.sleep(30) # sleeping
player.num_simulation = 300
print("\nrunning it 300 more times\n")
cboard = board.copy()
player.run(cboard, BLACK, print_info=True)

#time.sleep(30)
print("\nrunning it 300 more times\n")
cboard = board.copy()
player.run(cboard, BLACK, print_info=True)

#time.sleep(30)
print("\nrunning it 300 more times\n")
cboard = board.copy()
player.run(cboard, BLACK, print_info=True)
 def pop(self):
     if len(self.boards) > 1:
         return self.boards.pop()
     else:
         return GoBoard()
Beispiel #29
0
class GtpConnection():
    def __init__(self, go_engine, debug_mode=False):
        """
        Play Go over a GTP connection

        Parameters
        ----------
        go_engine: GoPlayer
            a program that is capable of playing go by reading GTP commands
        komi : float
            komi used for the current game
        board: GoBoard
            SIZExSIZE array representing the current board state
        """
        self.stdout = sys.stdout
        self._debug_mode = debug_mode
        sys.stdout = self
        self.go_engine = go_engine
        self.go_engine.komi = 0
        self.go_engine.selfatari = 1
        self.go_engine.pattern = 1
        self.board = GoBoard(7)
        self.param_options = {
            "selfatari": self.go_engine.selfatari,
            "pattern": self.go_engine.pattern
        }
        self.commands = {
            "protocol_version": self.protocol_version_cmd,
            "quit": self.quit_cmd,
            "name": self.name_cmd,
            "boardsize": self.boardsize_cmd,
            "showboard": self.showboard_cmd,
            "clear_board": self.clear_board_cmd,
            "komi": self.komi_cmd,
            "version": self.version_cmd,
            "known_command": self.known_command_cmd,
            "set_free_handicap": self.set_free_handicap,
            "genmove": self.genmove_cmd,
            "list_commands": self.list_commands_cmd,
            "play": self.play_cmd,
            "final_score": self.final_score_cmd,
            "legal_moves": self.legal_moves_cmd,
            "policy_moves": self.policy_moves_cmd,
            "random_moves": self.random_moves_cmd,
            "go_param": self.go_param_cmd,
            "gogui-analyze_commands": self.gogui_analyze_cmd,
            "num_sim": self.num_sim_cmd,
            "showoptions": self.showoptions_cmd
        }

        # used for argument checking
        # values: (required number or arguments, error message on argnum failure)
        self.argmap = {
            "boardsize": (1, 'Usage: boardsize INT'),
            "komi": (1, 'Usage: komi FLOAT'),
            "known_command": (1, 'Usage: known_command CMD_NAME'),
            "set_free_handicap":
            (1, 'Usage: set_free_handicap MOVE (e.g. A4)'),
            "genmove": (1, 'Usage: genmove {w, b}'),
            "play": (2, 'Usage: play {b, w} MOVE'),
            "legal_moves": (0, 'Usage: legal_moves does not have arguments'),
            "go_param": (2, 'Usage: goparam {{{0}}} {{0,1}}'.format(' '.join(
                list(self.param_options.keys())))),
            "num_sim": (1, 'Usage: num_sim #(e.g. num_sim 100 )'),
            "showoptions": (0, 'Usage: showoptions does not have arguments')
        }

    def __del__(self):
        sys.stdout = self.stdout

    def write(self, data):
        self.stdout.write(data)

    def flush(self):
        self.stdout.flush()

    def start_connection(self):
        """
        start a GTP connection. This function is what continuously monitors
        the user's input of commands.
        """
        self.debug_msg("Start up successful...\n\n")
        line = sys.stdin.readline()
        while line:
            self.get_cmd(line)
            line = sys.stdin.readline()

    def get_cmd(self, command):
        """
        parse the command and execute it

        Arguments
        ---------
        command : str
            the raw command to parse/execute
        """
        if len(command.strip(' \r\t')) == 0:
            return
        if command[0] == '#':
            return
        # Strip leading numbers from regression tests
        if command[0].isdigit():
            command = re.sub("^\d+", "", command).lstrip()

        elements = command.split()
        if not elements:
            return
        command_name = elements[0]
        args = elements[1:]
        if self.arg_error(command_name, len(args)):
            return
        if command_name in self.commands:
            try:
                self.commands[command_name](args)
            except Exception as e:
                self.debug_msg("Error executing command {}\n".format(str(e)))
                self.debug_msg("Stack Trace:\n{}\n".format(
                    traceback.format_exc()))
                raise e
        else:
            self.debug_msg("Unknown command: {}\n".format(command_name))
            self.error('Unknown command')
            sys.stdout.flush()

    def arg_error(self, cmd, argnum):
        """
        checker function 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
        """
        if cmd in self.argmap and self.argmap[cmd][0] != argnum:
            self.error(self.argmap[cmd][1])
            return True
        return False

    def debug_msg(self, msg=''):
        """ Write a msg to the debug stream """
        if self._debug_mode:
            sys.stderr.write(msg)
            sys.stderr.flush()

    def error(self, error_msg=''):
        """ Send error msg to stdout and through the GTP connection. """
        sys.stdout.write('? {}\n\n'.format(error_msg))
        sys.stdout.flush()

    def respond(self, response=''):
        """ Send msg to stdout """
        sys.stdout.write('= {}\n\n'.format(response))
        sys.stdout.flush()

    def reset(self, size):
        """
        Resets the state of the GTP to a starting board

        Arguments
        ---------
        size : int
            the boardsize to reinitialize the state to
        """
        self.board.reset(size)

    def protocol_version_cmd(self, args):
        """ Return the GTP protocol version being used (always 2) """
        self.respond('2')

    def quit_cmd(self, args):
        """ Quit game and exit the GTP interface """
        self.respond()
        exit()

    def name_cmd(self, args):
        """ Return the name of the player """
        self.respond(self.go_engine.name)

    def version_cmd(self, args):
        """ Return the version of the player """
        self.respond(self.go_engine.version)

    def clear_board_cmd(self, args):
        """ clear the board """
        self.reset(self.board.size)
        self.respond()

    def boardsize_cmd(self, args):
        """
        Reset the game and initialize with a new boardsize

        Arguments
        ---------
        args[0] : int
            size of reinitialized board
        """
        self.reset(int(args[0]))
        self.respond()

    def showboard_cmd(self, args):
        self.respond('\n' + str(self.board.get_twoD_board()))

    def showoptions_cmd(self, args):
        options = dict()
        options['komi'] = self.go_engine.komi
        options['pattern'] = self.go_engine.pattern
        options['selfatari'] = self.go_engine.selfatari
        options['num_sim'] = self.go_engine.num_simulation
        self.respond(options)

    def komi_cmd(self, args):
        """
        Set the komi for the game

        Arguments
        ---------
        args[0] : float
            komi value
        """
        self.go_engine.komi = float(args[0])
        self.respond()

    def known_command_cmd(self, args):
        """
        Check if a command is known to the GTP interface

        Arguments
        ---------
        args[0] : str
            the command name to check for
        """
        if args[0] in self.commands:
            self.respond("true")
        else:
            self.respond("false")

    def list_commands_cmd(self, args):
        """ list all supported GTP commands """
        self.respond(' '.join(list(self.commands.keys())))

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

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

    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)
        """
        moves = GoBoardUtil.generate_random_moves(self.board)
        if len(moves) == 0:
            self.respond("Pass")
        else:
            self.respond(GoBoardUtil.sorted_point_string(moves, self.board.NS))

    def gogui_analyze_cmd(self, args):
        try:
            self.respond("pstring/Legal Moves/legal_moves\n"
                         "pstring/Policy Moves/policy_moves\n"
                         "pstring/Random Moves/random_moves\n")
        except Exception as e:
            self.respond('Error: {}'.format(str(e)))

    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.board.current_player = GoBoardUtil.opponent(color)
                self.respond()
                return
            move = GoBoardUtil.move_to_coord(args[1], 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
            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()
        except Exception as e:
            self.respond("illegal move: {} {} {}".format(
                board_color, board_move, str(e)))

    def final_score_cmd(self, args):
        self.respond(self.board.final_score(self.go_engine.komi))

    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))
            #move = self.go_engine.get_move(self.board, color)
            policy_moves, type_of_move = GoBoardUtil.generate_all_policy_moves(
                self.board, self.go_engine.pattern, self.go_engine.selfatari,
                color)
            if len(policy_moves) == 0:
                self.respond("Pass")
            else:
                #print(policy_moves)
                move = policy_moves[randint(0, len(policy_moves) - 1)]
                #print(move)
                #move = GoBoardUtil.point_to_coord(move)
                #move = GoBoardUtil.sorted_point_string(policy_moves[randint(0,len(policy_moves)-1)], self.board.NS)
                #print(move)
                #print(move)
                #response = type_of_move + " " + GoBoardUtil.sorted_point_string(policy_moves, self.board.NS)
                #self.respond(response)

            if move is None:
                self.respond("pass")
                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)))
Beispiel #30
0
    def boardData(self, depth, board, m):
        # Store the {depth:{state: (winner, move), ...}, ...}
        self.boarddic[depth][board.get_twoD_board().tostring()] = (
            board.to_play, m)

        # optimize 2
        boardarr = board.get_twoD_board()
        blist = []
        blist.append(boardarr.tostring())
        for i in range(0, 7):
            emptyboard = GoBoard(board.size)
            emptyboard.move(m, 1)

            if i == 0:
                b = np.rot90(boardarr)
                if b.tostring() in blist:
                    continue
                empty_move = np.rot90(emptyboard.get_twoD_board())
            elif i == 1:
                b = np.rot90(boardarr, 2)
                if b.tostring() in blist:
                    continue
                empty_move = np.rot90(emptyboard.get_twoD_board(), 2)
            elif i == 2:
                b = np.rot90(boardarr, 3)
                if b.tostring() in blist:
                    continue
                empty_move = np.rot90(emptyboard.get_twoD_board(), 3)
            elif i == 3:
                b = np.fliplr(boardarr)
                if b.tostring() in blist:
                    continue
                empty_move = np.fliplr(emptyboard.get_twoD_board())
            elif i == 4:
                b = np.flipud(boardarr)
                if b.tostring() in blist:
                    continue
                empty_move = np.flipud(emptyboard.get_twoD_board())
            elif i == 5:
                b = np.fliplr(np.rot90(boardarr))
                if b.tostring() in blist:
                    continue
                empty_move = np.fliplr(np.rot90(emptyboard.get_twoD_board()))
            else:
                b = np.flipud(np.rot90(boardarr))
                if b.tostring() in blist:
                    continue
                empty_move = np.flipud(np.rot90(emptyboard.get_twoD_board()))

            blist.append(b.tostring())
            index = np.where(empty_move == 1)
            r, c = index[0][0] + 1, index[1][0] + 1
            new_move = board._coord_to_point(r, c)
            self.boarddic[depth][b.tostring()] = (board.to_play, new_move)