Pygame 角色移动

Pygame character movement

我正在用 pygame 练习,但不知道如何让我的角色动起来。例如,如果我放置 'print' 语句,它会起作用,并在我按 'a' 时打印我想要的任何内容,但角色会留在他的位置上。我对类知之甚少,所以我认为这是问题所在

import pygame

pygame.init()
pygame.font.init() 
width, height = 924, 500
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Priest Beast')
clock = pygame.time.Clock()

BG = pygame.transform.scale2x(pygame.image.load('art/background.png')).convert_alpha()

music = pygame.mixer.Sound('sound/music.mp3')

class Player(pygame.sprite.Sprite):

    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.transform.scale2x(pygame.image.load('art/Player.png')).convert_alpha()
        self.rect = self.image.get_rect(center = (800, 300))
        self.x = x 
        self.y = y

    def move(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_a]:
            self.rect.x += 5

    def update(self):
        self.move()
            

#Loop and exit
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
   
    # Sounds
    music.play()
    music.set_volume(0.1)

    screen.blit(BG, (0, 0))

    player = pygame.sprite.GroupSingle()
    player.add(Player(800,200))

    #Update everything
    player.draw(screen)
    player.update()
    pygame.display.update()
    clock.tick(60)

您不断地在初始位置重新创建对象。您需要在应用程序循环之前创建 SpriteGroup

player = pygame.sprite.GroupSingle() # <-- INSERT
player.add(Player(800,200))

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

    screen.blit(BG, (0, 0))

    # DELETE
    # player = pygame.sprite.GroupSingle()
    # player.add(Player(800,200))

    # [...]