OO style advice

DomF fidtz at clara#spam#.co.uk
Mon Feb 16 09:54:31 EST 2004


I have been putting together a little text chess program and have run into a
style issue when integrating my chess clock with my chessboard generator.
Basically, I would like to be able to manipulate the clock independently of
the board but also want the clock time as displayed by the board to change
automatically.

I am passing in a clock object to the board in __init__ to achieve this.
However, means that the clock object can be changed via the board object and
the clock object. Is this good style or should I be designing in a totally
different way?

I previously had them separate but that led to lots of ugly board.time1 =
clock.time1 statements.

Chopped up for brevity but tested code below.

Thanks for looking,

Dom Fitzpatrick

#-------#
import time

class ChessBoard:

    def __init__(self,clock):
        '''Pass in a clock object with time1 and time2 attributes.'''
        self.clock = clock

    def testforpost(self):
        print self.clock.time1
        print self.clock.time2

class ChessClock:

    defaulttime = 7200

    def __init__(self,startvalue1=defaulttime,startvalue2=defaulttime):
        '''set up the clock for the start of a game'''
        ChessClock.defaulttime = startvalue1
        self.time1 = startvalue1
        self.time2 = startvalue2
        self.state = 'Stopped'


    def reset(self,value1=defaulttime,value2=defaulttime):
        '''reset the chess clock with optional new game length'''
        self.time1 = value1
        self.time2 = value2
        self.state = 'Stopped'


    def clockgen(self):
        '''generator for clock events, uses self.state to control what
happens'''
        currenttimeleft = time.time()

        while 1:
            yield self.time1
            if self.state == 'Player1':
                self.time1 = self.time1 - int(time.time() - currenttimeleft)
                currenttimeleft = time.time()

            elif self.state == 'Player2':
                self.time2 = self.time2 - int(time.time() - currenttimeleft)
                currenttimeleft = time.time()
            else:
                currenttimeleft = time.time()



if __name__ == "__main__":

    gameclock = ChessClock()
    gameclockgen = gameclock.clockgen()
    gameclockgen.next()

    board = ChessBoard(gameclock)
    board.testforpost()

    gameclock.state = 'Player1'
    time.sleep(3)
    gameclockgen.next()

    board.testforpost()
#-----------#





More information about the Python-list mailing list