Exemple #1
0
def generate(config, model_file, output_file):
    model = load_model(model_file)
    with open(output_file, 'ab') as fout:
        file_pos = fout.tell()
        # Truncate any partially written record
        fout.seek(file_pos - file_pos % record_size(config.size))
        samples = 0
        start_time = time.time()
        game_boards = numpy.array(
            [new_board(config.size) for i in range(config.batch_size)])
        game_moves = [[] for i in range(config.batch_size)]
        while True:
            _values, priors = model.predict(game_boards)
            priors = numpy.reshape(priors, (-1, config.size, config.size))
            for i in range(config.batch_size):
                probs = fix_probabilities(game_boards[i], priors[i])
                move = sample_move(probs)
                game_moves[i].append(move)
                game_boards[i] = make_move(game_boards[i], move)
                if winner(game_boards[i]):
                    samples += 1
                    board, won, visits = game_result(config, model,
                                                     game_moves[i])
                    write_record(fout, board, won, visits)
                    fout.flush()
                    print_board(board, file=sys.stderr)
                    print('Games: %d, Time per game: %.2fs' %
                          (samples, (time.time() - start_time) / samples),
                          file=sys.stderr)
                    game_boards[i] = new_board(config.size)
                    game_moves[i] = []
Exemple #2
0
def compare(config, model_file1, model_file2):
    models = [load_model(model_file1), load_model(model_file2)]
    games = 0
    first_player_wins = 0
    win_ratio, uncertainty = None, None
    while True:
        move_index = 0
        predictors = [TreeSearchPredictor(config.search_config, model, new_board(config.size), True) for model in models]
        while not winner(predictors[0].board):
            if move_index == 0:
                predictor = predictors[1]
            else:
                predictor = predictors[(games ^ move_index) & 1]
            predictor.run(config.iterations)
            value, probabilities = predictor.predict()
            if move_index < 3:
                move = sample_move(probabilities)
            else:
                move = best_move(probabilities)
            for predictor in predictors:
                predictor.make_move(move)
            if games & 1 == move_index & 1:
                print_board(flip(predictors[0].board), move, file=sys.stderr)
            else:
                print_board(predictors[0].board, flip_move(move), file=sys.stderr)
            print('%s model win probability: %.2f' % (['First', 'Second'][((games ^ move_index) & 1)], (value + 1) / 2), file=sys.stderr)
            if games > 0:
                print('Win ratio %.2f ± %.2f (%d games)' % (win_ratio, uncertainty, games), file=sys.stderr)
            move_index += 1
        games += 1
        if games & 1 == move_index & 1:
            first_player_wins += 1
        win_ratio = float(first_player_wins) / games
        uncertainty = win_ratio * math.sqrt(win_ratio * (1 - win_ratio) / games)
Exemple #3
0
def game_status(players, channel):
    """Returns the current game status, game board, and whose turn it is if there is an ongoing game."""
    if channel['ongoing_game'] is True:
        if not channel['accepted_invite']:
            res = {
                "response_type":
                "ephemeral",
                "text":
                "Waiting for %s to accept a game. To cancel invite type '/ttt end'"
                % channel['player2']
            }
        if channel['accepted_invite'] is True:
            game_board = game.print_board(channel['board'])
            user_name = str(request.form.get('user_name'))
            turn = channel['turn']
            res = {
                "response_type":
                "in_channel",
                "text":
                "It is " + turn +
                "'s turn.\nHere is the current gameboard:\n For instructions type '/ttt instructions'\n"
                + "```" + game.print_board(channel['board']) + "```"
            }

    if channel['ongoing_game'] is False:
        res = {
            "response_type": "ephemeral",
            "text": "To start a game type '/ttt challenge @username'"
        }
    return res
Exemple #4
0
def replay_game():
    """
    This function reads a board state from a file, and calls the
    game.print_board function to print the board state.
    """
    path = input("Please enter the absolute path of the game file: ")
    board = []
    for _ in range(25):
        board.append(' ')
    with open(path, "r") as fin:
        for line in fin:
            for i in range(25):
                board[i] = line[i]
            print_board(board)
            sleep(1)
Exemple #5
0
def play():
    cur_player = input('Would you like to be X or O: ').upper()
    main_board = game.new_board()

    while True:
        game.print_board(main_board)
        move_str = input(
            'Where would you like to place an %s? (e.g. 12 for 1st row, 2nd column) '
            % cur_player)
        move_row = int(move_str[0]) - 1
        move_col = int(move_str[1]) - 1
        main_board = game.make_move(main_board, move_row, move_col, cur_player)
        if game.any_win(main_board, cur_player):
            game.print_board(main_board)
            print(
                'Congratulations Player %s! Better luck next time player %s' %
                (cur_player, game.other_player(cur_player)))
            break
        elif game.board_full(main_board):
            game.print_board(main_board)
            print('No more moves possible. The game ended in a draw.')
            break
        cur_player = game.other_player(cur_player)

    if input('Would you like to play again? [y/n]') == 'y':
        play()
    else:
        print('Thanks for playing.')
        return 0
Exemple #6
0
def accept(user_id, user_name, channel):
    """Allows the challenged player to accept a challenge"""
    players = channel['players']
    player2 = channel['player2']
    player1 = channel['player1']

    if channel['ongoing_game'] is False:
        res = {
            "response_type": "ephemeral",
            "text": "To start a game type '/ttt challenge @username'"
        }

    if channel['ongoing_game'] is True:
        if user_name == player2:
            players |= {user_id}
            channel['ongoing_game'] = True
            channel['accepted_invite'] = True
            channel['turn'] = player2
            game.initialize(player1, player2)
            res = {
                "response_type":
                "in_channel",
                "attachments": [{
                    "text":
                    "Please use the following cell number to make your move.\n/ttt move # - to make a move\n/ttt end - to end the game\n"
                    + "```" + game.instructions() + "```" +
                    "\nHere is the current game board:\n" + "```" +
                    game.print_board(channel['board']) + "```",
                    "pretext":
                    "Challenge accepted. %s starts the game. Your marker is 'O'. Please read the instructions below:"
                    % player2,
                    "mrkdwn_in": ["text", "pretext"]
                }]
            }

        if user_name != player2:
            res = {
                "response_type": "ephemeral",
                "text": "You were not the challenged player.",
            }

    return res
Exemple #7
0
board = [''] * 10
player_letter, computer_letter = input_letter()

turn = ''
if random.randint(0, 1) == 1: turn = 'computer'
else: turn = 'player'

print(turn + ' play first\n')

game_in_progress = True

while game_in_progress:

    if turn == 'player':
        print_board(board)
        move = get_move(board)
        make_move(board, player_letter, move)

        if is_winner(board, player_letter):
            print_board(board)
            print("You win!!")
            game_in_progress = False
        else:
            if is_board_full(board):
                print_board(board)
                print('Draw')
                break
            else:
                turn = 'computer'
Exemple #8
0
 def showboard(self):
     output = io.StringIO()
     print_board(self.board, file=output)
     result = output.getvalue().strip()
     output.close()
     return result
Exemple #9
0
import game
import dealer
from copy import deepcopy

game.verbose = False

board = game.start()
#game.output_board(board)
game.print_board(board)


def recurse(board, moves):
    #print(len(moves))
    if game.has_won(board):
        print(len(moves), " moves")
        print(moves)
        exit()
    elif len(moves) > 200:
        print("ERR?")
        print(moves)
        return
    if len(moves) == 52:
        print(".", end='')
    # Head all

    for from_stack in range(len(board.stacks)):
        f = deepcopy(board)
        if game.to_head(f, from_stack):
            new_moves = deepcopy(moves)
            new_moves.append(f"h {from_stack}")
            recurse(f, new_moves)
Exemple #10
0
def compare(config, model_file1, model_file2, temp, num_games):
    models = [load_model(model_file1), load_model(model_file2)]
    games = 0
    first_player_wins = 0
    win_ratio, uncertainty = None, None

    ratios = []
    # while True:
    for i in range(num_games):
        move_index = 0
        predictors = [
            TreeSearchPredictor(config.search_config, model,
                                new_board(config.size), True)
            for model in models
        ]

        # exp uct of model2 is 100
        # predictors = ["avshalom", "shlomo"]
        # config.search_config.uct_factor = 5.0
        # predictors[0] = TreeSearchPredictor(config.search_config, models[0], new_board(config.size), True)
        # config.search_config.uct_factor = 100.0
        # predictors[1] = TreeSearchPredictor(config.search_config, models[1], new_board(config.size), True)

        # exp uct of model2 is 100
        # predictors = ["avshalom", "shlomo"]
        # config.search_config.uct_factor = 5.0
        # predictors[0] = TreeSearchPredictor(config.search_config, models[0], new_board(config.size), True)
        # config.search_config.uct_factor = 100.0
        # predictors[1] = TreeSearchPredictor(config.search_config, models[1], new_board(config.size), True)

        # exp virtual loss of model2 is 100
        # predictors = ["avshalom", "shlomo"]
        # config.search_config.virtual_loss = 3.0
        # predictors[0] = TreeSearchPredictor(config.search_config, models[0], new_board(config.size), True)
        # config.search_config.virtual_loss = 100.0
        # predictors[1] = TreeSearchPredictor(config.search_config, models[1], new_board(config.size), True)

        # exp virtual loss of model2 is 0
        # predictors = ["avshalom", "shlomo"]
        # config.search_config.virtual_loss = 3.0
        # predictors[0] = TreeSearchPredictor(config.search_config, models[0], new_board(config.size), True)
        # config.search_config.virtual_loss = 0
        # predictors[1] = TreeSearchPredictor(config.search_config, models[1], new_board(config.size), True)

        while not winner(predictors[0].board):
            if move_index == 0:
                predictor = predictors[1]
            else:
                predictor = predictors[(games ^ move_index) & 1]
            predictor.run(config.iterations)
            value, probabilities = predictor.predict()

            # exp uniform probs
            #uprobs = [0.00826446] * 121
            #if games & 1 == move_index & 1:
            #   probabilities = np.array(uprobs).reshape(11, -1)

            # exp temperature
            tprobs = temperature(probabilities, temp)
            if games & 1 == move_index & 1:
                probabilities = tprobs
                #print(probabilities)

            if move_index < 3:
                move = sample_move(probabilities)
            else:
                #move = best_move(probabilities)
                move = sample_move(probabilities)
            for predictor in predictors:
                predictor.make_move(move)
            if games & 1 == move_index & 1:
                print_board(flip(predictors[0].board), move, file=sys.stderr)
            else:
                print_board(predictors[0].board,
                            flip_move(move),
                            file=sys.stderr)
            print('%s model win probability: %.2f' %
                  (['First', 'Second'][((games ^ move_index) & 1)],
                   (value + 1) / 2),
                  file=sys.stderr)
            if games > 0:
                print('Win ratio %.2f ± %.2f (%d games)' %
                      (win_ratio, uncertainty, games),
                      file=sys.stderr)
            move_index += 1
        games += 1
        if games & 1 == move_index & 1:
            first_player_wins += 1
        win_ratio = float(first_player_wins) / games
        uncertainty = win_ratio * math.sqrt(win_ratio *
                                            (1 - win_ratio) / games)

        ratios.append(win_ratio)

    return ratios
Exemple #11
0
from game import check_win, create_board, print_board
from game2 import check_player_move

# Initial Data
board_size = 3
no_of_players = 2

# Create initial Board and Print to Console
game = create_board(board_size)

# Switch between players
moves = board_size * board_size
players = [i+1 for i in range(no_of_players)]

# Print Board in starting
print_board(game)

# Run for moves:
for i in range(moves):
    idx = i % no_of_players
    curr_player = players[idx]
    print(f"Hello Player {curr_player}")
    player_made_move = False

    while not player_made_move:
        a, r, c = check_player_move(board_size, game)
        if a:
            player_made_move = True
            game[r-1][c - 1] = curr_player
            print_board(game)
Exemple #12
0
def move(user_id, players, user_name, turn, possible_moves, player1, player2,
         channel, cell):
    """Returns a draw, winner, or prints the new board after a player makes a move"""
    if channel['accepted_invite'] is False:
        res = {
            "response_type": "ephemeral",
            "text": "To start a game type '/ttt challenge @username'"
        }
    if channel['accepted_invite'] is True:
        if user_id in players:
            if turn == user_name:
                if cell in possible_moves:
                    game_moves = channel['possible_moves']
                    if cell not in game_moves:
                        res = {
                            "response_type": "ephemeral",
                            "text": "Sorry, that is not a legitimate move."
                        }
                    if cell in game_moves:
                        game_board = game.make_move(cell, turn,
                                                    channel['board'])
                        channel['board'] = game_board
                        game_moves.remove(cell)

                        if len(game_moves) > 0 and game.is_winner(
                                game_board, cell) is True:
                            channel['board'] = [' '] * 9
                            channel['ongoing_game'] = False
                            channel['accepted_invite'] = False
                            channel['possible_moves'] = [
                                0, 1, 2, 3, 4, 5, 6, 7, 8
                            ]
                            res = {
                                "response_type":
                                "in_channel",
                                "text":
                                turn + " has won the game!\n" + "```" +
                                game.print_board(game_board) + "```"
                            }

                        if len(game_moves) > 0 and game.is_winner(
                                game_board, cell) is False:
                            if turn == player1:
                                channel['turn'] = player2
                            else:
                                channel['turn'] = player1

                            res = {
                                "response_type":
                                "in_channel",
                                "text":
                                "You selected cell  " + str(cell) +
                                "\nIt is now " + channel['turn'] +
                                "'s turn.\n" +
                                "Here is the current gameboard:\n" + "```" +
                                game.print_board(game_board) + "```"
                            }

                        if len(game_moves) == 0:
                            channel['board'] = [' '] * 9
                            channel['ongoing_game'] = False
                            channel['accepted_invite'] = False
                            channel['possible_moves'] = [
                                0, 1, 2, 3, 4, 5, 6, 7, 8
                            ]
                            res = {
                                "response_type":
                                "in_channel",
                                "text":
                                "DRAW!\n " + "```" +
                                game.print_board(game_board) + "```"
                            }

            if turn != user_name:
                res = {
                    "response_type": "ephemeral",
                    "text": "Sorry, it is not your turn."
                }
        if user_id not in players:
            player1 = channel['player1']
            player2 = channel['player2']
            res = {
                "response_type":
                "in_channel",
                "text":
                "Sorry, this is a game between %s and %s. To end their game type '/ttt end'"
                % (player1, player2)
            }

    # if channel['game_ended'] is True:
    #     res = {
    #         "response_type": "ephemeral",
    #         "text": "To start a new game type '/ttt challenge @username'"
    #     }

    if channel['accepted_invite'] is False and channel['ongoing_game'] is True:
        res = {
            "response_type":
            "in_channel",
            "text":
            "Waiting for %s to accept a game. To cancel invite type '/ttt end'"
            % channel['player2']
        }

    return res