刷新 Pygame window 将 Sprite 之前的位置显示为背景屏幕的一部分

Refreshed Pygame window shows Sprite's previous location as a part of the background screen

下面我有一个格斗游戏,一旦玩家被推出屏幕,游戏就会结束并可以选择重新开始。我的问题是,在重新开始后,无论获胜者站在哪里,克隆(或图章、图像、幽灵或 blit)都会永久保留(即使在多个 rounds/deaths 之后)。我需要修复什么才能正确地重新填充旧位置的背景?我试过在几个地方添加 screen.fill() 无济于事。

class Game:
    def __init__(self):
        self.all_sprites = pg.sprite.Group()
        self.screen = pg.display.set_mode((WIDTH, HEIGHT))
        self.playing = True


    def new(self):
        # RESET PLAYERS
        self.player1 = Player(self, 2, FLOOR, RED)
        self.player2 = Player(self, 7, FLOOR, BLUE)
        return z.run()

    def run(self):
        # LOOP
        while self.playing:
            self.events()
            self.update()
            self.draw()

    def events(self):
        # INPUT
        for event in pg.event.get():
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_ESCAPE:
                    pg.quit()
                    sys.exit()

                # MOVE
                if event.key == pg.K_a:
                    self.player1.move(dx=-1)
                if event.key == pg.K_RIGHT:
                    self.player2.move(dx=1)
        # DIE
        if z.player1.x < 0:
            return z.encore()


    def update(self):
        # CHANGE INTERNAL PLAYER DATA
        self.all_sprites.update()

    def draw(self):
        # CHANGE PLAYER PHENOMENA
        z.screen.fill(BACKGROUND)
        z.all_sprites.draw(z.screen)
        pg.display.flip()

def encore(self):
        # PLAY AGAIN?
        curtain = True
        while curtain:
            z.screen.fill(RED)
            for event in pg.event.get():
                if event.type == pg.KEYDOWN:
                    return z.new()    

z = Game()
z.new()

在我的播放器下方 class:

    class Player(pg.sprite.Sprite):
    def __init__(self, game, x, y, color):
        self.groups = game.all_sprites
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        self.image = pg.Surface((TILESIZE, TILESIZE))
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.x = x
        self.y = y

    def move(self, dx=0):
        self.x += dx

    def update(self):
        self.rect.x = int(self.x * TILESIZE)
        self.rect.y = int(self.y * TILESIZE)

编程新手;希望包含所有这些代码并不过分;信不信由你,这实际上花了我很长时间才将它减少到 100 行以下。谢谢您的宝贵时间!

发生这种情况是因为 all_sprites 变量在每个游戏实例后都没有被重置。因此,即使没有连接到 Player,上一个游戏的精灵仍在绘制。这个可以用Group.empty()函数来解决,比如:

def encore(self):
    # PLAY AGAIN?
    curtain = True
    while curtain:
        z.screen.fill(RED)
        for event in pg.event.get():
            if event.type == pg.KEYDOWN:
                self.all_sprites.empty()
                return z.new()

此外,z.screen.fill(RED) 似乎没有效果,因为在循环期间显示没有更新。这可以通过在

之后添加pg.display.flip()来解决。