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 make this function call a function from a different class based on what location I am arriving to?

+1 vote
asked Feb 2 by Jeff The Chicken (2,860 points)
edited Feb 2 by Jeff The Chicken

In the arrive function of the Location class, I'm trying to call a function from the arriveoptions class and make which function that I'm calling based upon the location I'm arriving to, or self.name, with the word "option" following it. Basically I want it to call arriveoptions.____option, where ____ is the value of self.name. Tell me If this description is too confusing.

Update: I found a different way to do what I wanted, but getting an answer would still be helpful.

Here is the code, highighted is the part I'm having trouble with:

import time
#variables
candle = 0
apple = 0
horse = 0
string = 0
ring = 0
fathermoney=0
coin=0
score=0
feather=0
necklace=0
fruitbowl = 0
marblesack = 0
book = 0
speechpoints = 0
sawbarker = False
gavemarbles = 0
wentfield = False
wenthouse = False
#
# Declaration of classes -- game logic
#
class arriveoptions:
    def fieldoption():
        wentfield=True
    def houseoption():
        wenthouse=True
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):
        try:
            arriveoptions.#what do I put here?
        except AttributeError:
            pass
        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... :(")
                    time.sleep(2)
                    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 bed, 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(wentfield)

1 Answer

+1 vote
answered Feb 2 by Peter Minarik (22,620 points)
selected Feb 3 by Jeff The Chicken
 
Best answer

I get the description but not sure how (if at all) this can be done in Python. Below are some alternative ways to achieve what you're looking for.

if / elif / else

The simples solution would be to add a series of if/elif/else cases and call the functions according to how the conditions in the ifs evaluate.

Inheritance

A better solution would be to use inheritance again as we did before.

Create a function in the Locations (base) class, and override it in any derived classes (such as House) where you want to do something specific. An alternative solution is not to create any new function, just override the arrive() function in the derived class and when done implementing something specific, call the super().arrive() function in the end of the overwritten method.

import time

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

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 = []
    
    #
    # Generic logic for Location and derived classes
    #
    def addAction(self, action):
        self.actions.append(action)

    def arrive(self, states):
        self.handleArriveSpecific(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
        self.actions[index - 1].newLocation.arrive(states)
    
    #
    # Virtual functions below. Override them in the derived class to do somethign specific
    #
    def handleChoices(self, choice, states):
        pass # we don't want to do anything specific here, in the base class

    def handleArriveSpecific(self, states):
        pass # we don't want to do anything specific here, in the base class

class House(Location):
    def __init__(self, name, description):
        super().__init__(name, description)
        
    def handleArriveSpecific(self, states):
        states.visitedHouse = True

    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

#
# 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 some statistics
#
print("Moves in the game: {}".format(states.stepsTaken))
if states.visitedHouse:
    print("House visited.")
else:
    print("House not visited.")
print("Bye-bye")
commented Feb 2 by Jeff The Chicken (2,860 points)
Thank you again! You have helped me so much with this game! Would you like to be included in the credits? If so, how would you like me to refer to you? Also, if you want I can send you a link to the final product (when finished) if you give me an email (totally okay if you don't want to)
commented Feb 2 by Peter Minarik (22,620 points) 1 flag
You can just post the link here on OnlineGDB and I'll see it. ;)

I'm happy to help without taking credits for it in your game. It's your idea, I am just giving some guidance.
commented Feb 2 by Jeff The Chicken (2,860 points) 1 flag
Well then, I'll just post it after this comment when I'm done.
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.
...