In my class, we're making a text adventure, and I'm just trying to walk between rooms. So far, I made a class called "Room".
class Room(object):
def __init__(self,name):
self.name = name
As well as some rooms to move between with subclasses.
class Backyard(Room):
global current
def __init__(self):
self.name = "Backyard"
def choose(self,choice):
if "north" in choice:
current = kitchen
else:
print("You cannot go that way")
return current
class Kitchen(Room):
global current
def __init__(self):
self.name = "Kitchen"
def choose(self,choice):
if "south" in choice:
current = yard
else:
print("You cannot go that way")
return current
yard = Backyard()
kitchen = Kitchen()
Now, to run the actual game, I have this.
run = True
current = yard
show_yard
while run:
choose(input(">>> ")
show_current
The show_yard function just prints a description of that room (the yard), but when I run the game, I was hoping to be able to use show_current so that whatever the variable 'current' was set to, it would read off that description, but instead it gives me an error because there's no function called 'show_current'.
I'm wondering if there is some way to insert variables when calling a function so that I don't have to write a whole bunch of code for something that could be solved in something as simple as this. Thanks.
globalis a serious antipattern. Only in very rare occasions you should use that.show()method. Then all you need to use iscurrent.show()to call the corresponding method on the current location. You can put the method on the base class (and just useself.nameto print the name of the location), or give each subclass a more elaborate implementation.currenta global variable everywhere. Yourchoose()methods return the new location, so usecurrent = current.choose()to assign returned location back tocurrent. Not that settingglobal currenton the class even works, you can remove theglobal currentlines with no change in functionality for your current code.