在 python 中,我當前的代碼可以作業到某個點。我有另一個被呼叫的函式check_X_win_status(),它與下面的函式做同樣的事情,除了它檢查 1,而不是 -1。任何人對如何使這個更緊湊有任何想法嗎?此外,我有時會收到一個錯誤,其中即使 game_status = -1, 1,-1, 0, 0, 0, 0, 0, 0 代碼也會列印“win”
game_status = [-1,-1,-1,0,0,0,0,0,0]
def check_O_win_status():
if game_status[0] and game_status[1] and game_status[2] == -1:
print("O wins!")
if game_status[3] and game_status[4] and game_status[5] == -1:
print("O wins!")
if game_status[6] and game_status[7] and game_status[8] == -1:
print("O wins!")
if game_status[0] and game_status[3] and game_status[6] == -1:
print("O wins!")
if game_status[1] and game_status[4] and game_status[7] == -1:
print("O wins!")
if game_status[2] and game_status[5] and game_status[8] == -1:
print("O wins!")
if game_status[0] and game_status[4] and game_status[8] == -1:
print("O wins!")
if game_status[2] and game_status[4] and game_status[6] == -1:
print("O wins!")
uj5u.com熱心網友回復:
您可以通過準備一個以索引元組表示的獲勝模式串列來稍微簡化一下。然后,對于每個模式,使用 all() 檢查在 game_status 中是否所有 3 個索引都為 -1:
def check_O_win_status():
winPatterns = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(0,4,8),(2,4,6)]
if any(all(game_status[i]==-1 for i in patrn) for patrn in winPatterns):
print("O wins")
在 Python 中,A and B and C == -1不測驗所有 3 個變數是否都等于 -1。它將使用前兩個變數作為布林值,提取它們的Truthy值,就像你已經完成了一樣(A == True) and (B == True) and (C==-1)。
為了測驗所有3個變數是-1,你可以表達這樣的條件:A == B == C == -1。
uj5u.com熱心網友回復:
首先,不會那樣作業,當它是時1 and -1 == -1會回傳,您需要檢查每個元素,即:truefalse1 == -1 and -1 == -1
其次,為什么要使用兩個函式,您可以通過函式傳遞一個引數然后進行比較。艾:
def check_win_status(num):
if game_status[0] == num and game_status[1] == num and game_status[2] == num:
elif game_status[3] == num and game_status[4] == num and game_status[5] == num:
#rest of your code here
另外使用 elif 來檢查下一個元素而不是 if,這將消除輸入觸發多個 if 并開始多次列印的情況,如上所示
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/388329.html
