[英]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.