在特定时间内完成绘制圆

时间:2018-12-19 14:46:45

标签: python python-3.x pygame

我正在尝试用圆圈创建倒计时。圆圈将显示与给定时间相比经过了多少时间。因此,如果倒计时是10秒且已过去5个,则将绘制半个圆圈。我提出了以下代码:

from math import pi
import pygame


pygame.init()

(x, y) = (800, 600)
screen = pygame.display.set_mode((x, y))
clock = pygame.time.Clock()

radius = 50
# Just to place the circle in the center later on
top_left_corner = ((x / 2) - (radius / 2), (y / 2) - (radius / 2))
outer_rect = pygame.Rect(top_left_corner, (radius, radius))

countdown = 1000  # seconds

angle_per_frame = 2 * pi / (countdown * 60)
angle_drawn = 0
new_angle = angle_per_frame
while True:
    if angle_drawn < 2 * pi:
        new_angle += angle_drawn + angle_per_frame
        pygame.draw.arc(screen, (255, 255, 255), outer_rect, angle_drawn, new_angle, 10)
        angle_drawn += angle_per_frame
    clock.tick(60)
    pygame.display.update(outer_rect)

因此,fps = 60在每一帧中都在绘制2 * pi / countdown * fps,将一个完整的圆分成几帧。然后在每个框架中绘制一部分圆。似乎可以很好地绘制圆圈,但是由于以下两个原因,它不能用于计时器:

  1. 完成圈的时间似乎少于给定的时间。

  2. 在绘制圆时,似乎圆的最后部分绘制得更快。

有人可以指出我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

问题是您将new_angle增加了angle_drawn + angle_per_frame,并且由于在angle_per_frame上加上了angle_drawn,因此每帧都会更大。

我宁愿使用clock.tick返回的增量时间,否则,如果帧频不是恒定的,则可能会有误差。然后,将angle_per_second值乘以dt得到该帧的正确值。

此外,因为如果角度之间的差太小,pygame.draw.arc无效,那么我必须从起始角度减去0.2,并且必须在绘图开始之前添加一个短暂的延迟。

from math import pi
import pygame
from pygame import freetype


pygame.init()

x, y = 800, 600
screen = pygame.display.set_mode((x, y))
clock = pygame.time.Clock()
FONT = freetype.Font(None, 32)
WHITE = pygame.Color('white')

radius = 50
# Just to place the circle in the center later on
top_left_corner = (x/2 - radius/2, y/2 - radius/2)
outer_rect = pygame.Rect(top_left_corner, (radius, radius))

countdown = 10  # seconds
angle_per_second = 2*pi / countdown
angle = 0
dt = 0  # dt is the time since the last clock.tick call in seconds.
time = 0

done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    time += dt
    angle += angle_per_second * dt
    # Delay the drawing a little bit, because draw.arc doesn't work
    # with very small angle differences.
    if angle > 0.2:
        pygame.draw.arc(screen, WHITE, outer_rect, angle-0.2, angle, 10)

    rect = pygame.draw.rect(screen, (50, 50, 50), (400, 340, 100, 50))
    FONT.render_to(screen, (410, 350), str(round(time, 2)), WHITE)
    dt = clock.tick(60) / 1000  # / 1000 to convert it to seconds.
    pygame.display.update([outer_rect, rect])