1
我寫了一個小程序來繪製模式一個循環通過不同的顏色以及一個類,以調節幀速率。出於某種原因,每當我運行它時都會隨機閃爍,我不知道爲什麼。這非常簡單,所以我懷疑它與屏幕更新足夠快有關。我將不勝感激任何建議。pygame閃爍
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()
防止閃爍的最簡單方法是刪除'screen.fill()'調用(或將其移至循環外部),因爲您不需要此應用程序。 – 2012-01-13 15:00:32
我想你應該在'time'上使用'pygame.time.get_ticks()'和'pygame.time.Clock' – ninMonkey 2013-07-10 21:23:41