我做了一个骰子游戏,您有3局,如果您不猜3局,它会显示数字并说您输了,但对我来说,只有在您没有4局时,它才会显示去。
import random
import time
guess=3
print ("Welcome to the dice game :) ")
print ("You have 3 guess's all together!")
time.sleep(1)
dice=random.randint(1, 6)
option=int(input("Enter a number between 1 and 6: "))
while option != dice and guess > 0:
option=int(input("Wrong try again you still have " + str(guess) + " chances remaining: "))
guess=guess-1
if guess == 0:
print ("You lost")
print ("The number was " + str(dice))
if option == dice:
print ("You win and got it with " + str(guess) + " guess remaining")
结果是:
Welcome to the dice game :)
You have 3 guess's all together!
Enter a number between 1 and 6: 4
Wrong try again you still have 3 chances remaining: 4
Wrong try again you still have 2 chances remaining: 4
Wrong try again you still have 1 chances remaining: 4
You lost
The number was 2
更简洁的写法是
import random
import time
guesses = 3
print("Welcome to the dice game :) ")
print("You have 3 guesses all together!")
time.sleep(1)
dice = random.randint(1, 6)
while guesses > 0:
option = int(input("Enter a number between 1 and 6: "))
guesses -= 1
if option == dice:
print(f"You win and got it with {guesses} guess(es) remaining")
break
if guesses > 0:
print("Wrong try again you still have {guesses} guess(es) remaining")
else:
print("You lost")
print(f"The number was {dice}")
循环条件仅跟踪剩余的猜测数。如果您猜对了,请使用显式break
退出循环。然后,仅当您不使用显式的else
时,才执行循环中的break
子句。
您通过以下行为用户提供了更多机会:option=int(input("Enter a number between 1 and 6: "))
。尝试改为声明guess=2
。
您的代码显然会(在循环之前)授予初始猜测,然后在循环内再授予三个猜测。如果您希望它是3个猜测,则只需将猜测计数器减少1。