python一个简单的时钟模型展示
以python代码展示,使用了math,pygame等库。
一、思路
设置窗口大小为500x500,以(250,250)为圆心,以200为臂长L。秒针和分针每次跳6度在代码中以弧度计,时针每次跳30度同样以弧度计。
弧度计算公式:rad=angle° x π/180°
时间尺度计算:(x,y)=(|L*cos(rad)-250|,|L*sin(rad)-250|) #减250表示坐标变换
时间尺度的计算公式用于计算以pygame窗口左上角为原点时刻度的位置和3个指针的指向点。
得到我们所要的时间刻度和指针二元坐标系位置后,我们便可以在pygame窗口中准确绘制刻度和指针元素。
- 计算刻度和指针坐标点。
- 绘制刻度和指针图案。
- “时间回滚”–即每当某个指针绕过一圈后,它的带动指针要走过一段时间刻度。如秒针绕过一圈后,分针要走过6°,分针绕过一圈后,而时针要走30°。
二、代码展示
import pygame as pg
from pygame.locals import *
from math import sin,cos
help="""
***********************************************
* *
* This a simple model of clock,enjoy yourself *
* *
***********************************************
"""
print(help)
#-----------------------
#set some var about color,screen size,and image change speed
L=200
RED=(255,0,0)
GREEN=(0,255,0)
WHITE=(255,255,255)
BLUE=(0,0,255)
sec_point=[(int(abs(L*cos(i*0.0175)-250)),int(abs(L*sin(i*0.0175)-250))) for i in range(0,360,6)]
other_point=[(int(abs(L*cos(i*0.0175)-250)),int(abs(L*sin(i*0.0175)-250))) for i in range(0,360,30)]
clock = pg.time.Clock()
#-----------------------
#A key var about crabing three point move angle,sec=6 min=6,hour=30
alamrt=[0,0,0]
#-----------------------
#common pygame configure
pg.init()
screen=pg.display.set_mode((500,500),0,32)
#-----------------------
#cal where any three point func base var alamrt
def GetPoint():
global alamrt,L
sec_x=int(abs(L*cos(alamrt[-1]*0.0175)-250))
sec_y=int(abs(L*sin(alamrt[-1]*0.0175)-250))
min_x=int(abs(L*cos(alamrt[-2]*0.0175)-250))
min_y=int(abs(L*sin(alamrt[-2]*0.0175)-250))
hour_x=int(abs(L*cos(alamrt[-3]*0.0175)-250))
hour_y=int(abs(L*sin(alamrt[-3]*0.0175)-250))
return {"sec":(sec_x,sec_y),"min":(min_x,min_y),"hour":(hour_x,hour_y)}
#---------------------
#It's easy understand from the func name
def Draw():
global clock,screen,pg,sec_point,other_point,alamrt
screen.fill(WHITE)
#---------------------
#Draw time ticks
for px,py in sec_point:
pg.draw.circle(screen,BLUE,(px,py),2,0)
for px,py in other_point:
pg.draw.circle(screen,RED,(px,py),5,0)
#---------------------
#Draw clock point
PP=GetPoint()
pg.draw.line(screen,BLUE,(250,250),PP["sec"],1)
pg.draw.line(screen,GREEN,(250,250),PP["min"],2)
pg.draw.line(screen,RED,(250,250),PP["hour"],3)
pg.display.update()
clock.tick(30)#30000
#----------------
#let's show start :p
while True:
for event in pg.event.get():
if event.type==12:
pg.quit()
exit()
Draw()
#------------------
#time circle again
alamrt[-1]+=6
if alamrt[-1]>=360:
alamrt[-2]+=6
alamrt[-1]=0
if alamrt[-2]>=360:
alamrt[-3]+=30
alamrt[-2]=0
if alamrt[-3]>=360:
alamrt[-3]=0
三、操作截图
谢谢各位