OO style advice
Magnus Lyck?
magnus at thinkware.se
Thu Feb 19 16:00:37 EST 2004
"DomF" <fidtz at clara#spam#.co.uk> wrote in message news:<1076943278.22567.0 at echo.uk.clara.net>...
> 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?
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_button(self):
if self.running is None:
self.running = self.BLACK
self.last_start = time.time()
else:
self.press_button(self.WHITE)
def black_press_button(self):
self.press_button(self.BLACK)
def press_button(self, 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','RUNNING']
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_display = clock_display
...
...
self.clock_display()
...
class ChessPlayer:
def __init__(self, colour, press_clock_button):
self.press_clock_button = press_clock_button
...
...
self.press_clock_button()
...
...
clk = ChessClock()
game = ChessGame(clk.display)
w = ChessPlayer('White', clk.white_press_button)
b = ChessPlayer('Black', clk.black_press_button)
More information about the Python-list
mailing list