[Tutor] Location of object instance in a list

alan.gauld@bt.com alan.gauld@bt.com
Thu Oct 31 12:53:38 2002


> I am trying to learn about object oriented design with 
> python.  I have decided to make a computer based boardgame 


> >>> test = Board()
> >>> test.surface[0][0].append('Cool object instance')

Actually this won't work since you have defined surface to 
be a one dimensional list!

However better still would be to hide the surface completely
and provide a place() method, say, that did it for you:

test.place(piece, x, y)

which places a piece object at x,y.

> same name.  Is there anyway the said object instance can have 
> knowledge of its place in the list of lists 

It shouldn't know that. Otherwise it becomes tightly coupled to the 
representation of the board - which is bad OOD.

> (test.surface[x][y])?  If so, I can then give the objects the 
> ability to move around the Board.surface[x][y] fairly easily.

So pass the board to the piece which can then ask it to place itself...

class Piece:
   def move(self, board):
       board.place(self, newX, newY)

Or maybe the board should have a move method to move pieces...

   def move(self, piece, x, y):
       oldX, oldY = self.locate(piece)
       self.place(None, oldX, oldY)
       self.place(piece, x, y)

> instances themselves should have the ability to move, and not 
> have the board pushing them around...

It depends. Do the pieces know what kind of board they are on?
OTOH Does the board know the rules of movement?
Or are they controlled by another object - a Game say?
But maybe if the pieces can only be used for one game type 
your idea is OK - probably true for chess pieces, but not 
for checkers or Ludo counters say...

The question you must answer is what are the responsibilities of 
the piece and board respectively? Which one is responsible for 
knowing about movement, location etc. There is no absolute answer 
to this but hopefully the principles shown above might help...

HTH,

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld