无法执行的 Python 井字棋代码

63 阅读2分钟

一名 Python 学习者在编写一个简单的井字棋程序时遇到问题。他发现程序在让用户输入数字后就停止执行了,无法继续进行游戏。他尝试寻找错误,但一直没有找到解决办法。他希望得到帮助,以使他的程序能够正常运行。

huake_00257_.jpg

2、解决方案

  1. 首先,我们需要检查代码是否存在明显的错误。在这个例子中,我们发现 checkAll() 函数总是返回 True,这会导致程序在第一次检查时就结束游戏。这是因为在 checkAll() 函数中,所有 if 语句都只有一个 True 作为结果,而没有实际的逻辑来检查胜利条件。
  2. 其次,我们需要修改 checkAll() 函数,使其能够正确地检查胜利条件。我们可以使用 any() 函数来检查是否满足任何一个胜利条件。代码如下:
def checkAll():
    winning_combos = [[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 combo in winning_combos:
        if board[combo[0]] == board[combo[1]] == board[combo[2]] != " ":
            return True
    return False
  1. 最后,我们需要在 checkAll() 函数之前添加一个判断,以检查是否已经达到平局状态。如果已经达到平局状态,则游戏结束。代码如下:
if all(space != " " for space in board):
    print("The game is a tie!")
    break
  1. 修复了这些错误后,代码就可以正常运行了。以下是完整的代码:
import random

board = range(0, 9)

def print_board():
    print(board[0], "|", board[1], "|", board[2])
    print(board[3], "|", board[4], "|", board[5])
    print(board[6], "|", board[7], "|", board[8])

def checkAll():
    winning_combos = [[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 combo in winning_combos:
        if board[combo[0]] == board[combo[1]] == board[combo[2]] != " ":
            return True
    return False

print_board()

while True:
    input = int(input("Choose a number to place your X: "))

    if input <= 8:
        if board[input] != "x" or board[input] != "o":
            board[input] = "x"  # places x if board[input] is neither x or o

            # Check for winner

            if checkAll():
                print("The game is over!")
                break

            # Check for tie

            if all(space != " " for space in board):
                print("The game is a tie!")
                break

            # Computer's move

            finding = True
            while finding:
                random.seed()  # gives a random generator
                opponent = random.randrange(0, 8)  # generates a random integer between 1 and 8

                if board[opponent] != "x" or board[opponent] != "o":
                    board[opponent] = "o"

                    # Check for winner

                    if checkAll():
                        print("The game is over!")
                        break

                    finding = False

        else:
            print("This spot is taken.")
        print_board()

    else:
        print("Please choose a number between 0 and 8.")

现在,这段代码就可以正常运行了。用户可以输入数字来放置 X,计算机将自动放置 O,并且程序能够正确地检查胜利条件和平局状态。