【问题标题】:How to fix flickering of objects and figures in pygame? [duplicate]如何修复pygame中物体和图形的闪烁? [复制]
【发布时间】:2021-03-27 12:55:06
【问题描述】:

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

代码如下:

import pygame
pygame.init()

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

box_color = (255, 0, 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, box_color, pygame.Rect(20, 95, 50, 50), 2)
pygame.display.flip()

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

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    由于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, box_color, pygame.Rect(20, 95, 50, 50), 2)
    
        # update dispaly
        pygame.display.update()
    

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

    【讨论】:

      猜你喜欢
      • 2019-06-08
      • 2011-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-12
      • 1970-01-01
      • 1970-01-01
      • 2011-02-06
      相关资源
      最近更新 更多