首先, 初始化和编写主循环:
import pygame
from datetime import datetime
import math
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Pygame")
Clock = pygame.time.Clock()
Consolas = pygame.font.SysFont('Consolas', 32)
Black = (0, 0, 0)
White = (255, 255, 255)
Yellow = (255, 255, 0)
Green = (0, 255, 0)
Red = (255, 0, 0)
quit = False
while not quit:
for e in pygame.event.get():
if e.type == pygame.QUIT:
quit = True
Clock.tick(60)
screen.fill(Black)
pygame.display.flip()
pygame.quit()
exit()
然后,编写主要函数:
def draw_blank():
pygame.draw.circle(screen, White, (400, 300), 255) #钟的框
pygame.draw.circle(screen, Black, (400, 300), 250)
for i in range(1, 13):
pygame.draw.line(screen, White, (400 + math.sin(math.radians(i * 30)) * 250, 300 - math.cos(math.radians(i * 30)) * 250), (400 + math.sin(math.radians(i * 30)) * 220, 300 - math.cos(math.radians(i * 30)) * 220)) #大刻度
text = Consolas.render(str(i), True, White) #钟上的数字
screen.blit(text, (390 + math.sin(math.radians(i * 30)) * 200, 288 - math.cos(math.radians(i * 30)) * 200))
for i in range(1, 61):
pygame.draw.line(screen, White, (400 + math.sin(math.radians(i * 6)) * 250, 300 - math.cos(math.radians(i * 6)) * 250), (400 + math.sin(math.radians(i * 6)) * 240, 300 - math.cos(math.radians(i * 6)) * 240)) #小刻度, 有些被大的遮挡了
def draw_needles(radius: int, color: tuple, angle: float):
pygame.draw.line(screen, color, (400, 300), (400 + math.sin(math.radians(angle)) * radius, 300 - math.cos(math.radians(angle)) * radius)) #指针
def draw_time():
now = datetime.now() #获取时间
time = Consolas.render(f'Time:{now: %Y.%m.%d (%H:%M:%S)}', True, White)
screen.blit(time, (0, 0)) #显示时间
def draw_clock():
now = datetime.now()
s = (now.second) * 6 #角度
m = now.minute * 6 + now.second / 10
h = now.hour % 12 * 30 + m / 10 + s / 600
draw_blank() #画框
draw_needles(130, Red, h) #时针, 分针, 秒针
draw_needles(170, Green, m)
draw_needles(225, Yellow, s)
主循环添两行:
while not quit:
for e in pygame.event.get():
if e.type == pygame.QUIT:
quit = True
Clock.tick(60)
screen.fill(Black)
draw_time() #这两行
draw_clock()
pygame.display.flip()
pygame.quit()
exit()
效果:

1094

被折叠的 条评论
为什么被折叠?



