简体   繁体   中英

Can't move character in pygame

I am trying to move my character (a spaceship) in pygame but what I have done so far has not worked. Everything runs and it displays the character but it does not move when I press the keys.

class Player:
    vel = 10
    x = width/2-PLAYER.get_width()/2
    y = 450

    def __init__(self, width, height):
        self.width = width
        self.height = height

    def draw_player(self, win):
        win.blit(PLAYER, (self.x, self.y))


def main():
    running = True
    clock = pygame.time.Clock()
    fps = 30
    while running:
        bg = Background(0, 0)
        bg.draw_background()
        sc = Score(f"Score: {score}", WHITE)
        sc.draw_score()
        player = Player(50, 50)
        player.draw_player(win)
        pygame.display.set_caption("Space Invaders Game")

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        keys = pygame.key.get_pressed()
        if keys[pygame.K_RIGHT]:
            player.x += 1
        if keys[pygame.K_LEFT]:
            player.x -= 1

        pygame.display.flip()
        clock.tick(fps)


if __name__ == "__main__":
    main()

When you create an instance of a class, the constructor is executed and the object attributes are initialized. Hence, you continuously create a new player in his starting position. You are drawing the player at the same position over and over again. Actually the player is moving, but you never see the movement because a new player is immediately created at the starting position to replace the first player.
You must create the instance object of the Player class before the application loop instead of in the application loop:

def main():

    player = Player(50, 50)       # <--- ADD

    running = True
    clock = pygame.time.Clock()
    fps = 30
    while running:
        bg = Background(0, 0)
        bg.draw_background()
        sc = Score(f"Score: {score}", WHITE)
        sc.draw_score()

        # player = Player(50, 50)    <--- REMOVE
        
        player.draw_player(win)
        pygame.display.set_caption("Space Invaders Game")

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        keys = pygame.key.get_pressed()
        if keys[pygame.K_RIGHT]:
            player.x += 1
        if keys[pygame.K_LEFT]:
            player.x -= 1

        pygame.display.flip()
        clock.tick(fps)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM