鱼C论坛

 找回密码
 立即注册
查看: 2996|回复: 2

[已解决]pygame矩形移动闪烁怎么办

[复制链接]
发表于 2023-9-29 15:59:09 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. import pygame, sys
  2. from pygame.locals import *
  3. pygame.init()
  4. screen = pygame.display.set_mode((600, 500))
  5. pygame.display.set_caption("Drawing Rectangles")

  6. position = [300, 250,100, 100]
  7. vel = [2, 1]

  8. while True:
  9.     for event in pygame.event.get():
  10.         if event.type == QUIT:
  11.             pygame.quit()
  12.             sys.exit()

  13.     screen.fill((0, 0, 200))

  14.     #move teh rectangle
  15.     position[0] += vel[0]
  16.     position[1] += vel[1]
  17.     if position[0] > 500 or position[0] < 0:
  18.         vel[0] = -vel[0]
  19.     if position[1] > 400 or position[1] < 0:
  20.         vel[1] = -vel[1]
  21.     #draw the rectangel
  22.     color = 255, 255, 0
  23.     width = 0
  24.     pygame.draw.rect(screen, color, position, width)

  25.     pygame.display.update()
  26.     pygame.time.delay(10)
复制代码


最佳答案
2023-9-29 15:59:23
问题描述:矩形移动时出现闪烁问题。

解决方案:在pygame中,可以使用双缓冲技术来解决矩形移动时的闪烁问题。双缓冲技术的原理是将要显示的图像先绘制在一个缓冲区中,等到整个图像绘制完成后再将其一次性地显示出来。这样可以避免在绘制过程中出现的闪烁问题。

修改代码如下:

import pygame, sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("Drawing Rectangles")

position = [300, 250,100, 100]
vel = [2, 1]

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    # create a new surface with the same size as the screen
    # and fill it with the background color
    background = pygame.Surface(screen.get_size())
    background.fill((0, 0, 200))

    #move the rectangle
    position[0] += vel[0]
    position[1] += vel[1]
    if position[0] > 500 or position[0] < 0:
        vel[0] = -vel[0]
    if position[1] > 400 or position[1] < 0:
        vel[1] = -vel[1]

    #draw the rectangle on the background surface
    color = 255, 255, 0
    width = 0
    pygame.draw.rect(background, color, position, width)

    #copy the background surface to the screen
    screen.blit(background, (0, 0))

    pygame.display.update()
    pygame.time.delay(10)
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-9-28 07:09

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表