Python 绝对初学者:井字棋;为什么我的条件不起作用?

Python for the Absolute Beginner: Tic-Tac-Toe; Why Did my Condition Not Work?

按照上面列出的书中给出的说明,我试图改进我之前构建的 Tic-Tac-Toe 游戏,使其无法获胜。现在,我最终成功完成了这项任务,但我来到这里的原因是我未能理解为什么我最初的解决方案无效。

这是未经编辑的原始代码:

    #Tic-Tac-Toe
#Plays a game of Tic-Tac-Toe against a human opponent

#Global constants
X = "X"
O = "O"
EMPTY = " "
TIE = "TIE"
NUM_SQUARES = 9

def display_instruct():
    """Diplsay game instructions."""
    print(
    """
    Welcome to the greatest inetellectual challenge of all time: Tic-Tac-Toe.
    This will be a showdown between your rudimentary human brain and my superior
    silicon processor.

    You will make your move by entering  a number, 0-8. The number will correspond
    to the board position as illustrated:

                    0 | 1 | 2
                    ---------
                    3 | 4 | 5
                    ---------
                    6 | 7 | 8

    Prepare yourself, human. The ultimate battle is about to begin!\n
    """
    )

def ask_yes_no(question):
    """Ask a yes or no question."""
    response = None
    while response not in ("y", "n"):
        response = input(question).lower()
    return response

def ask_number(question, low, high):
    """Ask for a number within a range."""
    response = None
    while response not in range(low, high):
        response = int(input(question))
    return response

def pieces():
    """Determine if playor or computer goes first"""
    go_first = ask_yes_no("Do you require the first move? (y/n): ")
    if go_first == "y":
        print("\nThen take the first move. You will need it.")
        human = X
        computer = O
    else:
        print("\nYour bravery will be your undoing... I will go first.")
        computer = X
        human = O
    return computer, human

def new_board():
    """Create new game baord."""
    board = []
    for square in range(NUM_SQUARES):
        board.append(EMPTY)
    return board

def display_board(board):
    """Display game board on screen."""
    print("\n\t", board[0], "|", board[1], "|", board[2])
    print("\t", "---------")
    print("\t", board[3], "|", board[4], "|", board[5])
    print("\t", "---------")
    print("\t", board[6], "|", board[7], "|", board[8], "\n")

def legal_moves(board):
    """Creates a list of legal moves."""
    moves = []
    for square in range(NUM_SQUARES):
        if board[square] == EMPTY:
            moves.append(square)
    return moves

def winner(board):
    """Determine the game winner."""
    WAYS_TO_WIN = ((0, 1, 2),
                   (3, 4, 5),
                   (6, 7, 8),
                   (0, 3, 6),
                   (1, 4, 7),
                   (2, 5, 8),
                   (0, 4, 8),
                   (2, 4, 6))
    for row in WAYS_TO_WIN:
        if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
            winner = board[row[0]]
            return winner

    if EMPTY not in board:
        return TIE

    return None

def human_move(board, human):
    """Get human move."""
    legal = legal_moves(board)
    move = None
    while move not in legal:
        move = ask_number("Where will you move? (0 - 8):", 0, NUM_SQUARES)
        if move not in legal:
            print("\nThat square is already occipied, foolish hooman. Choose another.\n")
    print("Fine...")
    return move

def computer_move(board, computer, human):
    "Make computer move."""
    #Make a copy to work with since function will be changing list
    board = board[:]
    #The best positions to have, in order
    BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7)

    print("I shall take square number", end=" ")

    #If computer can win, take that move
    for move in legal_moves(board):
        board[move] = computer
        if winner(board) == computer:
            print(move)
            return move
        #Done checking this move, undo it
        board[move] = EMPTY

    #If human can win, block that move
    for move in legal_moves(board):
        board[move] = human
        if winner(board) == human:
            print(move)
            return move
        #Done checking this move, undo it
        board[move] = EMPTY

    #Since no one can win on next move, pick best option square
    for move in BEST_MOVES:
        if move in legal_moves(board):
            print(move)
            return move

def next_turn(turn):
    """Switch turns."""
    if turn == X:
        return O
    else:
        return X

def congrat_winner(the_winner, computer, human):
    """Congratulate the winner."""
    if the_winner != TIE:
        print(the_winner, "won!\n")
    else:
        print("It's a tie\n")

    if the_winner == computer:
        print("As I predicted hooman, I am triumphant! \n" \
              "proof that silicon is superior to flesh in all regards.")

    elif the_winner == human:
        print("No, no! It cannot be! Somehow you tricked me, ape. \n" \
              "But never again, I, the computer, so swear it!")

    elif the_winner == TIE:
        print("You were most fortunate, hooman, and somehow managed to tie me. \n" \
              "Celebrate today... for this is the best you will ever achieve.")

def main():
    display_instruct()
    computer, human = pieces()
    turn = X
    board = new_board()
    display_board(board)

    while not winner(board):
        if turn == human:
            move = human_move(board, human)
            board[move] = human
        else:
            move = computer_move(board, computer, human)
            board[move] = computer
        display_board(board)
        turn = next_turn(turn)

    the_winner = winner(board)
    congrat_winner(the_winner, computer, human)

#Start the program
main()
input("\n\nPress the enter key to quit.")

这是我最初尝试做的事情:

#Tic-Tac-Toe
#Plays a game of Tic-Tac-Toe against a human opponent

#Global constants
X = "X"
O = "O"
EMPTY = " "
TIE = "TIE"
NUM_SQUARES = 9
human_moves_so_far = []

def display_instruct():
    """Diplsay game instructions."""
    print(
    """
    Welcome to the greatest inetellectual challenge of all time: Tic-Tac-Toe.
    This will be a showdown between your rudimentary human brain and my superior
    silicon processor.

    You will make your move by entering  a number, 0-8. The number will correspond
    to the board position as illustrated:

                    0 | 1 | 2
                    ---------
                    3 | 4 | 5
                    ---------
                    6 | 7 | 8

    Prepare yourself, human. The ultimate battle is about to begin!\n
    """
    )

def ask_yes_no(question):
    """Ask a yes or no question."""
    response = None
    while response not in ("y", "n"):
        response = input(question).lower()
    return response

def ask_number(question, low, high):
    """Ask for a number within a range."""
    response = None
    while response not in range(low, high):
        response = int(input(question))
    return response

def pieces():
    """Determine if playor or computer goes first"""
    go_first = ask_yes_no("Do you require the first move? (y/n): ")
    if go_first == "y":
        print("\nThen take the first move. You will need it.")
        human = X
        computer = O
    else:
        print("\nYour bravery will be your undoing... I will go first.")
        computer = X
        human = O
    return computer, human

def new_board():
    """Create new game baord."""
    board = []
    for square in range(NUM_SQUARES):
        board.append(EMPTY)
    return board

def display_board(board):
    """Display game board on screen."""
    print("\n\t", board[0], "|", board[1], "|", board[2])
    print("\t", "---------")
    print("\t", board[3], "|", board[4], "|", board[5])
    print("\t", "---------")
    print("\t", board[6], "|", board[7], "|", board[8], "\n")

def legal_moves(board):
    """Creates a list of legal moves."""
    moves = []
    for square in range(NUM_SQUARES):
        if board[square] == EMPTY:
            moves.append(square)
    return moves

def winner(board):
    """Determine the game winner."""
    WAYS_TO_WIN = ((0, 1, 2),
                   (3, 4, 5),
                   (6, 7, 8),
                   (0, 3, 6),
                   (1, 4, 7),
                   (2, 5, 8),
                   (0, 4, 8),
                   (2, 4, 6))
    for row in WAYS_TO_WIN:
        if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
            winner = board[row[0]]
            return winner

    if EMPTY not in board:
        return TIE

    return None

def human_move(board, human):
    """Get human move."""
    legal = legal_moves(board)
    move = None
    while move not in legal:
        move = ask_number("Where will you move? (0 - 8):", 0, NUM_SQUARES)
        if move not in legal:
            print("\nThat square is already occipied, foolish hooman. Choose another.\n")
    print("Fine...")
    human_moves_so_far.append(move)
    return move

def computer_move(board, computer, human):
    "Make computer move."""
    #Make a copy to work with since function will be changing list
    board = board[:]
    #The best positions to have, in order
    BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7)

    print("I shall take square number", end=" ")

    #If computer can win, take that move
    for move in legal_moves(board):
        board[move] = computer
        if winner(board) == computer:
            print(move)
            return move
        #Done checking this move, undo it
        board[move] = EMPTY

    #If human can win, block that move
    for move in legal_moves(board):
        board[move] = human
        if winner(board) == human:
            print(move)
            return move
        #Done checking this move, undo it
        board[move] = EMPTY

    if human_moves_so_far == [0, 8] or [8, 0] or [6, 2] or [2, 6]:
        move = 7
        return move

    #Since no one can win on next move, pick best option square
    for move in BEST_MOVES:
        if move in legal_moves(board):
            print(move)
            return move

def next_turn(turn):
    """Switch turns."""
    if turn == X:
        return O
    else:
        return X

def congrat_winner(the_winner, computer, human):
    """Congratulate the winner."""
    if the_winner != TIE:
        print(the_winner, "won!\n")
    else:
        print("It's a tie\n")

    if the_winner == computer:
        print("As I predicted hooman, I am triumphant! \n" \
              "proof that silicon is superior to flesh in all regards.")

    elif the_winner == human:
        print("No, no! It cannot be! Somehow you tricked me, ape. \n" \
              "But never again, I, the computer, so swear it!")

    elif the_winner == TIE:
        print("You were most fortunate, hooman, and somehow managed to tie me. \n" \
              "Celebrate today... for this is the best you will ever achieve.")

def main():
    display_instruct()
    computer, human = pieces()
    turn = X
    board = new_board()
    display_board(board)

    while not winner(board):
        if turn == human:
            move = human_move(board, human)
            board[move] = human
        else:
            move = computer_move(board, computer, human)
            board[move] = computer
        display_board(board)
        turn = next_turn(turn)

    the_winner = winner(board)
    congrat_winner(the_winner, computer, human)

#Start the program
main()
input("\n\nPress the enter key to quit.")

具体来说,我创建了一个名为 "human_moves_so_far" 的列表(我认为)我可以用它来跟踪人类玩家的动作,如果他们输入计算机可以输入的四个特定动作序列之一不打败,计算机会暂时放弃正常的移动优先顺序并停止它们。

现在,经过进一步检查,我意识到这个解决方案可能不会导致无法获胜的游戏,但我来这里不是为了确定如何完成挑战,而是为了了解为什么计算机开始以这种方式运行确实如此。

看,在我尝试该解决方案之后,无论玩家做什么,计算机总是会在第一步走方格 7,我不知道它为什么开始这样做。就好像它完全忽略了 'if' 语句并简单地执行了代码。

现在我再看一遍,我想知道我是否错过了 'or' 声明;谁能告诉我这是否是问题所在,如果不是,那是什么问题?我认为了解我做错了什么对我的学习过程很重要,即使我最终找到了另一种方法。谢谢。

P.S:这是游戏的最终版本,据我所知,这是不可能的。以防万一有人好奇。

#Tic-Tac-Toe
#Plays a game of Tic-Tac-Toe against a human opponent

#Global constants
X = "X"
O = "O"
EMPTY = " "
TIE = "TIE"
NUM_SQUARES = 9
fatal_flaw = []

def display_instruct():
    """Diplsay game instructions."""
    print(
    """
    Welcome to the greatest inetellectual challenge of all time: Tic-Tac-Toe.
    This will be a showdown between your rudimentary human brain and my superior
    silicon processor.

    You will make your move by entering  a number, 0-8. The number will correspond
    to the board position as illustrated:

                    0 | 1 | 2
                    ---------
                    3 | 4 | 5
                    ---------
                    6 | 7 | 8

    Prepare yourself, human. The ultimate battle is about to begin!\n
    """
    )

def ask_yes_no(question):
    """Ask a yes or no question."""
    response = None
    while response not in ("y", "n"):
        response = input(question).lower()
    return response

def ask_number(question, low, high):
    """Ask for a number within a range."""
    response = None
    while response not in range(low, high):
        response = int(input(question))
    return response

def pieces():
    """Determine if playor or computer goes first"""
    go_first = ask_yes_no("Do you require the first move? (y/n): ")
    if go_first == "y":
        print("\nThen take the first move. You will need it.")
        human = X
        computer = O
    else:
        print("\nYour bravery will be your undoing... I will go first.")
        computer = X
        human = O
    return computer, human

def new_board():
    """Create new game baord."""
    board = []
    for square in range(NUM_SQUARES):
        board.append(EMPTY)
    return board

def display_board(board):
    """Display game board on screen."""
    print("\n\t", board[0], "|", board[1], "|", board[2])
    print("\t", "---------")
    print("\t", board[3], "|", board[4], "|", board[5])
    print("\t", "---------")
    print("\t", board[6], "|", board[7], "|", board[8], "\n")

def legal_moves(board):
    """Creates a list of legal moves."""
    moves = []
    for square in range(NUM_SQUARES):
        if board[square] == EMPTY:
            moves.append(square)
    return moves

def winner(board):
    """Determine the game winner."""
    WAYS_TO_WIN = ((0, 1, 2),
                   (3, 4, 5),
                   (6, 7, 8),
                   (0, 3, 6),
                   (1, 4, 7),
                   (2, 5, 8),
                   (0, 4, 8),
                   (2, 4, 6))
    for row in WAYS_TO_WIN:
        if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
            winner = board[row[0]]
            return winner

    if EMPTY not in the board:
        return TIE

    return None

def human_move(board, human):
    """Get human move."""
    legal = legal_moves(board)
    move = None
    while move not in legal:
        move = ask_number("Where will you move? (0 - 8):", 0, NUM_SQUARES)
        if move not in legal:
            print("\nThat square is already occipied, foolish hooman. Choose another.\n")
    print("Fine...")
    if move == 2:
        fatal_flaw.append("GAME")
    if move == 6:
        fatal_flaw.append("OVER")
    if move == 0:
        fatal_flaw.append("CHECK")
    if move == 8:
        fatal_flaw.append("MATE")
    return move

def computer_move(board, computer, human):
    "Make computer move."""
    #Make a copy to work with since function will be changing list
    board = board[:]
    #The best positions to have, in order
    if "GAME" in fatal_flaw and "OVER" in fatal_flaw or "CHECK" in fatal_flaw and "MATE" in fatal_flaw:
        BEST_MOVES = (7, 4, 0, 2, 6, 8, 1, 3, 5)
    else:
        BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7)

    print("I shall take square number", end=" ")

    #If computer can win, take that move
    for move in legal_moves(board):
        board[move] = computer
        if winner(board) == computer:
            print(move)
            return move
        #Done checking this move, undo it
        board[move] = EMPTY

    #If human can win, block that move
    for move in legal_moves(board):
        board[move] = human
        if winner(board) == human:
            print(move)
            return move
        #Done checking this move, undo it
        board[move] = EMPTY


    #Since no one can win on next move, pick best option square
    for move in BEST_MOVES:
        if move in legal_moves(board):
            print(move)
            return move

def next_turn(turn):
    """Switch turns."""
    if turn == X:
        return O
    else:
        return X

def congrat_winner(the_winner, computer, human):
    """Congratulate the winner."""
    if the_winner != TIE:
        print(the_winner, "won!\n")
    else:
        print("It's a tie\n")

    if the_winner == computer:
        print("As I predicted hooman, I am triumphant! \n" \
              "proof that silicon is superior to flesh in all regards.")

    elif the_winner == human:
        print("No, no! It cannot be! Somehow you tricked me, ape. \n" \
              "But never again, I, the computer, so swear it!")

    elif the_winner == TIE:
        print("You were most fortunate, hooman, and somehow managed to tie me. \n" \
              "Celebrate today... for this is the best you will ever achieve.")

def main():
    display_instruct()
    computer, human = pieces()
    turn = X
    board = new_board()
    display_board(board)

    while not winner(board):
        if turn == human:
            move = human_move(board, human)
            board[move] = human
        else:
            move = computer_move(board, computer, human)
            board[move] = computer
        display_board(board)
        turn = next_turn(turn)

    the_winner = winner(board)
    congrat_winner(the_winner, computer, human)

#Start the program
main()
input("\n\nPress the enter key to quit.")

您的代码总是执行 if 语句内容的原因是 Python 处理您的 or 语句的方式。

if human_moves_so_far == [0, 8] or [8, 0] or [6, 2] or [2, 6]:

对每个数字组合重复 or 不会将其与您的第一个语句 if human_moves_so_far == 相关联。

即使 human_moves_so_far == [0, 8] 解析为 Falseor [8, 0] 也总是解析为 True,因此 if 语句被激活。

换句话说,这一行应该是这样的:

if (human_moves_so_far == [0, 8]) or (human_moves_so_far == [8, 0]) or (human_moves_so_far == [6, 2]) or (human_moves_so_far == [2, 6]):

或者,您可以使用 in 语句编写代码,如果变量在给定列表中,则使 if 语句继续,如下所示:

if human_moves_so_far in [[0, 8],[8, 0],[6, 2],[2, 6]]: