[Tutor] Re: Help with classes
Andrei
project5 at redrival.net
Thu Apr 7 21:22:52 CEST 2005
Kevin <python.programming <at> gmail.com> writes:
> I am fooling around with classes and I was trying to create a very
> small one player text adventure. I made a class called commands here
> it is:
> class Commands:
> def __init__(self):
> pass
> def quiting(self):
> sys.exit()
<snip>
> I want to beable to type in a command from the list at the prompt and
> have it call one of the functions from the class. I was looking for a
> shorter way to write it but the only way I can think of is with an if
> statment for each command. Is there a better way or shorter way to do
> this?
I don't think you're making proper use of classes. A class is a collection of
data and methods related to that data. The Commands class is merely a collection
of unrelated methods. IMO the natural solution for your problem would be a
dictionary, where a command is mapped to a function. You'd ask the player for a
command, strip + lowercase it and check if you have a key of that name in your
commands dictionary and if that is the case, run the associated function. It's a
shorter solution and easier to maintain than making a class, keeping a list of
commands and inspecting a Commands object to see if something is available.
Possible classes in a text adventure could be a Player class (which could
contain a list of items which the Player carries, life points, etc.), a Room
class (which could contain information and methods related to the room the
player is in plus the connected rooms), an Item class (with subclasses for
different types of items, where different implementations of e.g. PickUp methods
would determine if the player could pick up a pencil or a skyscraper), etc.
Yours,
Andrei
More information about the Tutor
mailing list