簡體   English   中英

如果可能的話,你能讓我的代碼更干凈嗎?

[英]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")

另外,請注意,以這種方式循環仍然是無限的。 所以,如果你想讓游戲在某個時候結束,你可以,例如:

  • 引入一個計數器,該計數器跟蹤已執行了多少次循環迭代,然后使用 if 語句在計數器達到某個值后中斷循環;
  • 或引入另一個用戶輸入,例如是/否問題(如“繼續?”),然后如果玩家輸入“否”則打破循環。

我這樣做很開心:

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")

改進完成:

  • 用戶必須提供一個數字
  • 情況現在更清楚了
  • 比賽結束后繼續

你可以添加什么:

  • 添加評分系統
  • 提供有關玩家失敗原因的反饋
  • 在開始之前給出游戲規則
  • 為這個游戲創建一個 GUI
  • 讓玩家更改計算機選擇的最大值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM