python - python - 如果已经给出提示,则转到其他未使用的随机提示
问题描述
我正在制作这个你猜数字的游戏,它会提示你这个数字是什么。我为提示系统制作了这个。
if str(userinp) == ('hint'):
g = randint(1,3)
if g == 1 and g1 == True:
print('The number',(hint_1),'than 50')
g1 = False
elif g == 2 and g2 == True:
print('The number',(hint_2))
g2 = False
elif g == 3 and g3 == True:
print('the number',(hint_3))
elif g == 4 and g4 == True:
print('WIP')
如果使用 选择了重复的提示,我将如何做到这一点g = randint(1,3)
,它将转到另一个未使用的提示?
谢谢 :) 。
解决方案
您的错误在于使用单独的变量作为提示。将它们放在一个列表中,以便您可以使用random.shuffle()
:
# at the start
hints = [
"The number {} than 50".format(hint_1)
"The number {}".format(hint_2)
"The number {}".format(hint_3)
]
random.shuffle(hints)
# in the game loop
if userinp == 'hint':
if not hints:
print("Sorry, you are out of hints")
else:
hint = hints.pop() # take **one** of the randomised hints
print(hint)
random.shuffle()
将hints
列表按随机顺序排列,重复hints.pop()
调用将以随机顺序选择下一个可用提示。
请注意,现在也不再需要保留单独的提示标志,当hints
列表为空时,用户没有提示。
== True
附带说明:在布尔测试中使用没有意义。if
已经测试了布尔值,添加== True
是多余的(当你必须测试一个布尔对象时,只有你会使用is True
asTrue
并且False
是单例)。
推荐阅读
- iis - IIS 反向代理配置
- postman - POSTMAN 无法处理端点内的反斜杠
- css - 去除 VS Code 中多余的颜色框
- php - 我应该如何使用 PHP 在 MongoDB 中通过 ObjectID 查找
- pandas - 如何在熊猫数据框中查找包含除 NaN 之外的所有唯一值的列名?
- bash - 我可以在 Bash 上递归创建文件吗?
- node.js - 无法从 lambda 中的 s3 读取文件并在主处理程序函数 nodejs 中使用它
- r - 求圆上一点的角度
- python - 在 Python 中使用 Selenium webdriver 基于文本搜索元素
- c - 如何使用 STM32 微控制器在 C 语言中选择要打开的随机 LED?