簡體   English   中英

我應該在哪里為我的猜謎游戲放置 if function?

[英]Where should I put an if function for my Guessing game?

現在,我正在為絕對初學者編寫 Python 一書的第 3 章。

第 3 章末尾的挑戰之一是“修改猜我的號碼游戲,使玩家的猜測次數有限”,如果玩家未能獲得正確的猜測次數,則應顯示一條消息。

代碼如下所示:

# Guess My Number
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money

import random  

print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.\n")

# set the initial values
the_number = random.randint(1, 100)
guess = int(input("Take a guess: "))
tries = 1

# guessing loop
while guess != the_number:
    if guess > the_number:
        print("Lower...")
    else:
        print("Higher...")
            
    guess = int(input("Take a guess: "))
    tries += 1

print("You guessed it!  The number was", the_number)
print("And it only took you", tries, "tries!\n")
  
input("\n\nPress the enter key to exit.")

到目前為止,我需要添加一個變量來計算玩家擁有多少生命,該變量在開始時設置為一個數量,例如 10,並且應該使用 if 命令來確保當玩家用盡一生,顯示訊息。

但是,我不確定將 if 命令放在現有代碼中的什么位置。

好吧,如果我是你,我會制作一個游戲循環而不是猜測循環。 然后當我達到猜測極限時,我會打破游戲循環。 但是,如果你想保留你的代碼,你可以使用它。

while guess != the_number:
    if tries == 3: # Replace 3 with the limit you'd like to use
        print("You lost :(")
        exit()
    else:
        if guess > the_number:
            print("Lower...")
        else:
            print("Higher...")
        
    guess = int(input("Take a guess: "))
    tries += 1

同樣在你的情況下不要使用中斷,它仍然會導致最終打印獲勝的消息

(間距可能有點偏,所以你可能需要修復它)

在你說tries+=1之后,放一個 if 語句。 您的代碼應如下所示:

if tries>3:
    print("Game Over")
    break()
import random  

print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.\n")

# set the initial values
the_number = random.randint(1, 100)
guess = int(input("Take a guess: "))
tries = 1

while tries < 8:
    if guess == the_number:
        print("You guessed it!  The number was", the_number)
        print("And it only took you", tries, "tries!\n")
        break
    elif guess > the_number:
        print("Lower...")
    else:
        print("Higher...")
            
    guess = int(input("Take a guess: "))
    tries += 1

if tries == 8:
    print("You failed to guess my number")

input("\n\nPress the enter key to exit.")

你也可以這樣做

暫無
暫無

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

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