检查位置是否已被占用 Tic Tac Toe

Check if position has already been taken Tic Tac Toe

Board = [1,2,3,4,5,6,7,8,9]
print(Board[0], '|', Board[1], '|', Board[2])
print(Board[3], '|', Board[4], '|', Board[5])
print(Board[6], '|', Board[7], '|', Board[8])
Player_Input = int(input("Choose a number between 1-9: "))
while Board[Player_Input - 1] == Player_Input:
    Board[Player_Input - 1] = 'X'

所以这是在我的程序中运行的代码的一个简短示例。

while Board[Player_Input - 1] != Player_Input:
    Player_Input = int(input("Already taken. Choose another position: "))

我试过使用这 2 行来检查某个位置是否已被占用,但不知何故不起作用。我也试过用这个:

while Board[Player_Input - 1] == 'X' or Board[Player_Input - 1] == 'O':
    Player_Input = int(input("Already taken. Choose another position: "))

我认为主要问题是您试图使用 while 循环将 'X' 分配给他们选择的位置。 while 循环的目的不是对列表中某个特定的已知位置做某事;只要满足特定条件,它就会重复做某事。在您的情况下,您知道玩家选择了哪个 space(基于 Player_Input 的值),因此使用 while 循环不是正确的方法。 相反,只要检查选择的 space (Board[Player_Input - 1]) 是否还没有被占用,然后赋值。

类似于:

if Board[Player_Input - 1] != 'X' and Board[Player_Input - 1] != 'O':
   Board[Player_Input - 1] = 'X'  # assuming 'X' is the human player
else:
    # Handle the case where the space is full here.

编辑:

我想我现在可能明白你在循环中的目的了——你想要类似“重复直到他们做出有效选择”的东西。一种选择是将我上面写的代码包围起来:

while True: # Loop forever until we break out of it
    # Above code here
    if Board[Player_Input - 1] == 'X':
        break

编辑 2:

这也应该有效,并且可能更接近您的预期:

# Player chooses a space
Player_Input = int(input("Choose a number between 1-9: "))

# Available spaces should contain the space number, not 'X' or 'O'
# while choice not available: have player choose again
# (Should also add a check for if the input is not 1-9)
while Board[Player_Input - 1] != Player_Input:
    Player_Input = int(input("Already taken. Choose another position: "))

# Now that we know they made a valid choice, we fill in the players letter
Board[Player_Input - 1] = 'X'
Board = [1,2,3,4,5,6,7,8,9]
count = 0
Player_Input = int(input("Choose a number between 1-9: "))
if Player_Input < 10 and Player_Input >= 1:
    for player in range(9):
        if Board[Player_Input - 1] == 'X' or Board[Player_Input - 1] == 'O':
            print('you cant use this number')
        if count % 2 == 0:
            Board[Player_Input - 1] = 'X'
        else:
            Board[Player_Input - 1] = 'O'
        def show():
            print(Board[0], '|', Board[1], '|', Board[2])
            print(Board[3], '|', Board[4], '|', Board[5])
            print(Board[6], '|', Board[7], '|', Board[8])
        print(show())
        Player_Input = int(input("Already taken. Choose another position: "))
        count = count + 1