gpt4 book ai didi

带“尝试”选项的 Python 猜谜游戏

转载 作者:行者123 更新时间:2023-12-01 06:26:49 24 4
gpt4 key购买 nike

我正在开发一个 Python 猜谜游戏,以了解 Python 的工作原理。

我想添加一个选项来计算猜测次数,但如果玩家多次给出相同的答案,我想将其计为 1 次尝试。

我不知道如何继续。任何帮助将不胜感激:)

这是我当前的脚本

# The Guess Game   

# secret number between 1 and 10
import random
randomNumber = random.randrange(1,10)
#print randomNumber #check if it's working
tries = 0

# rules
print('Hello and welcome to the guess game !')
print('The number is between 1 and 10')

guessed = False
tries += 1

while guessed==False:

userInput = int(input("Please enter your guess: "))

if userInput==randomNumber:
guessed = True
tries = str(tries)
print("Congratulations ! You win after " + tries + " tries ! ")

elif userInput>10:
print("The guess range is between 1 and 10, please try again")
tries = tries + 1

elif userInput<1:
print("The guess range is between 1 and 10, please try again")
tries = tries + 1

elif userInput>randomNumber:
print("Your guess is too large")
tries = tries + 1

elif userInput < randomNumber:
print("Your guess is too small")
tries = tries + 1

print("End of the game, please play again")

最佳答案

首先要做的事情。您声称该数字介于 1 到 100 之间,但只选择了 1 到 10 之间的数字。

更改randomNumber = random.randrange(1,10)randomNumber = random.randrange(1, 100)

在验证用户输入时,您还会检查数字是否大于 10 而不是 100。更改elif userInput>10elif userInput > 100 .

现在,正如其他人提到的,为了跟踪猜测,您可以使用 set 。集合是一种数据结构(基本上是一种存储信息的方式),它只允许添加到其中的每个不同项目的单个副本。

使用一组,您可以轻松检查数字是否已被猜出,如下所示:

guess = int(input())
if guess not in guesses:
guesses.add(guess)

最后,您可以在读完猜测后立即添加 1,而不是在每个 if 中的尝试中添加 1。您还可以合并您的elif userInput > 100elif userInput < 1在一起,因为它们打印相同的东西。

完整代码:

# The Guess Game   

# secret number between 1 and 100
import random
randomNumber = random.randrange(1, 100) # changed from 10 to 100
#print randomNumber #check if it's working

# rules
print('Hello and welcome to the guess game !')
print('The number is between 1 and 100')

guesses = set() # your set of guesses
guessed = False
tries = 0 # no need add 1 to the tries here

while guessed == False:

userInput = int(input("Please enter your guess: "))

if userInput not in guesses: # if it's not in our set
tries += 1 # increase the tries
guesses.add(userInput) # add it to our set

if userInput == randomNumber:
guessed = True
tries = str(tries)
print("Congratulations ! You win after " + tries + " tries ! ")

elif userInput > 100 or userInput < 1:
print("The guess range is between 1 and 100, please try again")

elif userInput > randomNumber:
print("Your guess is too large")

elif userInput < randomNumber:
print("Your guess is too small")

print("End of the game, please play again")

额外:始终确保您的用户向您提供您期望的输入。看看当你运行这个程序并且用户输入“asdfg”时会发生什么。提示:查看 python 异常。

关于带“尝试”选项的 Python 猜谜游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60098987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com