【问题标题】:pygame skipped updating screenpygame跳过更新屏幕
【发布时间】:2020-08-28 13:17:30
【问题描述】:

我最近刚开始学习 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 在窗户上

我没有找到任何关于此事的信息。 有人有同样的问题吗?这是从哪里来的?

【问题讨论】:

    标签: python pygame screen python-3.8


    【解决方案1】:

    这是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)。

    【讨论】:

    • 让我移动鼠标是一个事件,只有当我将鼠标悬停在窗口上时矩形才会移动。我觉得自己好傻。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多