Beispiel #1
0
    def make_move(self, request):
        """Makes a move. Returns a game state with message"""
        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        user = User.query(User.key == game.user).get()

        if request.move.isdigit() and int(request.move) in range(1, 10):

            if game.game_over:
                return game.to_form('Game already over!')

            if int(request.move) not in game.remaining_moves:
                return game.to_form('That spot is already marked!')

            game.remaining_moves.remove(int(request.move))
            game.x_moves.append(int(request.move))
            msg = "'X' marked on {}".format(request.move)

            is_player_win = check_win(game.x_moves, int(request.move))

            if is_player_win == "win":
                game.end_game(True)
                user.points += 2
                user.put()
                return game.to_form("Player wins!")

            if(len(game.remaining_moves) == 0):
                user.points += 1
                user.put()
                game.end_game(True)
                return game.to_form("The game has ended in a tie!")

            omove = computer_move(game.o_moves, game.x_moves,
                                  game.remaining_moves)
            game.remaining_moves.remove(omove)
            game.o_moves.append(omove)
            is_computer_win = check_win(game.o_moves, omove)

            if is_computer_win == "win":

                game.end_game(True)
                return game.to_form("Computer wins!")

            msg += ", 'O' marked on {}".format(omove)

            game.put()
            return game.to_form(msg)

        else:
            raise endpoints.BadRequestException(
                    'Your guess should be a number between 1 and 9.')
Beispiel #2
0
    def make_move(self, request):
        """Makes a move. Returns a game state with message"""
        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        user = User.query(User.key == game.user).get()

        if request.move.isdigit() and int(request.move) in range(1, 10):

            if game.game_over:
                return game.to_form('Game already over!')

            if int(request.move) not in game.remaining_moves:
                return game.to_form('That spot is already marked!')

            game.remaining_moves.remove(int(request.move))
            game.x_moves.append(int(request.move))
            msg = "'X' marked on {}".format(request.move)

            is_player_win = check_win(game.x_moves, int(request.move))

            if is_player_win == "win":
                game.end_game(True)
                user.points += 2
                user.put()
                return game.to_form("Player wins!")

            if (len(game.remaining_moves) == 0):
                user.points += 1
                user.put()
                game.end_game(True)
                return game.to_form("The game has ended in a tie!")

            omove = computer_move(game.o_moves, game.x_moves,
                                  game.remaining_moves)
            game.remaining_moves.remove(omove)
            game.o_moves.append(omove)
            is_computer_win = check_win(game.o_moves, omove)

            if is_computer_win == "win":

                game.end_game(True)
                return game.to_form("Computer wins!")

            msg += ", 'O' marked on {}".format(omove)

            game.put()
            return game.to_form(msg)

        else:
            raise endpoints.BadRequestException(
                'Your guess should be a number between 1 and 9.')
Beispiel #3
0
def minimax_ab(board,
               player_id,
               depth,
               maximize,
               alpha=-inf,
               beta=-inf) -> (int, int):
    """
    # Minimax_ab

    This function implements a minimax game tree search with alpha/beta
    pruning.

    It returns a tuple of (int, int), which represents the most optimal
    move and that move's score, which is a sum of the different weights
    of the boards.

    The board weights are determined by the fastest possible win states.
    """
    winner = game.check_win(board)
    if winner == player_id:
        return None, 10 + depth
    if winner not in (' ', "draw"):
        return None, -10 - depth
    if winner == "draw":
        return None, 0
    if depth == 0:
        return None, None

    global boards
    boards += 1

    best_move = None
    value = None

    for i in range(25):
        if board[i] == ' ':
            board[i] = player_id
            _, value = minimax_ab(board, 'O' if player_id == 'X' else 'X',
                                  depth - 1, False, alpha, beta)
            board[i] = ' '
            if (value is not None
                    and (value > alpha if maximize else value < beta)):
                if maximize:
                    alpha = value
                else:
                    beta = value
                if (alpha != -inf and beta != inf and alpha >= beta
                        if maximize else beta >= alpha):
                    break
                best_move = i

    if maximize:
        return best_move, alpha

    return best_move, beta
def self_play(model, test=False):

    current_player = FIRST_PLAYER
    result = 0
    board = game.reset_board()
    first_game_records = []
    second_game_records = []
    last_moves = None

    for turn in range(42):

        if test:
            if current_player == FIRST_PLAYER:
                move, q = search(model, board, current_player)
            else:
                print(np.array(board))
                y = input("input row:")
                x = input("input column:")
                move = [int(y), int(x)]
        else:
            legal_moves = game.get_legal_moves(board)
            move = legal_moves[random.randrange(0, len(legal_moves))]

        board[move[0]][move[1]] = current_player
        result = game.check_win(board, 4)

        if current_player == FIRST_PLAYER:
            record = [get_board_by_player(board, FIRST_PLAYER), 0]
            first_game_records.append(record)
        else:
            record = [get_board_by_player(board, SECOND_PLAYER), 0]
            second_game_records.append(record)

        current_player *= -1

        if result != 0:
            break

    r = random.choice(first_game_records)
    r[1] = 1 if result == FIRST_PLAYER else -1 if result == SECOND_PLAYER else 0
    loss = model.train(
        np.array(r[0]).reshape(1, 8, 8, 2),
        np.array(r[1]).reshape(1, 1), 1)

    r = random.choice(second_game_records)
    r[1] = -1 if result == FIRST_PLAYER else 1 if result == SECOND_PLAYER else 0
    loss = model.train(
        np.array(r[0]).reshape(1, 8, 8, 2),
        np.array(r[1]).reshape(1, 1), 1)

    return loss, result
Beispiel #5
0
def start_game(player, max_buffer_size, is_active):
    global win_flag
    global passed
    global win

    while is_active:

        send_board(player)  #1send
        #2rcv
        client_input = process_input(
            player, receive_input(player.get("conn"), max_buffer_size))

        if "QUIT" in client_input:
            print("Client is requesting to quit")
            player.get("conn").close()
            # del players[int(player.get("id"))-1]
            print("Connection " + str(player.get("address")[0]) + ":" +
                  str(player.get("address")[1]) + " closed")
            is_active = False
        else:
            if 'P' in client_input:
                if win_flag == True:
                    data = "False|Someone already finished, enter 'T' to tap\n"
                    send_data(player, data)
                else:
                    turn_cards.update({client_input[1]: client_input[2:]})
                    print(turn_cards)

                    player.get("hand").remove(client_input[2:])
                    print(player.get("hand"))

                    data = "True|" + game.get_board(players,
                                                    int(player.get("id")) - 1)
                    send_data(player, data)  #3send

                    while len(turn_cards) < max_players:
                        continue

                    data = ""
                    if len(turn_cards) == max_players:
                        data = "Cont|All players ready, 1-2-3 Pass!\n"
                        send_data(player, data)  #4send

                        pass_cards()
                        passed += 1

                    # print("matutulog na ako")
                    print(passed)
                    if passed == max_players:  #dahil lahat nagpapass cards, iccclear lang yung list pag lahat nakapagpasa na
                        turn_cards.clear()
                        passed = 0

            elif 'F' in client_input:
                if win_flag == True:
                    data = "False|Someone already finished, enter 'T' to tap\n"
                    send_data(player, data)
                else:
                    win_flag = game.check_win(player.get("hand"))

                    if win_flag == True:
                        data = "True|Congratulations, you win!\n"
                        send_data(player, data)

                        player["win"] = win
                        win += 1

                        while win < (max_players + 1):
                            continue

                        if win == (max_players + 1):
                            data = "Quit|" + game.get_board(
                                players,
                                int(player.get("id")) - 1)
                            send_data(player, data)
                    else:
                        data = "False|Hand incomplete, try again \nWinning conditions still not met\n"
                        send_data(player, data)

            elif 'T' in client_input:
                if win_flag == True:
                    data = "True|Tap successful\n"

                    if win == max_players:
                        data += "\nYou tapped last, you lose\n"

                    send_data(player, data)

                    player["win"] = win
                    win += 1

                    while win < (max_players + 1):
                        continue

                    if win == (max_players + 1):
                        data = "Quit|" + game.get_board(
                            players,
                            int(player.get("id")) - 1)
                        send_data(player, data)

                else:
                    data = "False|Tap invalid, there is no winner yet\n"
                    send_data(player, data)

        data = ""
        # print("cur ergo?")

    print("out of loop")
    return is_active
Beispiel #6
0
def test_check_win_false():
    guess = list("coverage")
    guess[0] = "_"
    assert not check_win("coverage", guess)
Beispiel #7
0
def test_check_win_true():
    assert check_win("pytest", list("pytest"))
Beispiel #8
0
import game
import stats
import config


if __name__ == '__main__':
    while True:
        won, player = game.check_win(config.STATE)
        game.print_field()

        if won:
            print('Draw!' if player not in [0, 1] else config.STATE.players[player].get_name() + ' won!')
            break

        player = config.STATE.players[config.STATE.turn]
        print('\n', player.get_name() + ' turn')

        config.STATE = game.compute_move(config.STATE, game.make_turn(player))

    stats.show_summary()
    stats.show_stats()
Beispiel #9
0
                        (c * square_size + square_size // 2,
                         r * square_size + square_size + square_size // 2),
                        radius)
                elif board[r][c] == C4.YELLOW:
                    pygame.draw.circle(
                        screen, YELLOW,
                        (c * square_size + square_size // 2,
                         r * square_size + square_size + square_size // 2),
                        radius)

        pygame.display.flip()

        if game_over:
            pygame.draw.rect(screen, BLACK, (0, 0, width, square_size))

            winner = C4.check_win(board)
            if ai:
                if winner is None:
                    title = f"Game Over: Tie."
                else:
                    if winner == user:
                        winner = 'You'
                        winner_color = user_color
                    else:
                        winner = 'AI'
                        winner_color = ai_color
                    title = f"{winner} won."
            else:
                if winner is None:
                    title = f"Game Over: Tie."
                else:
Beispiel #10
0
def mcts(node, expanding=False):
    """
    # mcts
    This function implements Monte-Carlo Tree Search.
    """
    global boards
    boards += 1

    node.games += 1
    if game.check_win(node.board) != ' ':
        if game.check_win(node.board) == 'X' or game.check_win(
                node.board) == 'O':
            node.wins += 1
        return

    # Selection
    move = -1
    next_player = 'O' if node.player_id == 'X' else 'X'
    next_board = deepcopy(node.board)
    if len(node.children) == 25:
        max_uct = -inf
        for child in node.children:
            uct = child.wins / child.games + sqrt(
                log(node.games) / child.games)
            if uct > max_uct:
                max_uct = uct
                move = child.move

    # Expansion and Simulation
    elif not expanding:
        for move_expansion in range(25):
            if node.board[move_expansion] != ' ':
                continue
            next_board = deepcopy(node.board)
            next_board[move_expansion] = node.player_id
            next_node = Node(next_board, next_player, move_expansion)
            is_child = False
            for child in node.children:
                if child.board == next_board:
                    next_node = child
                    is_child = True
            if not is_child:
                node.children.append(next_node)
            mcts(next_node, True)
    else:
        move = randint(0, 24)
        while node.board[move] != ' ':
            move = randint(0, 24)
        next_board[move] = node.player_id
        next_node = Node(next_board, next_player, move)
        is_child = False
        for child in node.children:
            if child.board == next_board:
                next_node = child
                is_child = True
        if not is_child:
            node.children.append(next_node)
        mcts(next_node, expanding)

    # Back-Propagation
    node.wins = 0
    node.games = 0
    if node.children:
        for child in node.children:
            node.wins += child.games - child.wins
            node.games += child.games
Beispiel #11
0
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)

    win, line, p = check_win(game)
    if win:
        print(f"Player {p} wins the game at {line}")
        break
Beispiel #12
0
def move(channel_id, request, player):
    game = active_games.get(channel_id, None)
    message = {
        "response_type":
        "ephemeral",
        "text":
        "Sorry that was invalid, please select a number from the following configuration",
    }
    if game == None:
        message = {
            "response_type": "ephemeral",
            "text":
            "Sorry there is no active game in this channel at this time.",
        }
        return message
    print "statement " + game.player_1 + " and this is counter: " + str(
        game.turn_count
    ) + " and this is p0 " + game.player_0 + " and this is player " + player
    #statement U7VQCMCKG and this is counter: 0 and this is p0 U7V2GQZ9T and this is player0 U7V2GQZ9T
    if (game.turn_count % 2 == 1 and player != game.player_1):
        message = {
            "response_type": "ephemeral",
            "text": "Nice try! But it's not your turn",
        }
        return message
    if (game.turn_count % 2 == 0 and player != game.player_0):
        message = {
            "response_type": "ephemeral",
            "text": "Nice try! But it's not your turn",
        }
        return message
    try:
        number = int(request)
    except:
        message = {
            "response_type": "ephemeral",
            "text": "That is not a valid move",
        }
        return message
    if game.is_free(number) == False:
        message = {
            "response_type": "ephemeral",
            "text": "That is not a valid move",
        }
        return message
    #TO DO: verify player is in game and channel
    if player == game.player_0 and game.turn_count == 0:
        p0 = "<@" + player + ">"
        #first move scenario
        game.turn(number)
        message = {
            "response_type":
            "in_channel",
            "text":
            "<@" + game.player_0 + "> has challenged <@" + game.player_1 +
            "> to a game of tic tac toe!\nCurrent board is\n" +
            print_board(game.board) + "\n<@" + game.player_1 +
            "> please make your move",
        }
        return message
    game.turn(number)
    if game.check_win() == True:
        return end_game(channel_id, player)
    else:
        message = {
            "response_type": "in_channel",
            "text": "current board status:\n" + print_board(game.board),
        }

    return message