首页 > 解决方案 > 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),它将转到另一个未使用的提示?

谢谢 :) 。

标签: python

解决方案


您的错误在于使用单独的变量作为提示。将它们放在一个列表中,以便您可以使用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 TrueasTrue并且False是单例)。


推荐阅读