473,503 Members | 1,655 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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,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()
#-----------#
Jul 18 '05 #1
5 1121
"DomF" <fidtz@clara#spam#.co.uk> wrote in message
news:10****************@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.


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.start()
player.move()
player.clock.stop()
turn.next() # adjust turn index to let other player move next round
you could even have player.clock.start() and player.clock.stop() 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
Jul 18 '05 #2
On Mon, 16 Feb 2004 14:54:31 -0000, "DomF"
<fidtz@clara#spam#.co.uk> wrote:
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?
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...
I previously had them separate but that led to lots of ugly board.time1 =
clock.time1 statements.


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

board.synchronise(myClock)

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

def synchronise(self, aClock):
self.clock.setTime(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
http://www.freenetpages.co.uk/hp/alan.gauld
Jul 18 '05 #3
"DomF" <fidtz@clara#spam#.co.uk> wrote in message news:<10****************@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?

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.
Jul 18 '05 #4
"Alan Gauld" <al********@btinternet.com> wrote in message
news:m0********************************@4ax.com...
On Mon, 16 Feb 2004 14:54:31 -0000, "DomF"
<fidtz@clara#spam#.co.uk> wrote:
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?
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...
I previously had them separate but that led to lots of ugly board.time1 = clock.time1 statements.


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

board.synchronise(myClock)

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

def synchronise(self, aClock):
self.clock.setTime(aClock.time())

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


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!

Alan G.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld

Jul 18 '05 #5
"DomF" <fidtz@clara#spam#.co.uk> wrote in message news:<10****************@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)
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

35
4499
by: wired | last post by:
Hi, I've just taught myself C++, so I haven't learnt much about style or the like from any single source, and I'm quite styleless as a result. But at the same time, I really want nice code and I...
7
1638
by: Cameron Hatfield | last post by:
I was wondering how good this page of coding standards (http://www.doc.ic.ac.uk/lab/cplus/c++.rules/) is. Is it too outdated?
23
2691
by: Serve La | last post by:
When I write a medium to large sized C application I tend to create structures first, then makeStruct and freeStruct functions that dynamically allocate/free the struct and then I create a bunch of...
63
3442
by: Papadopoulos Giannis | last post by:
Which do you think is best? 1. a) type* p; b) type *p; 2. a) return (var); b) return(var); c) return var;
1
1302
by: RayS | last post by:
I've begun a Python module to provide a complete interface to the Meade LX200 command set, and have searched for a style/development guide for Python Lib/site-packages type modules, but only saw...
1
5809
by: r_mun | last post by:
Hello, I think it would be an interesting issue to everyone. What I'd like to do is simply change the style of my dynamically created table cell. I have written the following code to...
89
5051
by: scroopy | last post by:
Hi, I've always used std::string but I'm having to use a 3rd party library that returns const char*s. Given: char* pString1 = "Blah "; const char* pString2 = "Blah Blah"; How do I append...
12
1754
by: Christopher Key | last post by:
Hello, I've some code which I'd like to release in object form along with a suitable header. Before I do this however, I'd like to finalise the exact names for everything declared in the...
3
1894
by: Michellevt | last post by:
Hi I am working on a project (for college) and wondered if anyone can help me with my problem. In the project we are not allowed to make use of any "style" attributes but "class" attributes...
9
1263
by: Piotr K | last post by:
Ok, I tried simply everything that came to my mind and now I ran out of ideas, but to the point - take a look at the code below // GetStyle returns given style value (works fine)...
0
7202
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7086
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7280
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7330
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
5578
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5014
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4672
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3154
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1512
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.