Pregunta

I wrote a little program to draw a pattern a cycle through different color along with a class for moderating the frame rate. For some reason there is random flickering whenever I run it and I have no idea why. It is very simple so I doubt it has to do with the screen updating quickly enough. I would appreciate any suggestions.

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()
¿Fue útil?

Solución

For one thing, get that "pygame.quit()" out of your main loop.

The flickering is due to the fact that your drawing code is periodically crashing. When the except in the try-except block is hit, then nothing will be drawn that frame, and the screen will "flicker" black.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top