You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Pygame制作Pong游戏时矩形在背景图上移动留下拖影的问题

我正在制作一款Pong游戏,运行时球对象移动时会留下拖影,我想知道如何解决该问题,任何帮助都将不胜感激,提前致谢。以下是我的代码:

import sys
import pygame
pygame.init()
clock = pygame.time.Clock()
# screen setup
screen_width = 1200
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
background = pygame.image.load("spacebackground.png").convert_alpha()
pygame.mouse.set_visible(False)
pygame.display.set_caption('pong')


# set up player and opponent and ball rect
player = pygame.Rect(screen_width - 20,screen_height/2 - 70,10,140)
opponent = pygame.Rect(10,screen_height/2 - 70,10,140 )
ball = pygame.Rect(screen_width/2-15, screen_height/2 - 15,30, 30)

ball_speed_x = 7
ball_speed_y = 7
# defining clock and colour
red = (0,0,0)

clock = pygame.time.Clock()

while True:

    pygame.display.update(ball)
    pygame.display.flip()
    screen.blit(background, (0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    ball.x += ball_speed_x
    ball.y += ball_speed_y
    # Drawing the rects
    pygame.draw.rect(background, red, player)
    pygame.draw.rect(background, red, opponent)
    pygame.draw.ellipse(background, red, ball)
    pygame.display.update(ball)

    clock.tick(60)

拖影由以下代码逻辑错误导致:

  • 屏幕刷新顺序错误:先执行刷新操作再绘制新一帧内容,上一帧的显示内容没有被及时覆盖
  • 直接在原始背景素材上绘制元素:每次绘制都会永久修改background对象,导致后续调用blit时自带之前的绘制痕迹
  • 冗余刷新调用:同时混用pygame.display.flip()和多次pygame.display.update(),显示逻辑混乱

每一帧的正确执行顺序为:处理事件 → 更新元素坐标 → 贴背景覆盖上一帧内容 → 绘制当前帧元素 → 统一刷新屏幕 → 控制帧率,修正后完整代码如下:

import sys
import pygame
pygame.init()
clock = pygame.time.Clock()
# 屏幕设置
screen_width = 1200
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
# 保留原始背景图,不做修改
original_background = pygame.image.load("spacebackground.png").convert_alpha()
pygame.mouse.set_visible(False)
pygame.display.set_caption('pong')

# 初始化玩家、对手、球的矩形对象
player = pygame.Rect(screen_width - 20,screen_height/2 - 70,10,140)
opponent = pygame.Rect(10,screen_height/2 - 70,10,140 )
ball = pygame.Rect(screen_width/2-15, screen_height/2 - 15,30, 30)

ball_speed_x = 7
ball_speed_y = 7
red = (0,0,0)

while True:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    
    # 更新元素坐标
    ball.x += ball_speed_x
    ball.y += ball_speed_y

    # 贴背景覆盖上一帧内容
    screen.blit(original_background, (0, 0))
    # 在screen上绘制当前帧所有元素,不修改原始背景图
    pygame.draw.rect(screen, red, player)
    pygame.draw.rect(screen, red, opponent)
    pygame.draw.ellipse(screen, red, ball)

    # 统一刷新屏幕
    pygame.display.flip()

    # 控制帧率
    clock.tick(60)

内容的提问来源于stack exchange,提问作者ED t

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 00:18:01