[Tutor] my newbie program

Magnus Lycka magnus@thinkware.se
Thu Nov 21 06:33:03 2002


At 22:49 2002-11-20 -0600, david wrote:
>could you please explain the shared object?
>i am not clear on how Room is using one
>of Maps methods.
Sure.

> > class Room:
> >      map = Map() # Shared between instances.

Since we instanciate a map object here, in the class
scope which is executed only once, and not in __init__
which is executed one time for every Room object, we
get *one* map, which all room objects can access, either
as

Room.map

or as

self.map

as long as they don't hide it by doing "self.map = somethingElse".

Actually, since it's a public attribute of the Room class, any
piece of code in your program can access it as Room.map, but of
course, if it's not a Room instance, self.map won't work.

> > In Room.__init__ you have something like
> > self.map.placeRoom(self, x, y) so that the map
> > can keep track of where each room is.

You see?

if a room object is instanciated with (or somehow finds out)
it's x and y coordinates, it can do:
         self.map.placeRoom(self, x, y)
or if you wish:
         Room.map.placeRoom(self, x, y)

It will get a reference to the common map object and call its
placeRoom method with itself and the coordinates. Then the map
knows where a certain room should be located, and it can store
that information. See below in the Map class:

> >      def placeRoom(self, room, x, y):
> >          if self.grid.has_key((x, y)):
> >              raise KeyError, "Location taken!"
> >          self.grid[(x, y)] = room

You could also make map into a global object. I did like I did
because I felt that sometime in the future there might be several
maps, and then you'd have to change the room class so that each
room object gets the right map. If all the room objects always
use "self.map" you will only have to remove the map=Map() from the
current location and give the rooms their correct map in
Room.__init__. If they accessed a global map, and that was changed,
you'd have to change every place where the map objects use the map.
It's usually not a good idea to make things very complicated just
in case it might be needed in the future, but avoiding global
objects is usually a good idea. Using self.map instead of just map
doesn't feel like hard work...


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se