在pygame中闪烁

时间:2012-01-04 17:11:40

标签: refresh pygame flicker rate

我写了一个小程序,通过不同的颜色绘制一个循环模式,以及一个用于调节帧速率的类。出于某种原因,每当我运行它时都会出现随机闪烁,我不知道为什么。这很简单,所以我怀疑它与屏幕更新速度有关。我很感激任何建议。

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()

1 个答案:

答案 0 :(得分:3)

首先,从主循环中获取“pygame.quit()”。

闪烁是由于您的绘图代码会定期崩溃。当try-except块中的except被击中时,那个帧将不会被绘制,并且屏幕将“闪烁”黑色。