我的tic-tac-toe Python游戏没有';当一名球员获胜时,比赛就结束了

我的tic-tac-toe Python游戏没有';当一名球员获胜时,比赛就结束了,python,tic-tac-toe,Python,Tic Tac Toe,你好。我目前正在读迈克尔·道森的《Python绝对初学者》一书。我有第六章的代码,当我运行代码并在棋盘上直接得到“X”时,它不会返回获胜者。程序将继续,直到所有空格都标记为“X”或“O”。这是我的密码: #!/usr/bin/python3 X = "X" O = "O" EMPTY = " " TIE = "TIE" NUM_SQUARES = 9 def display_instruct(): print( """ Welcome to th

你好。我目前正在读迈克尔·道森的《Python绝对初学者》一书。我有第六章的代码,当我运行代码并在棋盘上直接得到“X”时,它不会返回获胜者。程序将继续,直到所有空格都标记为“X”或“O”。这是我的密码:

#!/usr/bin/python3
X = "X"
O = "O"
EMPTY = " "
TIE = "TIE"
NUM_SQUARES = 9

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

          You will make your move known 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 your self, human. The ultimate battle is about to begin. \n
            """)

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

def ask_number(question, low, high):
    response = None
    while response not in range(low, high):
        response = int(input(question))
    return response

def pieces():
    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():
    board = []
    for square in range(NUM_SQUARES):
        board.append(EMPTY)
    return board

def display_board(board):
    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):
    moves = []
    for square in range(NUM_SQUARES):
        if board[square] == EMPTY:
            moves.append(square)
    return moves

def winner(board):
    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 occupied, foolish human. 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[:]
    BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7)
    print("I shall take square number")

    # if computer can win, take that move
    for move in legal_moves(board):
        board[move] = computer
        if winner(board) == computer:
            print(move)
            return move
        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 ca win on next move, pick best open square
    for move in BEST_MOVES:
        if move in legal_moves(board):
            print(move)
            return move

def next_turn(turn):
    if turn == X:
        return 0
    else:
        return X

def congrat_winner(the_winner, computer, human):
    if the_winner != TIE:
        print(the_winner, "won!\n")
    else:
        print("It's a tie!\n")
    if the_winner == computer:
        print("As I predicted, human, I am triumphant once more. \n" \
              "Proof that computers are superior to humans in all regards.\n")

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

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

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)

main()

input("Press enter to exit")

检查胜利或平局的功能不正确。目前您有:

def winner(board):
    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
请注意,
returnnone
在循环中,因此当第一行不匹配时,您将返回
None
。除非电路板已满,在这种情况下,您可以正确返回
TIE
,除非您可以在尝试匹配任何行之前检查电路板是否已满

我们可以通过重新定义
return None
使函数在循环后执行,从而使函数正确。此外,在循环之前移动
TIE
检查也是有意义的

def winner(board):
    if EMPTY not in board:
        return TIE

    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

    return None
让我们回顾一下这个函数的作用。我们首先检查是否有完整的电路板。然后我们继续思考如何取胜。如果它们都不匹配,则返回
none

代码中还有一个问题:

def next_turn(turn):
    if turn == X:
        return 0
    else:
        return X
为了使后面的测试
if turn==human:
在所有情况下都能正常工作,
turn
的值必须是
X
O
,而不是
X
0
。这是一个快速解决方案:

def next_turn(turn):
    if turn == X:
        return O
    else:
        return X

解决此问题的更好方法是避免使用名为
O

的变量。您还在
def(congrat\u winner)
中犯了缩进错误

正确的方法是:

    def congrat_winner(the_winner, computer, human):

        if the_winner != TIE:
            print(the_winner, "won!\n")
        else:
            print("It's a tie!\n")

        if the_winner == computer:
            print("As I predicted, human, I am triumphant once more. \n" \
                  "Proof that computers are superior to humans in all regards.\n")

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

        elif the_winner == TIE:
            print("You were most lucky, human, and somehow managed to tie me. \n" \
                  "Celebrate today... for this is the best you will ever achieve.\n")
此外,最后一个
elif
应替换为
else

    def congrat_winner(the_winner, computer, human):

        if the_winner != TIE:
            print(the_winner, "won!\n")
        else:
            print("It's a tie!\n")

        if the_winner == computer:
            print("As I predicted, human, I am triumphant once more. \n" \
                  "Proof that computers are superior to humans in all regards.\n")

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

        else:
            print("You were most lucky, human, and somehow managed to tie me. \n" \
                  "Celebrate today... for this is the best you will ever achieve.\n")

请理解,您已经有了答案,但有一条建议-尝试单独测试您的功能

在您的情况下,您已经预感到您的
winner
函数存在问题。我是直接从你的问题中得出这个结论的,你在问题中提到“赢家不会回来”

有很多方法可以进行测试,但是让我们保持简单,抓住这个函数,将它复制到一个新的python程序中,向它扔一些游戏板,看看会发生什么。我的意思是字面上的“看”——当涉及到测试时,你最好的朋友是
print
。假设我们这样修改您的函数:

def winner(board):
    print("winner function entered")
    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:
        print("for loop entered")
        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

这似乎太容易了,但我们立即注意到,在所有情况下,for循环只输入一次。有一小部分代码需要关注,很快就会发现缩进错误。

您好,先生!我不太相信这会解决您的问题,但您可以尝试更改行:if board[row[0]==board[row[1]]==board[row[2]!=空:至:如果线路板[第[0]行]==线路板[第[1]行]==线路板[第[2]行]和线路板[第[0]行]!=空的:谢谢你给我的所有答案。我非常感激。希望大家今天过得愉快。最后一个问题。关于回报,没有一种方式能让你赢。如果获胜者返回,它不会返回None,对吗?为什么?最后输入返回无。我的理解是,当“return winner”时,程序将继续执行,直到函数的最后一个语句“return None”。为什么“回报赢家”不会变成“回报赢家”。对不起我的英语。如果你不明白。我会再解释一遍。谢谢你的回答,先生。先生,我可以问几个问题吗?您是在哪里学会使用python编程的?我可以问一些关于python的技巧吗?特别是关于类和Tknter,我通过阅读该语言的发明者Guido van Rossum的著作来学习Python。它包括关于课程的材料。我是从学校学的。好的,谢谢。你还喜欢读什么书,或者那些对你帮助很大的书。谢谢我读过的关于Python的另一本书是。非常好。我推荐。谢谢你,先生。最后一个问题。关于回报,没有一种方式能让你赢。如果获胜者返回,它不会返回None,对吗?为什么?最后输入返回无。我的理解是,当“return winner”时,程序将继续执行,直到函数的最后一个语句“return None”。为什么“回报赢家”不会变成“回报赢家”。对不起我的英语。如果你不明白。我会再解释一遍。