我最近刚开始学习pygame,目前正在研究一个示例示例,该示例的猫在窗口的边缘跑来跑去(我将猫替换为读取的矩形,以便可以复制示例)
import pygame
import sys
from pygame.locals import *
pygame.init()
FPS = 5
fpsClock = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32)
pygame.display.set_caption('Animation')
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# catImg = pygame.image.load('cat.png')
catx = 10
caty = 10
direction = 'right'
while True:
DISPLAYSURF.fill(WHITE)
if direction == 'right':
catx += 5
if catx == 280:
direction = 'down'
elif direction == 'down':
caty += 5
if caty == 220:
direction = 'left'
elif direction == 'left':
catx -= 5
if catx == 10:
direction = 'up'
elif direction == 'up':
caty -= 5
if caty == 10:
direction = 'right'
# DISPLAYSURF.blit(catImg, (catx, caty))
pygame.draw.rect(DISPLAYSURF, RED, (catx, caty, 100, 50))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
fpsClock.tick(FPS)
但是,如果我运行它,则显示的图像不是我期望的:红色矩形不会运行,除非将鼠标放在窗口上。 (这可能是设计选择。那么无论如何) 更令人担忧的是,矩形没有按照我预期的方式移动。它比沿路径向前跳几步,然后再移动一点,再跳一遍,依此类推。 我找不到跳跃发生方式的模式。我唯一能说的是它不会沿着窗口的边缘离开路径。
如果我移动这行:
DISPLAYSURF.fill(WHITE)
从while循环中,我可以看到屏幕沿路径的跳过部分之后仍然显示为红色。 因此,在我看来,代码仍在后台运行,并且矩形仍被写入虚拟DISPLAYSURF对象,但是该DISPLAYSURF对象并未打印到屏幕上。而且代码运行得非常快。
我使用python 3.8.0 pygame 2.0.0.dev6 在Windows上
我没有发现任何事情。 有人有同样的问题吗?这是哪里来的?
答案 0 :(得分:2)
这是Indentation的问题。 pygame.display.update()
必须在应用程序循环而不是事件循环中完成:
while True:
DISPLAYSURF.fill(WHITE)
# [...]
pygame.draw.rect(DISPLAYSURF, RED, (catx, caty, 100, 50))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
#<---|
pygame.display.update()
fpsClock.tick(FPS)
请注意,应用循环中的代码在每一帧中执行,但是事件循环中的代码仅在事件发生时才执行,例如鼠标移动(pygame.MOUSEMOTION
)。