Post Reply 
Analog clock written in Python
08-16-2023, 03:04 PM
Post: #1
Analog clock written in Python
This program draws an analog clock displaying the current time. It is written in Python. The following code needs to be saved as a PPL program.

Code:
#PYTHON clock
from hpprime import *
from math import *
#Set to the center of the screen.
x0=160
y0=120
#Repeat clock update until escape key is pressed.
while keyboard()>>4&1<1:
#Set G1 to a white background the size of the screen.
 dimgrob(1,320,240,0xffffff)
#Get current time by calling Time through eval. A rational number is returned which indicates the amount of hours including the decimal part. The maximum resolution is in seconds.
 time=eval("Time")
#Store the hours in variable h.
 h=int(time)
#Calculate the angle of the hour hand in radians and store it in variable ph. It is necessary to apply an offset as angles start from the positive x axis, that is to say not from number 12 on the clock but from number 3. 
 ph=time%12/6*pi-1/2*pi
#Calculate the angle of the minute hand in radians and store it in variable pm. The whole decimal part is considered so that the minute hand moves smoothly, even for fractions of a minute.
 pm=(time-h)*2*pi-1/2*pi
#Store the minutes in variable m. The decimal part is retained.
 m=(time-h)*60
#Store the decimal part of m in variable raws.
 raws=m-int(m)
#Calculate the angle of the seconds hand in radians and store it in variable ps. 
 ps=raws*2*pi-1/2*pi
#Store the seconds in variable s.
 s=raws*60
#Round the amount of seconds, taking into account that it goes from 0 to 59.
 if s-int(s)>=0.5:
  if s<59:
   s+=1
  else:
   s=0
 s=int(s)
#Remove the decimal part from m.
 m=int(m)
#Draw the outline of a black circle of size 100 at the center of the screen.
 circle(1,x0,y0,100,0)
#Draw the numbers of the clock face. Some values were determined by trial and error in an attempt to place the numbers along a round path.
 for i in range(12):
  n=i
#Set to 12 if 0.
  if i<1:
   n=12
  pii=i/6*pi-1/2*pi
#The variable ni is an offset needed to adjust the position of numbers 0 to 6.
  ni=0
  if i<7:
   ni=2
#The numbers are drawn in the color black in a radius of 90 around the center of the screen.
  textout(1,x0+90*cos(pii)-4*len(str(n))+ni,y0+90*sin(pii)-8,str(n),0) 
#The 3 hands of the clock are drawn with different lenghts.
 line(1,x0,y0,x0+85*cos(ps),y0+85*sin(ps),0xff0000)
 line(1,x0,y0,x0+75*cos(pm),y0+75*sin(pm),0xff00)
 line(1,x0,y0,x0+50*cos(ph),y0+50*sin(ph),0xff)
#Each time value is formatted to add a zero in front when a single digit number.
 if h<10:
  h="0"+str(h)
 if m<10:
  m="0"+str(m)
 if s<10:
  s="0"+str(s)
#The time string is displayed in the top left of the screen.
 textout(1,0,0,str(h)+":"+str(m)+":"+str(s),0)
#G1 is copied to G0.
 blit(0,0,0,1)
#end
EXPORT CLOCK()
BEGIN
PYTHON(clock)
END;

HP 35S - HP Prime - HP 50g - HP 39gII
Find all posts by this user
Quote this message in a reply
Post Reply 




User(s) browsing this thread: 1 Guest(s)