我写了一个小程序来绘制一个循环通过不同颜色的图案以及一个用于调节帧速率的类。出于某种原因,每当我运行它时都会随机闪烁,我不知道为什么。它非常简单,所以我怀疑它是否与屏幕更新足够快有关。我将不胜感激任何建议。
import pygame, time, random
w, h = 640, 480
screen = pygame.display.set_mode((w, h))
running = 1
inc = 20
m = [1, 1, 1]
c = [random.randint(0,255), random.randint(0,255), random.randint(0,255)]
class FrameRate():
def __init__(self, rate = 60):
self.frame_rate = rate
self.refresh_time = 1.0/self.frame_rate
self.cur_time = time.time()
self.prev_time = time.time()
self.elapsed_time = 0
def update(self):
temp = self.cur_time
self.cur_time = time.time()
self.elapsed_time = self.cur_time - self.prev_time
self.prev_time = temp
def regulate_frame_rate(self):
if self.elapsed_time < self.refresh_time:
time.sleep(self.refresh_time - self.elapsed_time)
fr = FrameRate()
pygame.init()
while running:
fr.update()
fr.regulate_frame_rate()
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = 0
screen.fill((0, 0, 0))
# Reverse color direction
for i, p in enumerate(c):
if c[i] > 255 or c[i] < 0:
m[i] = -m[i]
c[i] += m[i]
for i in range(0,w/inc):
try:
pygame.draw.line(screen, (c[0],c[1],c[2]), (i * inc, 0), (0, h - i*inc))
pygame.draw.line(screen, (c[0],c[1],c[2]), (w - i * inc, 0), (w, h - i*inc))
pygame.draw.line(screen, (c[0],c[1],c[2]), (i * inc, h), (0, i*inc))
pygame.draw.line(screen, (c[0],c[1],c[2]), (w - i * inc, h), (w, i*inc))
except TypeError:
pass
pygame.display.flip()
pygame.quit()