Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How do I add items (variables) to this game for certain game choices?

+4 votes
asked Jan 31, 2021 by Jeff The Chicken (2,920 points)

Recently Somebody helped me to simplify a text-only game I was making, but I don't know how I can make it change variable values based on the options the user chooses:

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")

2 Answers

+1 vote
answered Feb 1, 2021 by Peter Minarik (84,720 points)
selected Feb 1, 2021 by Jeff The Chicken
 
Best answer

3. Use Inheritance

You can use a base class to do your generic work and you can derive from this class to make different code to run for specific locations.

Read about inheritance here.

import time

class States:
    def __init__(self):
        self.stepsTaken = 0

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 handleChoices(self, choice, states):
        #
        # Do generic things here that is the same for all location. Such as moving to the next location (line below)
        #
        self.actions[choice].newLocation.arrive(states)

    def arrive(self, states):
        states.stepsTaken += 1
        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.handleChoices(index - 1, states) # indexing is 0-based, but we get 1-based index from the user

class House(Location):
    def __init__(self, name, description):
        super().__init__(name, description)
    
    def handleChoices(self, choice, states):
        #
        # Add House specific state changes, if needed. When done, let the super class (base class) handle the rest, i.e. moving to the next location.
        #
        if choice == 0:
            pass # You can add your specific changes for "go to your room" choice
        elif choice == 1:
            pass # You can add your specific changes for "go to the kitchen" choice
        elif choice == 2:
            pass # You can add your specific changes for "go to the main room" choice
        super().handleChoices(choice, states)

#
# Declare your locations here
#
yourRoom = Location("your room", "Your room is pretty plain, but at least you have your own. A bed stands in the corner, and a small, crude dresser sits under the window.")
kitchen = Location("the kitchen", "Mom has set out her delicious rolls to cool and has left the room. There are cupboards, a large table, and an oven in the kitchen.")
mainRoom = Location("the main room", "Your father takes a break from his work in the chair, which is the only thing besides a low table that furnishes the room. Of course the fireplace is there too.")

house = House("house", "Inside the house there is a sweet aroma of rolls being baked.")
house.addAction(Action("go to your room", yourRoom))
house.addAction(Action("go to the kitchen", kitchen))
house.addAction(Action("go to the main room", mainRoom))

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")

spawnPosition = Location("Spawn position", "You wake up in a sunny morning. After you get out of your bad, you decide to:")
spawnPosition.addAction(Action("go to the house", house))
spawnPosition.addAction(Action("walk the fields", field))
spawnPosition.addAction(Action("visit the stable", stable))

#
# 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

states = States()
spawnPosition.arrive(states)
print("Moves in the game: {}".format(states.stepsTaken))
print("Bye-bye")

I hope this helps. Good luck! :)

commented Feb 1, 2021 by Jeff The Chicken (2,920 points)
3. is the one I needed. So I basically make a class for each room with variable-related choices. thanks!
commented Feb 1, 2021 by Peter Minarik (84,720 points)
Yes, you can make a class (inheriting from Location) for all the rooms where you want to do more than just let the player go into some other direction.
0 votes
answered Feb 1, 2021 by Peter Minarik (84,720 points)
edited Feb 1, 2021 by Peter Minarik

There are multiple ways to do this.

1. Use Global Variables

Declare your states you want to change in a global scope.

import time

#
# Declare your globals here
#
stepsTaken = 0

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):
        # mark global variables as _global_ to change them, otherwise you can only read them
        global stepsTaken
        stepsTaken += 1
        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
#
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")

spawnPosition = Location("Spawn position", "You wake up in a sunny morning. After you get out of your bad, you decide to:")
spawnPosition.addAction(Action("go to the house", house))
spawnPosition.addAction(Action("walk the fields", field))
spawnPosition.addAction(Action("visit the stable", stable))

#
# 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()
print("Moves in the game: {}".format(states.stepsTaken))
print("Bye-bye")

2. Use A State Object

A more sophisticated way would be to create an object that holds the game states, and pass it to the functions that may need to read/change them.

import time

class States:
    def __init__(self):
        self.stepsTaken = 0

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, states):
        states.stepsTaken += 1
        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(states) # indexing is 0-based, but we get 1-based index from the user
        
#
# Declare your locations here
#
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")

spawnPosition = Location("Spawn position", "You wake up in a sunny morning. After you get out of your bad, you decide to:")
spawnPosition.addAction(Action("go to the house", house))
spawnPosition.addAction(Action("walk the fields", field))
spawnPosition.addAction(Action("visit the stable", stable))

#
# 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

states = States()
spawnPosition.arrive(states)
print("Moves in the game: {}".format(states.stepsTaken))
print("Bye-bye")

To be continued...

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...