Python 在特定的时间内完成绘制一个圆
我正在尝试创建一个带圆圈的倒计时。圆圈将显示与给定的时间量相比,经过了多少时间。因此,如果倒计时是10秒,5秒已经过去,那么半个圆圈就画出来了。我想出了以下代码:Python 在特定的时间内完成绘制一个圆,python,python-3.x,pygame,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
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)
从数学导入pi
导入pygame
pygame.init()
(x,y)=(800600)
screen=pygame.display.set_模式((x,y))
clock=pygame.time.clock()
半径=50
#稍后将圆放在中心
左上角=((x/2)-(半径/2),(y/2)-(半径/2))
outer_rect=pygame.rect(左上角,(半径,半径))
倒计时=1000秒
每帧角度=2*pi/(倒计时*60)
绘制的角度=0
新角度=每帧角度
尽管如此:
如果绘制的角度小于2*pi:
新角度+=绘制角度+每帧角度
pygame.draw.arc(屏幕,(255,255,255),外部矩形,角度绘制,新角度,10)
绘制角度+=每帧角度
时钟滴答(60)
pygame.display.update(外部错误)
因此,在每一帧中,我画的是2*pi/countdown*fps,将一整圈划分为多帧。然后在每一帧中,画出圆的一部分。它似乎可以很好地画出圆圈,但它不能用作计时器,原因有二:
有人能指出我做错了什么吗?问题是,你将
新角度增加角度+每帧角度,因为你将每帧角度添加到角度
我宁愿使用返回的delta时间,否则如果帧速率不是常数,可能会有不准确的情况。然后,将每_秒角度
值乘以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])
太好了,谢谢!我已经计算出起始角度总是0
,不必担心小角度!