[Tutor] designing POOP

Kent Johnson kent37 at tds.net
Wed Feb 13 13:38:06 CET 2008


Tiger12506 wrote:
> vg = VideoGame()
> howmany = rand.randint(0,100)
> for i in range(howmany):
>   vg.buttonpush()
>   print vg.score        #Tear open the case (hope you have a screwdriver)
> 
> OR
> 
> class VideoGame():
>   def __init__(self):
>     self.score = 0
>   def updatedisp():
>     print self.score
>   def buttonpush():
>     self.score += 1
>     self.updatedisp()
> 
> vg = VideoGame()
> howmany = rand.randint(0,100)
> for i in range(howmany):
>   vg.buttonpush()                #Let the videogame display your score 
> however it wishes
> 
> The second way is preferable for many reasons...

Hmm. Not to me. The second version couples the game state with the 
display. I would rather have

- a Game object that maintains the state of the game and has methods to 
manipulate the state

- a Display object that displays the state of the game

- a Controller object that mediates between user interaction, the Game 
and the Display.

Something like:

class Game(object):
   def __init__(self):
     self.score = 0
   def handleSomethingGood(self):
     self.score += 1

class Display(object):
   def showScore(self, score):
     print score

class Controller(object):
   def __init__(self, game, display):
     self.game = game
     self.display = display
   def handleButton(self):
     self.game.handleSomethingGood()
     self.display.showScore(self.game.score)

Now Game.handleSomethingGood() is decoupled from both the display and 
the actual UI event that signals SomethingGood happened.

This is an example of Model-View-Controller architecture (google it). 
Notice that the Game and Display are now reusable (maybe there are both 
GUI and text interfaces to the game, for example, or versions for 
wxPython and PyQt) and testable independently of each other.

A more advanced design might register the Display as an observer of the 
Game score but I don't want to get into that...

Kent


More information about the Tutor mailing list