[英]Python TikTakToe game if statement not working properly
所以我正在写一个 python tiktaktoe 游戏作为一个项目。 我需要使用多维 arrays 并且没有错误。 在 function 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()
你可以尝试这样的事情:
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}")
将p_turn
重命名为player_turn
。 这样你就可以赋予你的 function 更多的意义。 这同样适用于c_turn
- cumputer_turn
要清楚得多。 在你的小例子中,它并没有太大的区别,但在更大的项目中,命名真的很重要!
p_play_1
和p_play_2
被简单地命名为x
和y
会更有意义。
您的边界检查本质上是:
if x != 1 or x != 2 or x != 3 or # ... repeat for y
那是行不通的。 上述if
条件从左到右进行评估,并在某些内容为True
时立即终止。 以x = 2
为例(这是一个有效的坐标)。 x != 1
计算结果为True
并且您的移动被视为无效。
Python中有很多方法可以检查变量是否在一定范围内。
使用比较运算符:
if lower_bound <= value <= upper_bound:
# value is between lower and upper bound
使用range()
:
if value in range(lower_bound, upper_bound + 1):
# value is between lower and upper bound
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.