Write a generic Counter class with these methods. The counter should start at 0 and go up to the maximum value, then reset to 0 and start counting up again.
constructor that takes a maximum value. What data needs to be stored in every counter object?
__init__(self, maxval)
str method, in case someone tries to print a counter object
__str__(self)
getter, for current value of counter
getValue(self)
setter, to set or reset value:
setValue(self, v)
increment, to increase value by 1, rollover back to zero if needed
increment(self)
Test your Counter class with something simple like this:
c = Counter(23)
for i in range(60):
print c
c.increment()
(should print 0, 1, 2, ... 23, 0, 1, 2...)
Write a clock class with these methods. Note: make use of the Counter() class!
Also note: no graphics in this class...this is just a simple clock object.
constructor that takes current time of clock. What data needs to be stored in every Clock object?
__init__(self, hr, mn, sc)
Hint: you should use 3 Counter objects!
str method to allow printing of Clock objects
__str__(self)
getTime(), to get/return a string representation of the time:
getTime(self)
setClock(), to allow setting the time (we will not use this today, but probably a useful method to have in a clock class):
setClock(self, h, m, s)
tick(), to advance time of clock by 1 second:
tick(self)
Again, add a simple test to make sure the clock class works:
c = Clock(11,58,45)
for i in range(130):
print c
c.tick()
Should print out:
11:58:45
11:58:46
11:58:47
11:58:48
...
Now run the digital clock app, which imports the Clock class:
from graphics import *
from clock import *
from time import sleep
import datetime
##########################################################
def main():
"""create graphics/digital clock app for desktop"""
w = 300
h = 100
gw = GraphWin("digiclock", w, h)
gw.setBackground("grey15")
color = color_rgb(239,145,4)
cp = Point(w/2, h/2)
# use datetime module to get current hour, min, sec
now = datetime.datetime.now()
h = now.hour
m = now.minute
s = now.second
# create clock object and clock text object
digclock = Clock(h,m,s)
clockTextObj = Text(cp, digclock.getTime())
clockTextObj.setSize(36)
clockTextObj.setFace("times roman")
clockTextObj.setTextColor(color)
clockTextObj.draw(gw)
# go into getTime mode...
while True:
sleep(1)
digclock.tick()
clockTextObj.setText(digclock.getTime())
key = gw.checkKey()
if key == 'Escape':
break
##########################################################
main()