OO style advice

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • DomF

    OO style advice

    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,c lock):
    '''Pass in a clock object with time1 and time2 attributes.'''
    self.clock = clock

    def testforpost(sel f):
    print self.clock.time 1
    print self.clock.time 2

    class ChessClock:

    defaulttime = 7200

    def __init__(self,s tartvalue1=defa ulttime,startva lue2=defaulttim e):
    '''set up the clock for the start of a game'''
    ChessClock.defa ulttime = startvalue1
    self.time1 = startvalue1
    self.time2 = startvalue2
    self.state = 'Stopped'


    def reset(self,valu e1=defaulttime, value2=defaultt ime):
    '''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.clock gen()
    gameclockgen.ne xt()

    board = ChessBoard(game clock)
    board.testforpo st()

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

    board.testforpo st()
    #-----------#


  • Sean Ross

    #2
    Re: OO style advice

    "DomF" <fidtz@clara#sp am#.co.uk> wrote in message
    news:1076943278 .22567.0@echo.u k.clara.net...[color=blue]
    > I have been putting together a little text chess program and have run into[/color]
    a[color=blue]
    > style issue when integrating my chess clock with my chessboard generator.
    > Basically, I would like to be able to manipulate the clock independently[/color]
    of[color=blue]
    > the board but also want the clock time as displayed by the board to change
    > automatically.[/color]

    Hi.
    My first thought is to make a Clock object that has a time attribute and
    start() and stop() methods

    Then have one instance of Clock for each player (and perhaps an independent
    one for the board?)

    If you have Player objects, perhaps they could have a clock instance. In
    that way
    you could do something like:

    # suppose the players are maintained by the board in a list
    # and you have a turn variable for accessing the player whose turn it is to
    play
    while board.state != STALEMATE and board.state != CHECKMATE:
    player = player[turn]
    player.clock.st art()
    player.move()
    player.clock.st op()
    turn.next() # adjust turn index to let other player move next round


    you could even have player.clock.st art() and player.clock.st op() at the
    start
    and end of the inside of player.move() so your code looks more like this

    while board.state != STALEMATE and board.state != CHECKMATE:
    player[turn].move()
    turn.next()


    Just an idea,
    Sean


    Comment

    • Alan Gauld

      #3
      Re: OO style advice

      On Mon, 16 Feb 2004 14:54:31 -0000, "DomF"
      <fidtz@clara#sp am#.co.uk> wrote:[color=blue]
      > 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?[/color]

      In OO objects communicate via messages. Thus think about the
      messages that can be sent to the clock. Do not think about the
      data inside the clock, that should be treated as private (even
      though Python does not enforce this).

      Now you have a single clock object but referenced both inside and
      outside the board. Is that really what you want or do you want
      the oard to have its own clock instance internally? If it is a
      single object then its perfectly reasonable that both internal
      and external objects can send it messages. If its an internal
      object then only the board can conceptually see it.
      If you need to initialise the internal clock you may want to take
      a time parameter to the board and use that to set the clock
      initial values, rather than passing a functioning clock object as
      the parameter.

      Also as somebody else said you may want to use multiple clock
      objects...
      [color=blue]
      > I previously had them separate but that led to lots of ugly board.time1 =
      > clock.time1 statements.[/color]

      Rather than access the data I'd provide a method, say
      synchronise?

      board.synchroni se(myClock)

      Which internally sets the board clock to the same time as the
      parameter clock, something like:

      def synchronise(sel f, aClock):
      self.clock.setT ime(aClock.time ())

      Whether you think that looks any less ugly than the assignments
      you had is a moot point!

      Alan G.
      Author of the Learn to Program website

      Comment

      • A. Lloyd Flanagan

        #4
        Re: OO style advice

        "DomF" <fidtz@clara#sp am#.co.uk> wrote in message news:<107694327 8.22567.0@echo. uk.clara.net>.. .[color=blue]
        > 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?
        >[/color]
        As long as the clock is one conceptual object, you should definitely
        have only one instance. You're just passing a handle to the board to
        give the board permission to read/update the clock.
        The method of having the time in the board and the clock, and
        synchronizing, has a fatal flaw. You would have two instances
        modeling the exact same object, and that _would_ be bad design. I
        think you've got the right answer here.

        Comment

        • DomF

          #5
          Re: OO style advice

          "Alan Gauld" <alan.gauld@bti nternet.com> wrote in message
          news:m0m230lm5d v7j3rmpe1425nof 55mj11ahf@4ax.c om...[color=blue]
          > On Mon, 16 Feb 2004 14:54:31 -0000, "DomF"
          > <fidtz@clara#sp am#.co.uk> wrote:[color=green]
          > > 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[/color][/color]
          and[color=blue][color=green]
          > > the clock object. Is this good style or should I be designing in a[/color][/color]
          totally[color=blue][color=green]
          > > different way?[/color]
          >
          > In OO objects communicate via messages. Thus think about the
          > messages that can be sent to the clock. Do not think about the
          > data inside the clock, that should be treated as private (even
          > though Python does not enforce this).
          >
          > Now you have a single clock object but referenced both inside and
          > outside the board. Is that really what you want or do you want
          > the oard to have its own clock instance internally? If it is a
          > single object then its perfectly reasonable that both internal
          > and external objects can send it messages. If its an internal
          > object then only the board can conceptually see it.
          > If you need to initialise the internal clock you may want to take
          > a time parameter to the board and use that to set the clock
          > initial values, rather than passing a functioning clock object as
          > the parameter.
          >
          > Also as somebody else said you may want to use multiple clock
          > objects...
          >[color=green]
          > > I previously had them separate but that led to lots of ugly board.time1[/color][/color]
          =[color=blue][color=green]
          > > clock.time1 statements.[/color]
          >
          > Rather than access the data I'd provide a method, say
          > synchronise?
          >
          > board.synchroni se(myClock)
          >
          > Which internally sets the board clock to the same time as the
          > parameter clock, something like:
          >
          > def synchronise(sel f, aClock):
          > self.clock.setT ime(aClock.time ())
          >
          > Whether you think that looks any less ugly than the assignments
          > you had is a moot point![/color]

          There isn't only one way to do this then :)

          Thanks for the reply, points taken. I think the final decision will depend
          on whether I need to use the clock instance outside of the board or not. At
          the moment I reckon I will for match and player classes but maybe not!
          [color=blue]
          >
          > Alan G.
          > Author of the Learn to Program website
          > http://www.freenetpages.co.uk/hp/alan.gauld[/color]


          Comment

          • Magnus Lyck?

            #6
            Re: OO style advice

            "DomF" <fidtz@clara#sp am#.co.uk> wrote in message news:<107694327 8.22567.0@echo. uk.clara.net>.. .[color=blue]
            > 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?[/color]

            So, just pass in a bound method to view the clock output then!
            Likewise, player objects can get buttons to play with. Methods
            are also objects that can be passed around, you know... E.g:

            import time

            class ChessClock:
            WHITE, BLACK = False, True

            def __init__(self):
            self.last_start = None
            self.total = [0.0,0.0]
            self.running = None

            def white_press_but ton(self):
            if self.running is None:
            self.running = self.BLACK
            self.last_start = time.time()
            else:
            self.press_butt on(self.WHITE)

            def black_press_but ton(self):
            self.press_butt on(self.BLACK)

            def press_button(se lf, color):
            if self.running == color:
            self.running = not color
            self.total[color] += time.time() - self.last_start
            self.last_start = time.time()
            else:
            print "Not your turn!"

            def display(self):
            times = self.total[:]
            txt = ['STOPPED','RUNN ING']
            if not self.running is None:
            times[self.running] += time.time() - self.last_start
            for color, COLOR in [('White', self.WHITE), ('Black', self.BLACK)]:
            print "%s: %d min %02d sec %s" %(
            (color, times[COLOR]//60, times[COLOR]%60, txt[COLOR]))


            class ChessGame:
            def __init__(self, clock_display):
            self.clock_disp lay = clock_display
            ...

            ...
            self.clock_disp lay()
            ...


            class ChessPlayer:
            def __init__(self, colour, press_clock_but ton):
            self.press_cloc k_button = press_clock_but ton
            ...

            ...
            self.press_cloc k_button()
            ...

            ....

            clk = ChessClock()
            game = ChessGame(clk.d isplay)
            w = ChessPlayer('Wh ite', clk.white_press _button)
            b = ChessPlayer('Bl ack', clk.black_press _button)

            Comment

            Working...