Erik Rasmussen
Erik Rasmussen

Reputation: 95

How do I make a python program check for a value every time something happens?

I'm making a game in python, and it has a health system. Can I make the program check for changes in the game_state['health'] I have all the time without using if game_state['health'] = =< 0?

Upvotes: 1

Views: 498

Answers (1)

nzlinus
nzlinus

Reputation: 46

Definitely read up on some educational materials, tutorials, etc.

A basic approach might be something like the following:

class MyCharacter(object):
    """Simple Character Class"""

    def __init__(self, health):
        self._health = health

    @property
    def health(self):
        return self._health

    @health.setter
    def health(self, new_value):
        self._health = new_value
        if new_value <= 0:
            print "What's that strange white light...?"
            raise EndGameEvent("Character is dead... :(")

    def takes_damage(self, damage):
        print "Ouch... that really hurt!"
        self.health = self.health - damage

Your main game thread would receive the EndGameEvent and act on it appropriately. I guess this is still using your check, but you don't have to explicitly write a line of code every time you want to check the health status.

Upvotes: 2

Related Questions