Pygame 移动物体/图像重复自身

Pygame moving object /image repeat itself

我正在使用 pygame 构建一个简单的游戏,这个游戏的功能是控制图像并使其移动 up/down left/right 但是我遇到了这个问题,向下或向旁边移动时图像会重复出现

import pygame
pygame.init()
display_width = 1080
display_height = 1080

screen = pygame.display.set_mode((display_width,display_height))

Clock = pygame.time.Clock()
pygame.display.set_caption('DEMO')
black=(0,0,0)
white=(255,255,255)
red=(255,0,0)
green=(0,255,0)
blue=(0,0,255)
screen.fill(white)

face=pygame.image.load('H:\brain.jpg')

 def brain(x,y):
     screen.blit(face,(x,y))

 x1 =(display_width*0.5)
 y1 =(display_height*0.5)
  x_change =0
   y_change =0
  gameExit = False

while not gameExit:
for event in pygame.event.get():

    if event.type == pygame.QUIT:
        gameExit = True

    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            x_change = -5
        elif  event.key == pygame.K_RIGHT:
            x_change = 5
        elif event.key == pygame.K_DOWN:
            y_change = 5
        elif event.key == pygame.K_UP:
            y_change = -5
    if event.type == pygame.KEYUP:
        if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
            x_change = 0
    if event.type == pygame.KEYUP:
        if event.key == pygame.K_DOWN or event.key == pygame.K_UP:
            y_change = 0

x1 += x_change
y1 += y_change
print(event)
brain(x1,y1)
pygame.display.update()
Clock.tick(100)
pygame.quit()
quit()

您需要清空旧图像,并绘制新图像。您看到的是残留物:之前图像中没有被新图像的白色(背景色)覆盖的部分。

处理此问题的一种简单方法是扩展绘制的图像以包括至少与动作大小一样大的白色边框。

您必须在 while 循环的每次迭代中 blit 背景:

 while True:
     for event in pygame.event.get():

         #get keyboard input


     screen.fill((255, 255, 255)) #or, you can draw a background image

     x1 += x_change
     y1 += y_change
     print(event)
     brain(x1,y1)
     pygame.display.update()