예제 #1
0
class AlphaGoPlayer():
    def __init__(self, _, seed, player):
        self.game = GoGame(13, 7.5)  # THe Go Game class

        #THERE IS NO init state
        self.board = self.game.get_starting_board()

        self.seed = seed

        self.player = -1 if player == 1 else 1

        self.args = parse_args()
        self.nnet = NetTrainer(self.game, self.args)
        self.nnet.load_checkpoint(self.args.best_model_path)

        self.mct = MCT(self.nnet, self.game, self.args, noise=False)

    def get_action(self, _, opponent_action):

        if opponent_action != -1:  # MEANS
            self.board = self.game.get_next_state(self.board, -1 * self.player,
                                                  opponent_action)

        self.board.set_move_num(0)
        action_probs = self.mct.actionProb(self.board, self.player, 0)
        self.board.set_move_num(-1)

        best_action = np.argmax(action_probs)
        self.board = self.game.get_next_state(self.board, self.player,
                                              best_action)

        return best_action
예제 #2
0
    def __init__(self, init_state, seed, player):
        self.game = GoGame(init_state)  # THe Go Game class

        #THERE IS NO init state

        # self.init_state = init_state
        self.seed = seed
        self.player = player
예제 #3
0
파일: go_app.py 프로젝트: spencerparkin/Go
 def my_turn_yet(self, **kwargs):
     name = kwargs['name']
     color = kwargs['color']
     game_doc = self.game_collection.find_one({'name': name})
     if not game_doc:
         return {'error': 'Failed to find game by the name: ' + name}
     go_game = GoGame()
     go_game.Deserialize(game_doc['data'])
     whose_turn = 'white' if go_game.whose_turn == GoBoard.WHITE else 'black'
     return {'answer': 'yes' if whose_turn == color else 'no', 'error': False}
예제 #4
0
class AlphaGoPlayer():
    def __init__(self, init_state, seed, player):
        self.game = GoGame(init_state)  # THe Go Game class

        #THERE IS NO init state

        # self.init_state = init_state
        self.seed = seed
        self.player = player

    def get_action(self, cur_state, opponent_action):
        # State is the board

        #Do we have to play oppenent's action ? why don't we get the played board then ?
        #This above step is wasting time.

        #Run the opponent's move
        cur_board = self.game.get_next_state(cur_state, -1 * self.player,
                                             opponent_action)

        #Get the possible actions
        possible_actions = self.game.get_valid_moves(cur_board, self.player)

        # ADDITIONAL LOGIC IF POSSIBLE ACTIONS SHAPED INCORRECTLY
        #     # print(actions)
        #     selected_action = None
        #     possible_actions = []
        #     for action , indicator in enumerate(actions):
        #         if indicator == 1:
        #             # selected_action = action
        #             # break
        #             possible_actions.append(action)

        #can possible actions be null ? or will resign already be in there ?

        high_score = 0
        greedy_action = None

        for action in possible_actions:
            new_board = self.game.get_next_state(cur_board, self.player,
                                                 action)
            score = self.game.get_score(new_board, self.player)

            if score >= high_score:  # Modify if multiple high scores
                greedy_action = action  # The greedy action

        # assuming best action isn't None and resign and pass will be in the possible actions

        #No need for final board
        final_board = self.game.get_next_state(cur_board, self.player,
                                               greedy_action)

        return greedy_action
예제 #5
0
파일: go_app.py 프로젝트: spencerparkin/Go
 def new_game( self, **kwargs ):
     name = kwargs[ 'name' ]
     game_doc = self.game_collection.find_one( { 'name' : name } )
     if game_doc:
         return { 'error' : 'A game by the name "%s" already exists.' % name }
     size = int( kwargs[ 'size' ] ) if 'size' in kwargs else 7
     go_game = GoGame( size )
     data = go_game.Serialize()
     game_doc = {
         'name' : name,
         'data' : data,
     }
     result = self.game_collection.insert_one( game_doc )
     return {}
예제 #6
0
    def __init__(self, _, seed, player):
        self.game = GoGame(13, 7.5)  # THe Go Game class

        #THERE IS NO init state
        self.board = self.game.get_starting_board()

        self.seed = seed

        self.player = -1 if player == 1 else 1

        self.args = parse_args()
        self.nnet = NetTrainer(self.game, self.args)
        self.nnet.load_checkpoint(self.args.best_model_path)

        self.mct = MCT(self.nnet, self.game, self.args, noise=False)
예제 #7
0
    def __init__(self, init_state, seed, player):
        self.game = GoGame(init_state)  # THe Go Game class

        #THERE IS NO init state

        # self.init_state = init_state
        self.seed = seed
        self.player = player

        # WHERE ARE WE GETTING THE ARGS FROM ?
        self.args = parse_args()
        self.nnet = NetTrainer(self.game, self.args)
        self.nnet.load_checkpoint(self.args.best_model_path +
                                  str(self.args.type))

        self.mct = MCT(self.nnet, self.game, self.args)
예제 #8
0
class AlphaGoPlayer():
    def __init__(self, init_state, seed, player):
        self.game = GoGame(init_state)  # THe Go Game class

        #THERE IS NO init state

        # self.init_state = init_state
        self.seed = seed
        self.player = player

        # WHERE ARE WE GETTING THE ARGS FROM ?
        self.args = parse_args()
        self.nnet = NetTrainer(self.game, self.args)
        self.nnet.load_checkpoint(self.args.best_model_path +
                                  str(self.args.type))

        self.mct = MCT(self.nnet, self.game, self.args)

    def get_action(self, cur_state, opponent_action):

        cur_board = self.game.get_next_state(cur_state, -1 * self.player,
                                             opponent_action)

        action_probs = self.mct.actionProb(cur_board, self.player, 0)

        best_action = np.argmax(action_probs)

        return best_action
예제 #9
0
파일: go_app.py 프로젝트: spencerparkin/Go
 def take_turn( self, **kwargs ):
     name = kwargs[ 'name' ]
     game_doc = self.game_collection.find_one( { 'name' : name } )
     if not game_doc:
         return { 'error' : 'A game by the name "%s" was not found.' % name }
     color = kwargs[ 'color' ]
     if color == 'white':
         color = GoBoard.WHITE
     elif color == 'black':
         color = GoBoard.BLACK
     else:
         return { 'error' : 'Bogus color given.' }
     row = int( kwargs[ 'row' ] )
     col = int( kwargs[ 'col' ] )
     go_game = GoGame()
     go_game.Deserialize( game_doc[ 'data' ] )
     if go_game.whose_turn != color:
         return { 'error' : 'It is not yet your turn.' }
     move = None
     if row < 0 or col < 0 or go_game.CurrentBoard().GetState( ( row, col ) ) == GoBoard.EMPTY:
         try:
             go_game.PlaceStone( row, col )
         except Exception as ex:
             return { 'error' : str(ex) }
         move = { 'row' : row, 'col' : col }
         if 'respond' in kwargs and kwargs[ 'respond' ] == 'true':
             move = go_game.CalculateReasonableMove()
             go_game.PlaceStone( move[0], move[1] )
             move = { 'row' : move[0], 'col' : move[1] }
     elif go_game.CurrentBoard().GetState( ( row, col ) ) == color:
         try:
             go_game.RelinquishStone( row, col )
         except Exception as ex:
             return { 'error' : str(ex) }
     data = go_game.Serialize()
     update = { 'data' : data }
     if move:
         update[ 'most_recent_move' ] = move
     result = self.game_collection.update_one( { 'name' : name }, { '$set' : update } )
     if result.modified_count != 1:
         return { 'error' : 'Failed to update game in database.' }
     return {}
예제 #10
0
import random
from go_game import GoGame
import numpy
import sys
numpy.set_printoptions(threshold=sys.maxsize)

if __name__ == "__main__":
    game = GoGame(13, 5.5)

    board = game.get_starting_board()
    player = -1

    while True:
        if game.get_game_ended(board, player):
            break

        actions = game.get_valid_moves(board, player)
        actions[-1] = 0
        selected_action = None
        possible_actions = []

        for action, indicator in enumerate(actions):
            if indicator == 1:
                possible_actions.append(action)

        if len(possible_actions) > 0:
            selected_action = random.choice(possible_actions)
        else:
            selected_action = game.get_action_space_size() - 1
        board = game.get_next_state(board, player, selected_action)
예제 #11
0
def main():
    print("We are going to play a game of Go.")

    board_size = 0

    while (board_size != 9 and board_size != 13 and board_size != 19):
        try:
            board_size = int(input("Please input a board size (9, 13, 19): "))
        except ValueError:
            pass

    game = GoGame(board_size)
    error = None

    def end_game():
        clear()

        (black_stones_on_board,
         white_stones_on_board) = game.get_num_stones_on_board()

        print('Black had {} stones on the board at the end of the game.\n'.
              format(black_stones_on_board))
        print('White had {} stones on the board at the end of the game.\n'.
              format(white_stones_on_board))

        if black_stones_on_board < white_stones_on_board:
            print("\n\nWhite has won!\n\n")
        elif black_stones_on_board > white_stones_on_board:
            print("\n\nBlack has won!\n\n")
        else:
            print("\n\nBlack and White have tied.")

        print("\nThe game has ended.")
        time.sleep(5)
        sys.exit(0)

    PASSED = {"Black": False, "White": False}

    while True:
        clear()

        print('It is {}\'s turn.\n'.format(game.get_turn_name()))
        print('{}\n\n'.format(game.get_board_display()))

        (black_stones_captured,
         white_stones_captured) = game.get_stones_captured()
        (black_stones_on_board,
         white_stones_on_board) = game.get_num_stones_on_board()

        print('Black has captured {} stones.\n'.format(black_stones_captured))
        print('White has captured {} stones.\n'.format(white_stones_captured))

        print('Black has {} stones on the board.\n'.format(
            black_stones_on_board))
        print('White has {} stones on the board.\n\n'.format(
            white_stones_on_board))

        if error is not None:
            print('\n' + error + '\n')
            error = None

        try:
            print("Input coordinates (0, 0) if you wish to pass the turn." +
                  "The game ends when both players pass consecutively.\n")
            print("The winner of the game is whoever has the most stones on" +
                  "the board at the end.\n\n")
            x = int(input("Please input the x coordinate: "))
            y = int(input("Please input the y coordinate: "))

            if (x == 0 and y == 0):
                PASSED[str(game.get_turn_name())] = True
                time.sleep(1)
                if (PASSED["Black"] is True and PASSED["White"] is True):
                    end_game()
            game.move(x, y)
            PASSED[str(game.get_turn_name())] = False

        except (KeyError, ValueError) as errorMessage:
            print("\n" + str(errorMessage))
            time.sleep(2)
예제 #12
0
def test_1():
    g = GoGame()

    p1 = Player('player B')
    p2 = Player('player W')

    assert not g.hasGameStarted

    resp = g.joinPlayer(p1)
    assert isinstance(resp, interactions.ResponseSuccess)
    assert resp.isValid

    assert resp.dataToSome is None
    assert json.loads(resp.dataToSender) == {'message': 'Joined as black'}
    (b, ), msgToAll = resp.dataToAll
    assert b == p1
    #assert w is None
    assert json.loads(msgToAll) == {
        'board': [['' for _ in range(19)] for _ in range(19)],
        'color': 'black',
        'turn': ''
    }

    assert not g.hasGameStarted
    assert isinstance(resp, interactions.ResponseSuccess)
    assert resp.isValid

    resp = g.joinPlayer(p2)
    assert isinstance(resp, interactions.ResponseSuccess)
    assert resp.isValid

    assert resp.dataToSome == {p1: '{"message": "player W joined as white"}'}
    assert json.loads(resp.dataToSender) == {
        'message': 'Joined as white. player B is your opponent'
    }
    (b, w), msgToAll = resp.dataToAll
    assert b == p1
    assert w == p2
    assert g.hasGameStarted
    assert json.loads(msgToAll) == {
        'board': [['' for _ in range(19)] for _ in range(19)],
        'color': 'white',
        'turn': 'player B'
    }

    assert g.hasGameStarted

    assert g._GoGame__curTurn is p1

    x = g.handleRequest(p2, "")
    assert isinstance(x, interactions.ResponseFailure)
    assert not x.isValid

    x = g.handleRequest(p1, json.dumps({'type': 'pass'}))
    assert isinstance(x, interactions.ResponseSuccess)
    assert x.isValid

    assert g._GoGame__curTurn is p2

    x = g.handleRequest(
        p2, json.dumps({
            'type': 'move',
            'locationX': 1,
            'locationY': 3
        }))
    assert isinstance(x, interactions.ResponseSuccess)
    assert x.isValid

    assert g._GoGame__curTurn is p1
예제 #13
0
파일: go_main.py 프로젝트: spencerparkin/Go
import re
import argparse

from go_game import GoGame
from go_board import GoBoard

if __name__ == '__main__':
    
    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument( '--size', help = 'Indicate the desired size of Go board.  7 is the default.', type = str )
    
    args = arg_parser.parse_args()
    
    size = int( args.size ) if args.size else 7
    go_game = GoGame( size )
    
    while go_game.consecutive_pass_count < 2:
        try:
            go_game.Print()
            
            if go_game.whose_turn == GoBoard.WHITE:
                whose_turn = 'WHITE'
            else:
                whose_turn = 'BLACK'
                
            command = input( whose_turn + ': ' )
            if command == 'resign':
                break
            elif command == 'pass':
                go_game.PlaceStone( -1, -1 )
예제 #14
0
"""
Compete with best model
"""
import os

from go_game import GoGame
from NNet import NetTrainer
from play import compete_random_greedy
from utils import parse_args

if __name__ == "__main__":
    ARGS = parse_args()
    GAME = GoGame(13, 7.5)

    OLD_WIN_COUNT, NEW_WIN_COUNT, black_win, white_win = compete_random_greedy(
        GAME, ARGS)

    # if not os.path.exists('../compete_results'):
    # os.makedirs('../compete_results')

    print('Random {} Greedy {}'.format(OLD_WIN_COUNT, NEW_WIN_COUNT),
          flush=True)

    # with open('../compete_results/' + str(ARGS.thread_num) + '.txt', 'w') as file:
    # file.write(str(OLD_WIN_COUNT) + ' ' + str(NEW_WIN_COUNT)+' '+ str(black_win) +' '+ str(white_win))
예제 #15
0
파일: go_app.py 프로젝트: spencerparkin/Go
 def game( self, **kwargs ):
     name = kwargs[ 'name' ]
     color = kwargs[ 'color' ]
     game_doc = self.game_collection.find_one( { 'name' : name } )
     if not game_doc:
         return self.MakeErrorPage( 'Failed to find game: %s', name )
     go_game = GoGame()
     go_game.Deserialize( game_doc[ 'data' ] )
     whose_turn = 'white' if go_game.whose_turn == GoBoard.WHITE else 'black'
     color_id = GoBoard.WHITE if color == 'white' else GoBoard.BLACK
     move = { 'row' : -1, 'col' : -1 }
     if 'most_recent_move' in game_doc:
         move = game_doc[ 'most_recent_move' ]
     board = go_game.CurrentBoard()
     group_list = {
         GoBoard.WHITE : board.AnalyzeGroups( GoBoard.WHITE ),
         GoBoard.BLACK : board.AnalyzeGroups( GoBoard.BLACK )
     }
     html_board_table = '<table cellspacing="0" cellpadding="0">\n'
     for i in range( board.size ):
         html_board_table += '<tr>'
         for j in range( board.size ):
             html_board_table += '<td class="cell" style="height: 64px; width: 64px;">\n'
             board_back_image = self.DetermineBoardImage( i, j, board.size )
             state = board.GetState( ( i, j ) )
             if state == GoBoard.EMPTY:
                 html_board_table += '<img src="images/%s" onclick="OnPlaceStoneClicked( \'%s\', \'%s\', %d, %d )">\n' % ( board_back_image, name, color, i, j )
                 if any( [ board.GetState( adj_location ) != GoBoard.EMPTY for adj_location in board.AdjacentLocations( ( i, j ) ) ] ):
                     html_board_table += '<img class="lib_img" id="liberty_%d_%d" src="images/liberty.png" style="visibility:hidden"/>\n' % ( i, j )
             else:
                 if state == GoBoard.WHITE:
                     board_fore_image = 'white_stone.png'
                 elif state == GoBoard.BLACK:
                     board_fore_image = 'black_stone.png'
                 hover_calls = self.FormulateLibertyHoverJSCalls( group_list[ state ], i, j )
                 click_calls = 'onclick="OnGiveUpStoneClicked( \'%s\', \'%s\', %d, %d )"' % ( name, color, i, j ) if state == color_id else ''
                 html_board_table += '<img class="back_img" src="images/%s"/>\n' % board_back_image
                 html_board_table += '<img class="fore_img" src="images/%s" %s %s/>\n' % ( board_fore_image, hover_calls, click_calls )
                 if move[ 'row' ] == i and move[ 'col' ] == j:
                     html_board_table += '<img class="high_img" src="images/highlight.png" %s/>\n' % hover_calls
             html_board_table += '</td>\n'
         html_board_table += '</tr>\n'
     html_board_table += '</table>\n'
     html_message = '<p>It is %s\'s turn.  You are %s.</p>' % ( whose_turn, color )
     html_white_info = self.GenerateInfoForColor( go_game, 'white' )
     html_black_info = self.GenerateInfoForColor( go_game, 'black' )
     scores = go_game.CalculateScores()
     html_score_info = '<center><table border="2">\n'
     html_score_info += '<tr><th></th><th>white</th><th>black</th></tr>\n'
     html_score_info += '<tr><td>score</td><td>%d</td><td>%d</td></tr>\n' % ( scores[ GoBoard.WHITE ][ 'score' ], scores[ GoBoard.BLACK ][ 'score' ] )
     html_score_info += '<tr><td>captures</td><td>%d</td><td>%d</td></tr>\n' % ( scores[ GoBoard.WHITE ][ 'captures' ], scores[ GoBoard.BLACK ][ 'captures' ] )
     html_score_info += '<tr><td>territory</td><td>%d</td><td>%d</td></tr>\n' % ( scores[ GoBoard.WHITE ][ 'territory' ], scores[ GoBoard.BLACK ][ 'territory' ] )
     html_score_info += '</table></center>\n'
     html_pass_button = '<p><center><button type="button" onclick="OnPlaceStoneClicked( \'%s\', \'%s\', -1, -1 )">forfeit turn</button>' % ( name, color )
     return '''
     <html lang="en-US">
         <head>
             <title>Go Game: %s</title>
             <link rel="stylesheet" href="css/go.css">
             <script src="https://code.jquery.com/jquery.js"></script>
             <script src="scripts/go.js"></script>
         </head>
         <body onload="OnPageLoad(%s, '%s', '%s')">
             <div>
                 <p><center>%s</center></p>
                 <p><center>%s</center></p>
                 <!--<center><input type="checkbox" id="respond">Have computer respond.</input></center>-->
                 <center>%s</center>
                 %s
                 <p><center>Click an empty board intersection to place a stone.  Click on your own stone to give it up as a prisoner (at end of game.)</center></p>
             </div>
             <div>
                 %s
                 %s
             </div>
         </body>
     </html>
     ''' % ( name, ('true' if whose_turn == color else 'false'), color, name, html_message, html_score_info, html_board_table, html_pass_button, html_white_info, html_black_info )