How do I change variables in this program for certain user choices/locations?

Viewed 63

Background

Recently I simplified a text-only game I was making:

Here is the code:

import time

#
# Declaration of classes -- game logic
#
class Action:
    def __init__(self, description, newLocation):
        self.description = description
        self.newLocation = newLocation

class Location:
    def __init__(self, name, description):
        self.name = name
        self.description = description
        self.actions = []
    
    def addAction(self, action):
        self.actions.append(action)
        
    def arrive(self):
        print("----------------------------------------")
        print('You arrived to: {}'.format(self.name))
        print(self.description)
        i = 0
        print("   (0. Exit game)")
        for action in self.actions:
            i = i + 1
            print("    {}. {}".format(i, action.description))
        validChoice = False
        while not validChoice:
            try:
                index = int(input("? : "))
                if index == 0:
                    print("Abandoning your quest... :(")
                    return
                if 0 < index and index <= len(self.actions):
                    validChoice = True
            except ValueError:
                pass
        self.actions[index - 1].newLocation.arrive() # indexing is 0-based, but we get 1-based index from the user
        
#
# Declare your locations here -- data
#initial rooms
house = Location("house", "Inside the house there is a sweet aroma of rolls being baked.")
field = Location("field", "Grass swishes as you walk through it. a solitary horse is grazing in the field.")
stable = Location("stable", "You are greeted by the sound of various animal noises and the smell of various animal odors")
#secondary rooms-house


#declare location actions here
spawnPosition = Location("Spawn position", "You wake up in a sunny morning. After you get out of your bad, you decide to:")
spawnPosition.addAction(Action("for house", house))
spawnPosition.addAction(Action("for field", field))
spawnPosition.addAction(Action("for stable", stable))
#house options
house.addAction(Action("leave the house",field))



#
# The game starts here
#
print ("Cool Cousins Studios Presents...")
time.sleep(2) # Sleep for 2 seconds
print ("With use of Python Code...")
time.sleep(2) # Sleep for 2 seconds
print ("Adventure In Saldica")
time.sleep(2) # Sleep for 2 seconds
print ("(cue dramatic music)")
time.sleep(3) # Sleep for 3 seconds

spawnPosition.arrive() # This is all you need to do to initiate the game. When this function returns, your journey has concluded.
print("Bye-bye")

However, I don't know how I can make it change variable values based on the options/locations the user chooses. I've tried putting if statements in the Location.arrive function, but I'm wondering if there is a simpler way.

What I need to know:

How do I make and edit variables based on my location, and what is the simplest way to do it?

1 Answers

You should define a class for your character, where you would store their current location and you can present choices based on the current location or history of actions that the character has taken. The Location class should contain the available actions you can make from that location and a function to present them when needed. This way, you will only need to define each room once.

import time

#
# Declaration of classes -- game logic
#

class Character:
    def __init__(self, name, location):
        self.name: str = name
        self.location: Location = location # initialize with some starting location
        self.actions = [] # Store all the actions this player has taken
        
        # Here we will have a never ending loop to get inputs from the user
        while True:
            newLocation = self.location.arrive()
            self.actions.append(newLocation)
            self.location = newLocation

            if sum([1 for loc in self.actions if loc == house]) >= 2:
                house.description = "Why are you back home? Go somewhere else."

            if self.location == exitLocation:
                break


        print("\n\nYou visited:")
        for i in self.actions:
            print(i.name)

class Location:
    def __init__(self, name, description, actions:list = []):
        self.name = name
        self.description = description
        self.actions = actions # this should be a list of locations that can be visited from here
        
    def arrive(self):
        print("----------------------------------------")
        print('You arrived to: {}'.format(self.name))
        print(self.description)
        i = 0
        print("   (0. Exit game)")
        for action in self.actions:
            i = i + 1
            print("    {}. for {}".format(i, action.name))
        validChoice = False
        while not validChoice:
            try:
                index = int(input("? : "))
                if index == 0:
                    validChoice = True
                    print("Abandoning your quest... :(")
                    return exitLocation
                if 0 < index and index <= len(self.actions):
                    validChoice = True
                    return self.actions[index - 1] # indexing is 0-based, but we get 1-based index from the user
            except ValueError:
                pass
        
#
# Declare your locations here -- data
#initial rooms
field = Location("field", "Grass swishes as you walk through it. a solitary horse is grazing in the field.")
stable = Location("stable", "You are greeted by the sound of various animal noises and the smell of various animal odors")
house = Location("house", "Inside the house there is a sweet aroma of rolls being baked.")

spawnPosition = Location("Spawn position", "You wake up in a sunny morning. After you get out of your bed, you decide to:", [field, stable, house])

exitLocation = Location("Exit Game", "Bye-bye")

#secondary rooms-house

# Declare location actions here
field.actions = [stable, house, spawnPosition]
stable.actions = [field, house, spawnPosition]
house.actions = [field, stable, spawnPosition]

#
# The game starts here
#
print ("Cool Cousins Studios Presents...")
time.sleep(2) # Sleep for 2 seconds
print ("With use of Python Code...")
time.sleep(2) # Sleep for 2 seconds
print ("Adventure In Saldica")
time.sleep(2) # Sleep for 2 seconds
print ("(cue dramatic music)")
time.sleep(3) # Sleep for 3 seconds

# Create a character and initialize with spawn position
character = Character("John", spawnPosition) # This is all you need to do to initiate the game. When this function returns, your journey has concluded.
print("----------------------------------------")

print("Bye-bye")

If you want to change the description of the room based on events that have occurred, you can read self.actions within the character object and modify the descriptions of the rooms there. Same goes for changing the available actions from a room. You would simply modify house.actions in that while loop, if you want to change which rooms you can visit from there after the user has completed some set of actions.

Related