首页 > 解决方案 > Python TikTakToe 游戏 if 语句无法正常工作

问题描述

所以我正在写一个python tiktaktoe游戏作为一个项目。我需要使用多维数组并且没有错误。在函数 p_turn()(管理玩家移动)中,我将实现一个 if 语句来检查移动是否有效(在 1 和 3 之间)。但是现在,无论我输入什么数字,它仍然说移动无效。

期望的结果是游戏不允许不在 1 和 3 之间的数字。

def p_turn():
    system(command='cls')
    print_board()
    p_play_1 = int(input("Choose a position for the Y between 1 and 3 -->  "))
    p_play_2 = int(input("Choose a position for the X between 1 and 3 -->  "))
    if p_play_1 != 1 or p_play_1 != 2 or p_play_1 != 3 or p_play_2 != 1 or p_play_2 != 2 or p_play_2 != 3: # This is whats not working correctly
        print("This is not a valid move. The values must be betweeen 1 and 3! ")
        time.sleep(3)
        p_turn()
    if board[p_play_1 - 1][p_play_2 -1] == " ":
        board[p_play_1 - 1][p_play_2 - 1] = "X"
        system(command='cls')
        print_board()
        c_turn() # Computer play
    elif board[p_play_1 - 1][p_play_2 - 1] == "X" or [p_play_1 - 1][p_play_2 - 1] == "O":
        print("Someone already went there! ")
        time.sleep(3)
        p_turn()

另外,如果它很重要,这就是我存储电路板的方式。


board = [[" ", " ", " "],
         [" ", " ", " "],
         [" ", " ", " "]]

def print_board():
    print()
    print(f"{board[0][0]} | {board[0][1]} | {board[0][2]}")
    print("---------")
    print(f"{board[1][0]} | {board[1][1]} | {board[1][2]}")
    print("---------")
    print(f"{board[2][0]} | {board[2][1]} | {board[2][2]}")
    print()

标签: python

解决方案


你可以尝试这样的事情:

while not 1 <= (p_play_1 := int(input("Choose a position for the Y between 1 and 3 -->  "))) <= 3:
    print(f"Invalid Y position: {p_play_1}")

while not 1 <= (p_play_2 := int(input("Choose a position for the X between 1 and 3 -->  "))) <= 3:
    print(f"Invalid X position: {p_play_2}")

推荐阅读