[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Text-Based RPG



On Mon, June 18, 2007 8:57 pm, Jonah Fishel wrote:

>> I don't really have a good enough grasp of classes to implement
>> them. Could I make a RoomManager class?
>
>> Also you should look up how 'class'es work. Using them would make
>> this easier.


Here's one I know enough to answer! 8)

Yes, you could (and should). It looks like you're handling each room and
action as a special case, which means a lot of repeated work. For
instance, you have several commands for "talk to [person]". What if you
processed the input a bit more, like so:

## Where "command" is a string with what the user typed:
words = command.split() ## Split into a list of words, found by searching
for spaces (by default; but try eg. split(","))
if words[0] == "talk":
    person_to_talk_to = words[1]

Looking for specific words like that does require that you check for how
many words there are, though (using len(words)); the above code would
crash if the user typed a blank line or just "talk".

Classes don't have to be scary. The only arcane bit of setup is this:

class MyClass:
    """Put comments here"""
    def __init__(self): ## Has to be called __init__
        self.some_variable = 42
        self.some_other_variable = "Trogdor"

Then you define functions within the class, and make an actual instance of
the class by saying:
x = MyClass()

Then you can access it like so:
x.some_variable ## Returns the number 42

Even without getting into functions (besides that automatic setup
function), the usefulness of a class like this is that you can easily keep
track of a group of related variables, like all the information about a
single room.

A suggestion for one way to set up a class:

class Knight:
    def __init__(self,**options):
        self.name = options.get("name","Robin") ## The second is a default
value
        self.airspeed_velocity = options.get("airspeed_velocity") ##
Default is None

## Now create an instance:
arthur = Knight(name="Arthur",hit_points=999)
## Since "hit points" isn't referred to in the class setup, it gets
ignored harmlessly.

Hopefully this will be useful.