Reputation: 91
Basically, I am making a text-based python game and have come across a block.
The player can enter a battle and as always, there is a chance you would die (hp is 0). What I want to do is to break the main loop of the game, which is several functions down the road, roughly 5-6 (from main to the combat system function), dispersed in different files.
The structure is as follows:
core()
while True:
main()
game_over()
What I want to do is that whenever the player's hp goes 0 (or even below), the main() function would be broken so that the player can then be prompted to either exit the game or run the main function once more. I would like this to happen differently from having to type return and a value after each function.
The game_over function prompts the player to type in "new" and start main() again as the function would simply not do anything, or "quit" and the function would call quit() and exit the game.
TL:DR - How can I break out of a function all the way from a smaller one? Trying to avoid an array of returns?
Upvotes: 0
Views: 556
Reputation: 33863
you can raise an exception
eg
def main():
if condition:
raise StopIteration
else:
return value
while True:
main()
for more complicated logic you can raise custom exceptions and catch them:
class GameOver(Exception):
pass
class Quit(Exception):
pass
def main():
if game_over:
raise GameOver
if quit:
raise Quit
else:
return value
while True:
try:
main()
except GameOver:
game_over()
except Quit:
break
Upvotes: 2