当我移动雪碧时,它会留下重复的内容

2024-04-20 13:33:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在网上学习,并使用各种教程在pygame窗口中绘制精灵。我现在试图让它在屏幕上移动一定数量的像素(取决于掷骰子返回的数字)

def diceroll():
    roll = random.randint(1, 6)
    print(roll)
    playerCar.move_piece_hoz((WIDTH / 13) * roll)


def main():
    run = True
    clock = pygame.time.Clock()

    while run:  # a while loop to run the game out of, it sets the clock speed and also consistently checks if
        # user ever quits
        clock.tick(FPS)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                diceroll()

        # checks any updates to the array of sprites
        all_sprites_list.update()

        # draws all our sprites in their respective positions
        all_sprites_list.draw(screen)

        # Refresh Screen
        pygame.display.flip()


main()

这里有相关的代码,我基本上想要它,所以每当玩家按下鼠标左键时,它就会调用骰子滚动功能,然后在棋盘上随机选取一些棋子。然而,每当我按下鼠标左键时,精灵基本上保持在它的当前位置,并在它应该去的地方绘制一个新的副本。我附上了一张图片,以防对我的意思有任何混淆here。雪碧是红场

如果我在main()函数之外单独使用:diceroll()手动调用该函数。精灵被正确地重新绘制,没有问题,也没有留下副本,但是这样我只能调用它一次,这不是我需要的

多谢各位


1条回答
网友
1楼 · 发布于 2024-04-20 13:33:16

screen是一个^{}对象。 在曲面上绘制某物时,存储在曲面对象中的像素数据将发生更改。在每一帧中重新绘制整个场景。您需要在每一帧中清除显示或绘制背景:

def main():
    run = True
    clock = pygame.time.Clock()

    while run:  # a while loop to run the game out of, it sets the clock speed and also consistently checks if
        # user ever quits
        clock.tick(FPS)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                diceroll()

        screen.fill(0) # < - this is missing

        # checks any updates to the array of sprites
        all_sprites_list.update()

        # draws all our sprites in their respective positions
        all_sprites_list.draw(screen)

        # Refresh Screen
        pygame.display.flip()


main()

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

  • 通过调用^{}^{}来处理事件
  • 根据输入事件和时间(分别为帧)更新游戏状态和对象位置
  • 清除整个显示或绘制背景
  • 绘制整个场景(blit所有对象)
  • 通过调用^{}^{}更新显示
  • 使用^{}限制每秒帧数以限制CPU使用

相关问题 更多 >