Reputation:
Im making this game that you guess the number, and it gives you hints to what that number is. I made this for the hint system.
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')
How would I make it so if there was a duplicate hint was chosen with g = randint(1,3)
, it would go to another unused hint?
Thanks :) .
Upvotes: 2
Views: 69
Reputation: 1123780
Your mistake is in using separate variables for your hints. Put them in a list instead, so you can use 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()
puts the hints
list in random order, and repeated hints.pop()
calls will pick the next available hint, in random order.
Note that now there is no need to keep separate hint flags anymore either, when the hints
list is empty, the user is out of hints.
As a side note: there is no point in using == True
in boolean tests. if
already tests for boolean truth, adding == True
is redundant (and when you must test for a boolean object only you'd use is True
as True
and False
are singletons).
Upvotes: 6
Reputation: 882
You could put the hints in a list and then select a random entry in the list and then remove it from the list.
hints = ["Something warm", "Fuzzy", "Meows"]
if str(userinput) == "hint":
hintn = randint(0,len(hints)-1) # assuming the range of randint is inclusive
print(hints[hintn])
del hints[hintn]
Or as Martijn suggested in the comments, shuffle it once and then pop from it.
from random import shuffle
hints = ["Something warm", "Fuzzy", "Meows"]
shuffle(hints)
#...
if str(userinput) == "hint":
if not hints:
print("No hints remaining")
else:
print(hints.pop())
Upvotes: 2