我试图在Python 3.6中编写一个程序,在pygame(一个Python模块)的帮助下,它应该在屏幕上快速闪烁红色,绿色和蓝色。程序在停止响应之前大约需要十到十五秒的时间运行。 (我注意到只有3个事件被打印到控制台,当时应该有很多。)
import pygame
import threading
import time
'''
IMPORTS ARE ABOVE THIS LINE
'''
class EventHandler(threading.Thread):
def run(self):
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
'''
CLASSES ARE ABOVE THIS LINE
'''
# Initializer
gameInit = pygame.init()
# Colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# Setup Crap
gameDisplay = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Pygame Colors")
# Event Handler
handler = EventHandler()
handler.start()
# Game Loop
while True:
gameDisplay.fill(red)
pygame.display.update()
time.sleep(0.1)
gameDisplay.fill(green)
pygame.display.update()
time.sleep(0.1)
gameDisplay.fill(blue)
pygame.display.update()
time.sleep(0.1)
答案 0 :(得分:2)
你需要在run
方法中使用while循环,并将主循环放入函数中。
import pygame
import threading
import time
class EventHandler(threading.Thread):
def run(self):
while True:
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameInit = pygame.init()
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
gameDisplay = pygame.display.set_mode((800, 600))
def main_loop():
while True:
gameDisplay.fill(red)
pygame.display.update()
time.sleep(0.4)
gameDisplay.fill(green)
pygame.display.update()
time.sleep(0.4)
gameDisplay.fill(blue)
pygame.display.update()
time.sleep(0.4)
handler = EventHandler()
handler.start()
t = threading.Thread(target=main_loop)
t.start()
但是,在这种情况下,threading
真的不需要,代码看起来很奇怪。您可以使用pygame.time.get_ticks()
来计算传递的时间,然后在超过时间限制时更改颜色。如果你想无限循环遍历几个值,itertools.cycle
非常方便。
import itertools
import pygame
pygame.init()
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# An infinite iterator that cycles through these colors.
colors = itertools.cycle((red, green, blue))
color = next(colors)
gameDisplay = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
start_time = 0
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
current_time = pygame.time.get_ticks()
if current_time - start_time > 500: # 500 milliseconds.
color = next(colors)
start_time = current_time
gameDisplay.fill(color)
pygame.display.flip()
clock.tick(60)
pygame.quit()
答案 1 :(得分:0)
我建议您的代码运行得太快,并增加time.sleep
值。