[英]Can you make my code cleaner if possible?
如果可能的話,你能讓我的代碼更干凈嗎? 游戲的本質是讓玩家輸入一個大於電腦的數字。 但如果玩家的數字比計算機選擇的數字多 50,則玩家也輸了。
這是我的代碼:
from random import randint
#Variables
choice_ai = randint(0,1000)#AI selection
choice_p = int(input("Enter the number: "))#Player selection
choise_win = choice_ai + 50
print(choice_ai)
while True:
if choice_p == choice_ai:
print("You and the computer pick the same numbers")
elif choice_p <= choice_ai or choice_p >= choise_win:
print("You lose")
elif choice_p >= choice_ai and choice_p <= choise_win:
print("You won")
如果你使用上面的代碼,你會得到一個無限循環打印總是相同的結果,因為循環內部沒有任何變化並且在循環的每次迭代中滿足相同的條件。 如果你想讓游戲繼續下去,你應該重寫你的代碼如下:
from random import randint
while True:
choice_ai = randint(0,1000)#AI selection
choice_p = int(input("Enter the number: "))#Player selection
choise_win = choice_ai + 50
print(choice_ai)
if choice_p == choice_ai:
print("You and the computer pick the same numbers")
elif choice_p <= choice_ai or choice_p >= choise_win:
print("You lose")
elif choice_p >= choice_ai and choice_p <= choise_win:
print("You won")
另外,請注意,以這種方式循環仍然是無限的。 所以,如果你想讓游戲在某個時候結束,你可以,例如:
我這樣做很開心:
from random import randint
# Variables
INPUT_MESSAGE = "\nPlease, choose a number : "
OVER_PICK_VALUE = 50
while True:
while not (raw_input := input(INPUT_MESSAGE)).isdigit():
print(f"'{raw_input}' is not a number")
choice_p = int(raw_input)
choice_ai = randint(0, 1000)
print(f"The computer chose {choice_ai}.")
if choice_p == choice_ai:
print("You and the computer both chose the same value")
elif choice_ai < choice_p < choice_ai+OVER_PICK_VALUE:
print("You won")
else:
print("You lost")
改進完成:
你可以添加什么:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.