I am working on a text based game for my class. Its not required, but I want to have a health system. I'm trying global health, but I keep getting an error. I want to make it so you have a base health of 100. After the battle it will stay at the damaged health And you can use potions to restore it, and also view it by entering health. how would I go about doing that?
you need to open the attached file to work the code and save it as .py. Its imported in to the code.

#brooke Wilkison
#Project 1.2 move from room to room

import text_game
import random

villageVisit = 0

class GamePlayer(text_game.Player):
    """A main character that can be in a location with controlled movements and actions."""
    def __init__(self, location,
                 winning_location,
                 need_rope,
                 fight1,
                 restart
                 ):
        #where player starts the game
        self.location = location
        self.inventory = text_game.Container()

        #winning room where we can check to see if they made it.
        self.winning_location = winning_location
        #we need the rope to get into the sewers
        self.need_rope = need_rope
        #add fighting
        self.fight1 = fight1
        self.restart = restart
        
    def move(self, direction):
        new_location = self.location.leads_to(direction)
        if new_location:
            if new_location == self.need_rope:
                #check to see if the item is in your inventory
                #or already in room:
                flag = 0
                #if the rope is dropped in teh new location
                if "rope" in new_location.contents:
                    flag = 1
                #if you have the rope
                if "rope" in self.inventory:
                    flag = 2
                #if you have what you need move on.
                if flag == 1:
                    self.location = new_location
                    print "You enter:", new_location
                elif flag == 2:
                    self.location = new_location
                    print "You throw the rope down the hole"
                    print "so you can climb into the sewers."
                    print "You climb down."
                    print "You enter:", new_location
                else:
                    print "There's no way to get down there.",

            else:
                self.location = new_location
                print "You enter:", new_location
        else:
            print "You can't go that way."
            #winning location
        if self.location == self.winning_location:
            if "shiny_stone" in self.inventory:
                print """ You see the gem hill meant for the lost stone. The village is safe.
                """
                print "Type EXIT... if you dare."

        if self.location == self.fight1:
            global health
            health = 100

            global villageVisit
            villageVisit += 1
            print "VillageVisit :", villageVisit
            if villageVisit >= 2:
                 print "A dragon flys above the village."
            if villageVisit == 3:
                print "It lands in front of you."
            if villageVisit == 3:
                eHealth = 100
                print "Fight the Dragon"
                while health > 0 and eHealth > 0:
                    damage = random.randrange(10)
                    eDamage = random.randrange(8)
                    eHealth -= damage
                    health -= eDamage
                    print "After a terrible battle the statistics are:"
                    print "Dragon health:",eHealth
                    print "Your health:",health
                    #raw_input("Press enter to continue the battle: ")
                    pause()
                    
                if health > eHealth:
                    print "You won! The village is safe for now."

                else:
                    print "Game over"
                    raw_input = ("Press any key to restart.")
                    villageVisit = 0
                    self.location = self.restart
                    print "You are back in the strange house...", self.restart
def pause():
    raw_input("Press enter key to continue")

class Game(text_game.GamePlay):
    """ My adventure game """
    def __init__(self):
        #Define each location
        strange_house = text_game.Location("Strange House", "This house is neat and tidy. Very small, and not much to it. You look to your right and see a door to the outside.")
        village = text_game.Location("Village", "You see all sorts of different people looking around. They don't even look human. There are a few houses and a trail that leads off. There is a man who keeps looking at you.")
        house = text_game.Location("A House","Anotehr small house. This one is quite messy like the other. There is a door leading south and the exit north.")
        cellar = text_game.Location("Cellar","Dark and damp. Its kinda hard to see down there. Stone walls add to the creepy effect.")
        item_shop = text_game.Location("Store","You see many weapons and shields displayed. A person is sitting at the counter.")
        upstairs = text_game.Location("Upstairs","You see a bed and a dresser. Not much to it, but it looks nice.")
        leader_house = text_game.Location("Village leaders house","This is the biggest house you've seen thus far. A fire is going, keeping the house toasty.")
        sewers = text_game.Location("Sewers","A ladder leads you to the sewers. The smell is wretched. With barley any room to walk, unless one wants to walk in flith. Rats run around.")
        desert = text_game.Location("Desert","Nothing like you've seen in movies. There's some grass, and a few trees. Its hot but not unbearable.")
        pond = text_game.Location("Pond","A small pond found in teh desert. The water is refreashing.")
        trail = text_game.Location("Trail","A trail leading to who knows where. Its nice and shaded by various trees. Ans you can hear nature all around. Its peacful.")
        woods = text_game.Location("Woods","Many trees now surround you, Be careful not to lose your way or run into something dangerous.")
        abandoned_house = text_game.Location("Adandoned House","Wooden panels on the house are broken, its missing pillars. What a dump. Furniture is all over the place, and many broken things. what happened?")
        river = text_game.Location("River","A small river runs. A beautiful waterfall can be seen.")
        flower_field = text_game.Location("Flower Field","Bundles of flowers around you. A very nice scene.")
                                    
        #Add exits to each room
        strange_house.add_exit(text_game.Location.SOUTH, village)

        village.add_exit(text_game.Location.NORTH_EAST, trail)
        village.add_exit(text_game.Location.NORTH_WEST, strange_house)
        village.add_exit(text_game.Location.SOUTH, house)
        village.add_exit(text_game.Location.EAST, item_shop)
        village.add_exit(text_game.Location.WEST, leader_house)
        
        house.add_exit(text_game.Location.NORTH, village)
        house.add_exit(text_game.Location.SOUTH, cellar)

        cellar.add_exit(text_game.Location.NORTH, house)
        
        item_shop.add_exit(text_game.Location.NORTH, upstairs)
        item_shop.add_exit(text_game.Location.WEST, village)

        upstairs.add_exit(text_game.Location.SOUTH, item_shop)
        
        leader_house.add_exit(text_game.Location.EAST, village)
        leader_house.add_exit(text_game.Location.SOUTH, sewers)

        sewers.add_exit(text_game.Location.NORTH, leader_house)
        sewers.add_exit(text_game.Location.EAST, desert)

        desert.add_exit(text_game.Location.SOUTH, pond)
        desert.add_exit(text_game.Location.WEST, sewers)

        pond.add_exit(text_game.Location.NORTH, desert)
        
        trail.add_exit(text_game.Location.SOUTH, village)
        trail.add_exit(text_game.Location.EAST, woods)

        woods.add_exit(text_game.Location.NORTH, flower_field)
        woods.add_exit(text_game.Location.SOUTH, abandoned_house)
        woods.add_exit(text_game.Location.EAST, river)
        woods.add_exit(text_game.Location.WEST, trail)

        abandoned_house.add_exit(text_game.Location.NORTH_WEST, woods)
        abandoned_house.add_exit(text_game.Location.NORTH_EAST, river)

        river.add_exit(text_game.Location.WEST, woods)
        river.add_exit(text_game.Location.SOUTH, abandoned_house)
        river.add_exit(text_game.Location.NORTH, flower_field)

        flower_field.add_exit(text_game.Location.SOUTH_EAST, river)
        flower_field.add_exit(text_game.Location.SOUTH_WEST, woods)
        
        #add a list of possible locations to list
        self.locations = []
        self.locations.append(strange_house)
        self.locations.append(village)
        self.locations.append(house)
        self.locations.append(cellar)
        self.locations.append(item_shop)
        self.locations.append(upstairs)
        self.locations.append(leader_house)
        self.locations.append(sewers)
        self.locations.append(desert)
        self.locations.append(pond)
        self.locations.append(trail)
        self.locations.append(woods)
        self.locations.append(abandoned_house)
        self.locations.append(river)
        self.locations.append(flower_field)

    #define objects
        #define each item
        money = text_game.Entity("money","5 dollars sits upon the dresser.")
        rope = text_game.Entity("rope","a pile of tangles rope is in the corner. What could this be used for?")

        shiny_stone = text_game.Entity("shiny_stone","A brilliant looking stone. It looks like it could be worth some money.")

        apron = text_game.Entity("apron","used for cooking.")
        doll = text_game.Entity("doll","Probably some little girls toy")
        glasses = text_game.Entity("glasses","A bulky pair of glasses sit upon the end table.")

        money_house = text_game.Entity("money","There's a stash of money in this pot. It contairs 15 dollars.")

        key = text_game.Entity("key","A silver key sits next to the bed. It looks very old.")

        torn_gloves = text_game.Entity("torn_gloves","They're in bad condition, but they'll work for now.")

        dog_food = text_game.Entity("dog_food","a bag of food. Not much, but enough for a few meals.")

        desert_flower = text_game.Entity("desert_flower","One beautiful flower sits in this almost wasteland.")
        rocks = text_game.Entity("desert_rocks","Dusty rocks. What's the point of these?")

        bottle_of_water = text_game.Entity("bottle_of_water", "THis is refreashing.")

        twigs = text_game.Entity("twigs","These could make a nice fire.")

        cheap_ring = text_game.Entity("cheap_ring","A cheap looking ring sits upon the floor.")
        wallet = text_game.Entity("wallet","Someones wallet. There could be something good inside..")

        ladybug = text_game.Entity("ladybug","Many ladybug's are flying around.")
        flower_circlet = text_game.Entity("flower_circlet","A lovely looking flower circlet sits upoun the flowers.")

        
        #assign rooms
    
        strange_house.contents.add_item(money)
        strange_house.contents.add_item(rope)

        village.contents.add_item(shiny_stone)

        house.contents.add_item(apron)
        house.contents.add_item(doll)
        house.contents.add_item(glasses)

        cellar.contents.add_item(dog_food)

        desert.contents.add_item(desert_flower)
        desert.contents.add_item(rocks)

        pond.contents.add_item(bottle_of_water)

        woods.contents.add_item(twigs)

        abandoned_house.contents.add_item(wallet)
        abandoned_house.contents.add_item(cheap_ring)

        flower_field.contents.add_item(ladybug)
        flower_field.contents.add_item(flower_circlet)

        item_shop.contents.add_item(torn_gloves)

        upstairs.contents.add_item(key)

        leader_house.contents.add_item(money_house)

        sewers.contents.add_item(shiny_stone)
        
     
        # Put the player in the first room to start
        self.player = GamePlayer(strange_house, desert, sewers, village, strange_house)
        


def prolog():
    print """
****************************************************************************
Set the stage for your game.
Answer this question:  "How did the player find themselves where they are?
*****************************************************************************
    """

def to_win():
    print """
The object of the game is to ...

HINT:  Any hints would be helpful.

    """
    
def main():
    prolog()
    to_win()
    adv = Game()
    adv.play("Enter the name of your game here.")
       
main()
raw_input("Press any key to exit")
Attachments
# Simple Adventure
# The beginnings of a text adventure game
# Modified by Paul Sbraccia from work initially developed by M.Dawson

class Entity(object):
    """ Base from which all others game objects are derived """ 
    def __init__(self, name, desc = None):
        self.name = name
        self.desc = desc
        

    def __str__(self):
        rep = self.name.upper()
        if self.desc:
            rep += " - " + self.desc
        return rep
    
class Container(dict):
    """ Object that can contain Entity objects. """
    def __str__(self):
        if len(self) == 0:
            rep = "Nothing"
        else:
            rep = ""
            for item_name in self:
                rep += item_name.upper() + "\n"
        return rep

    def add_item(self, item):
        self[item.name] = item
    def health(self):
        self.health = 100

    def remove_item(self, item):
        del self[item.name]

    def name_to_item(self, item_name):
        return self.get(item_name)

class Location(Entity):
    """ A place where the player can be """
    NORTH = "n"
    SOUTH = "s"
    EAST = "e"
    WEST = "w"
    SOUTH_EAST = "se"
    SOUTH_WEST = "sw"
    NORTH_EAST = "ne"
    NORTH_WEST = "nw"
    DIRECTIONS = (NORTH, SOUTH, EAST, WEST, NORTH_EAST, NORTH_WEST, SOUTH_EAST, SOUTH_WEST)
    
    def __init__(self, name, desc = None):
        super(Location, self).__init__(name, desc)
        self.exits = {}
        self.contents = Container()
        
        
    def __str__(self):
        rep = super(Location, self).__str__()
        rep += "\nAvailable exits: " + str(self.exits.keys())
        rep += "\nIt contains:\n"
        rep += str(self.contents)
        return rep
 
    def add_exit(self, direction, location):
        self.exits[direction] = location

    def leads_to(self, direction):
        return self.exits.get(direction)

class Player(object):
    """ A main character that can be in a location """
    def __init__(self, location):
        self.location = location
        self.inventory = Container()

    def display_inventory(self):
        print "You carry:\n", self.inventory

    def health(self):
        print "your health:\n", self.health

    def look(self, item_name):
        item = self.inventory.name_to_item(item_name) or \
               self.location.contents.name_to_item(item_name)
        if item:
            print "You see:\n", item
        else:
            print "You don't see anything like that here."

    def look_location(self):
        print "You're in:\n", self.location
        
    def move(self, direction):
        new_location = self.location.leads_to(direction)
        if new_location:
             self.location = new_location
             print "You enter:", new_location
        else:
            print "You can't go that way."

    def get(self, item_name):
        item = self.location.contents.name_to_item(item_name)
        if item:
            print "You get it."
            self.inventory.add_item(item)
            self.location.contents.remove_item(item)
        else:
            print "That's not something you can get."
    def drop(self, item_name):
        item = self.inventory.name_to_item(item_name) 
        if item:
            print "You drop it."
            self.location.contents.add_item(item)            
            self.inventory.remove_item(item)
        else:
            print "That's not something you can drop."

    def sell(self):
        print "Sell not implemented"
        
    def buy(self):
        print "buy not implemented"
        
class GamePlay(object):
          
    def play(self,opening_message = "Welcome to my Text Adventure Game"):
         
        print opening_message
        self.help()
       
        self.player.look_location()
        
        while True:
            command = raw_input("\n>")
            verb, noun = self.parse(command)
            
            if verb == "exit":
                break

            elif verb == "look":
                if noun:
                    self.player.look(noun)        
                else:
                    self.player.look_location()

            elif verb == "inventory":
                self.player.display_inventory()
                
            elif verb == "get":
                self.player.get(noun)

            elif verb == "take":
                self.player.get(noun)
                
            elif verb == "drop":
                self.player.drop(noun)

            elif verb in Location.DIRECTIONS:
                self.player.move(verb)

            elif verb == "help":
                self.help()

            elif verb == "health":
                self.health
                
            #New actions    
            elif verb == "sell":
                self.player.sell()
            elif verb == "buy":
                self.player.buy()
            else:
                print "I don't understand", verb

    def help(self):
        print "Use the following commands in you adventure:"
        print "'n' - to move north"
        print "'s' - to move south"
        print "'e' - to move east"
        print "'w' - to move west"
        print "'ne' - to move north east"
        print "'nw' - to move north west"
        print "'se' - to move south east"
        print "'sw' - to move south west"
        print "'look' - to view your surroundings"
        print "'look' object - to look at a particular object, i.e. 'look key'"
        print "'get' object - to get an object, i.e. 'get key'"
        print "'drop' object - to drop an object, i.e. 'drop key'"
        print "'inventory' - to list what you carry"
        print "'health' - to view your current health."
        print "'sell' - Sell stuff"
        print "'buy' - Buy stuff"
        print "'exit' - to end your adventure"
        print "'help' - to see this text\n"
        print

    def parse(self, command):
        command = command.strip()       # get rid of leading/trailing whitespace
        command = command.lower()       # make lowercase
        words = command.split()         # split into a list of words
        if len(words) == 0:
            return "",""
        elif len(words) == 1:
            return words[0], ""
        else:
            return words[0], words[1]

if __name__ == "__main__":
    print "This is a Module with classes for text based games."
    raw_input("\n\nPress the enter key to exit.")

So this is still a wip. The dragon is a practice battle. And I still have to enter required items to go certain places, and the story in.

The health variable would be the same as the location and inventory variables. Using a class makes this simple. Instead of "money", "rope", "shiny_stone", etc. I would suggest using a dictionary.

vars_dict = ["money":[0, "5 dollars sits upon the dresser."],
        "rope":[0, "a pile of tangles rope is in the corner."],
        "shiny_stone",[0, "A brilliant looking stone. It looks like it could be worth some money."]}
        for var in vars_dict:
            print var, vars_dict[var][0], vars_dict[var][1]
            vars_dict[var][0] = text_game.Entity(var, vars_dict[var][1])
            print var, vars_dict[var][0], vars_dict[var][1], "\n"

Edited 5 Years Ago by woooee: n/a

The health variable would be the same as the location and inventory variables. Using a class makes this simple. Instead of "money", "rope", "shiny_stone", etc. I would suggest using a dictionary.

vars_dict = ["money":[0, "5 dollars sits upon the dresser."],
        "rope":[0, "a pile of tangles rope is in the corner."],
        "shiny_stone",[0, "A brilliant looking stone. It looks like it could be worth some money."]}
        for var in vars_dict:
            print var, vars_dict[var][0], vars_dict[var][1]
            vars_dict[var][0] = text_game.Entity(var, vars_dict[var][1])
            print var, vars_dict[var][0], vars_dict[var][1], "\n"

I haven't done anything like that before. o.O

This article has been dead for over six months. Start a new discussion instead.