[Tutor] More class questions

Alan Gauld alan.gauld at btinternet.com
Tue Sep 4 10:23:01 CEST 2007


"Ara Kooser" <ghashsnaga at gmail.com> wrote

> What I have so far is a very simple text adventure with two rooms, 
> two
> items, and some exits.

So presumably you have a Room class, an Item class and
maybe an Exit class?

>   Two question which relates directly to classes: Do you create all
> your instances at the end of the program or just as needed?

You create objects as needed.
There is no mystery you have been using objects almost
since you started using Python. Strings are objects and
you create them as you need them. Same with Files.
Your own classes are no different except that the instantiation
mechanism is a little bit different.

> call functions from other classes within a class

Yes, If your Room class contains a list of Items you can
send messages to thoise items from your Room methods.:

class Item:
    def __innit__(self,n):
        self.n = n

    def say(self): print 'item', n

class Room:
     def __init__(self,id)
         self.items = [Item(42),Item(26)]
         self.id = id

     def describe(self):
         print 'Room:',self.id,'has:'
         for item in items: item.say()

r = R('hall')
r.describe()

Notice that Room.describe calls the Item.say method...
Also note that the Room constructor creates two instances of Item.

>   Third question. Using function I understand how to move a player
> around in different rooms using raw_input and if statements but how 
> do
> you do that with classes.

You have a Player class and it has a move method. You create
instances of players and ask them to move. If they are in a Room
you move within the room - perhaps you move to an exit which
will in turn return a new room which you assign to the player.

Something like:

class Exit:
    def __init__(self, toRroom)
        self.room = toRoom
     def pass(self):
        return self.room

class Player:
    def __init__(self,location=None):
       self.location = location
    def move(self, direction):
       exit = self.location.exitAt(direction)
       self.location = exit.pass()

Now when you call move('N') the player goes tonthe North exit
and passes throough to the room on the other side.

> I created a player class and I want one of
> the methods to be moving from room to room.

> Or should movement be a separate class?
I doubt it, movement is an action not an object
(usually), its a behaviour of other objects. If more
than players can move you may create a Movableobject
superclass and inherit the movement methods from that.

>   I am looking at the code that Paul McGuire wrote for using
> pyparsing and I don't quite understand how it all works. I have to
> book Game Programming: The L line coming in two weeks. I am just
> trying to get a head start.

Sorry, cant help there.

Alan G. 




More information about the Tutor mailing list