0

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()
  • core - runs main function and game_over() in a While loop
  • main function runs the game
  • main calls event function
  • event function does something depending on conditions/circumstances (or nothing if none are met) -> the function calls the combat loop whenever the player writes 'battle'
  • quite a bunch of functions are used in the combat loop, but what the loop does is eventually check if the player's hp is greater than 0.

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?

1
  • You can't "break out of a function" - return is the only way. Commented Oct 20, 2015 at 16:30

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome! It helped and works like a charm! I guess it is not that difficult after all once you know how the Exceptions and raising classes works! Thanks!
you can also raise like this raise MyCustomException('message') then in the except you can except MyCustomException as error: print error.message and more docs.python.org/2/tutorial/errors.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.