1

So I've been playing around in Python and using __init__ etc.

Now I was wondering if you could do something else that would execute a piece of code (basically jump to that part of code) when triggered.

Easiest way to make it clear I think is like when a player in a game dies, he should just die and not get any more chances of having a turn or whatever.

I know this can be done in other ways, but the point is this may not always be nice.

I was thinking of something like (note: this is completely made up):

__as-soon-as__ PlayerHealth < 1: ## End what you are doing and do this when PlayerHealth is less than 1##
    print('Game Over')

So the real question is: Does anything like this exist?

LuukV
  • 203
  • 1
  • 11
  • You can `break` from `for` or `while` loops, `return` early from functions, `raise` and catch an error - there are plenty of options. – jonrsharpe May 13 '14 at 14:47
  • This would totally depend on what `PlayerHealth` is and how it is updated. Generally, implement this logic with a simple `if` statement in the code where `PlayerHealth` is changed. – Lev Levitsky May 13 '14 at 14:48
  • You could implement this by making PlayerHealth a property of a Player object, then registering callbacks on the setter, one of which would be a method that checks if the player is dead and prints "Game Over" if so. However, generally, something like this would be handled outside the object itself (division of responsibility; the game knows about the player, the player doesn't know about the game) in a game loop. This may really be an XY problem, in that case. Can you show more code, or describe more of the structure of your program? – Silas Ray May 13 '14 at 15:04

1 Answers1

0

One way to do this is using events in python.

There are several event frameworks that you could use PyDispatcher or similar frameworks like the ones mentioned in florisla's answer

But to keep this lightweight a simpler choice would be to use the event/signal dispatcher recipe from ActiveState. This will enable you to send simple events when the conditions you need are met.

Community
  • 1
  • 1
drapal
  • 1
  • 2