如何修复pygame中物体和图形的闪烁?

问题描述

在这里,我想使用 pygame 模块简单地制作 2 个矩形。我已经使用 2 种方法制作它们,但它们似乎不起作用。请推荐一些可以工作的。 (我使用的是 Python 3.8.3)

代码如下:

import pygame
pygame.init()

screen = pygame.display.set_mode((100,100))

Box_color = (255,0)
color = (0,150,100)

yBox = 20
xBox = 20

running = True
while running:
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False
        
    if event.type == pygame.KEYDOWN:
                                                             
        yBox += 5


    if (yBox >= 45):
        yBox = 45                                                               
pygame.draw.rect(screen,Box_color,pygame.Rect(xBox,yBox,50,50),2)
pygame.display.flip()

pygame.draw.rect(screen,pygame.Rect(20,95,2)
pygame.display.flip()

screen.fill(color)
pygame.display.update()

解决方法

您的游戏因多次调用 pygame.display.flip()pygame.display.update() 而闪烁。在应用程序循环结束时更新一次显示就足够了。多次调用 pygame.display.update()pygame.display.flip() 会导致闪烁。

从您的代码中删除所有 pygame.display.update()pygame.display.flip() 调用,但在应用程序循环结束时调用一次。但是,在绘制对象之前清除显示:

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            ybox += 5
        if (ybox >= 45):
            ybox = 45                                                               

    # clear disaply
    screen.fill(color)

    # draw objects
    pygame.draw.rect(screen,box_color,pygame.Rect(xbox,ybox,50,50),2)
    pygame.draw.rect(screen,pygame.Rect(20,95,2)

    # update dispaly
    pygame.display.update()

典型的 PyGame 应用程序循环必须: