示例#1
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()
def run():
    """
    start the gtp connection and wait for commands.
    """
    board = GoBoard(7)
    con = GtpConnection(FlatMCSimPlayer(10, board), board)
    con.start_connection()
示例#3
0
def run():
    """
    start the gtp connection and wait for commands.
    """
    board = GoBoard(7)
    con = GtpConnection(Gomoku(), board)
    con.start_connection()
示例#4
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)
示例#5
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()
示例#6
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")
        }
示例#7
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')
        }
示例#8
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)
示例#9
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)
         ],
     )
示例#10
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 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 = []
示例#15
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)
示例#16
0
def run():
    """
    start the gtp connection and wait for commands.
    """
    board = GoBoard(7)
示例#17
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)

        # Assignment2 - 1.timelimit
        self.timelimit = 1
        signal.signal(signal.SIGALRM, self.timeout)
        self.boarddic = {}
        for d in range(0, 49):
            self.boarddic[d] = {}

        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,

            # Assignment2 - 1.timelimit
            "timelimit": self.timelimit_cmd,

            # Assignment2 - 2.solve
            "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}'),

            # Assignment2 - 1.timelimit
            "timelimit": (1, "Usage: timelimit 1<=INT<=100"),
        }
示例#18
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')
        }
示例#19
0
文件: main.py 项目: sooheng/wxGo
    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)
示例#20
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)])
 def pop(self):
     if len(self.boards) > 1:
         return self.boards.pop()
     else:
         return GoBoard()
 def __init__(self):
     empty_board = GoBoard()
     self.boards = [empty_board]
    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
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)