Reputation: 21204
I'm building a game as part of a tutorial on learning code.
The following class has a while loop that should return either 'finished' or, leave the loop and return 'death' (These are dict entries that run the game) but instead does not even seem to run. I'm looking at the while loop after def guess:
The loop is meant to ask the user to guess a number between 1 and three. If they guess wrong more than three times they "lose" and 'death' is returned, else 'finished'.
But, when I play the game I am not even prompted to enter a number, instead "Too many failed guesses, you lose!" is printed, even if guesses is 0.
class Smaug(Scene):
def enter(self):
print "Smaug is a terrifying huge fire breathing dragon, but you must get the Arkenstone from him for Thorin"
print "In Smaug's cave, the Lonely Mountain, Smaug notices your presence and challenges you to a game"
print "He says \"Guess a number between 1 and 3\""
smaugNum = random.randint(1, 3)
print "Smaugs number cheat:", smaugNum
guesses = 0
def guess():
while guesses < 4:
print "Guess a number between 1 and 3"
numb = raw_input("> ")
if numb == smaugNum:
print "Well done! You win."
Player.BilbosStuff.append('arkenstone')
print "Now Bilbo has", Player.BilbosStuff
return 'finished'
else:
print "You lose!"
guesses += 1
guess()
print "Too many failed guesses, you lose!"
return 'death'
Looking at the nesting of the code blocks, is it that when 'finished' is returned in the while loop, does it also, automatically, get returned as part of the wider class? Put another way, if numb == smaugNum then I need Smaug class to return finished.
Upvotes: 0
Views: 148
Reputation: 189317
You are defining guess
smack dab in the middle of enter
, but you are never calling it.
The blocks are like
class Smaug:
def enter:
#here's what to do when enter() is called
def guess:
#here's what to do when guess() is called
#here's some more stuff to do when enter() is called
Upvotes: 2
Reputation: 162
The problem here is that you are infinitely recursing down the guess function and never calling guess() in the first place.
After you increase your guesses counter you do not need to call guess() again as the execution will still be inside the while loop due to the number of guesses being less than 4, simply trust the while loop to do the comparison. Avoid calling guess() manually.
Upvotes: 1
Reputation: 11070
The problem is that you are not calling the guess()
function at all.. You have guess()
as a function and it is not called at all. so, the control directly jumps to the next line after the function. The best way is to remove the function and use the code like this:
guesses = 0
while guesses < 4:
print "Guess a number between 1 and 3"
numb = raw_input("> ")
if numb == smaugNum:
print "Well done! You win."
Player.BilbosStuff.append('arkenstone')
print "Now Bilbo has", Player.BilbosStuff
return 'finished'
else:
print "You lose!"
guesses += 1
print "Too many failed guesses, you lose!"
return 'death'
Upvotes: 3