1

我写了一个小程序来绘制一个循环通过不同颜色的图案以及一个用于调节帧速率的类。出于某种原因,每当我运行它时都会随机闪烁,我不知道为什么。它非常简单,所以我怀疑它是否与屏幕更新足够快有关。我将不胜感激任何建议。

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

1 回答 1

3

一方面,将“pygame.quit()”从主循环中取出。

闪烁是由于您的绘图代码会定期崩溃。当 try-except 块中的 except 被命中时,该帧将不会绘制任何内容,并且屏幕将“闪烁”为黑色。

于 2012-02-15T05:40:38.773 回答