简体   繁体   English

无法在 pygame 中移动角色

[英]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.我试图在 pygame 中移动我的角色(宇宙飞船),但到目前为止我所做的没有奏效。 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.当您创建 class 的实例时,将执行构造函数并初始化 object 属性。 Hence, you continuously create a new player in his starting position.因此,您在他的起始 position 中不断创建一个新player You are drawing the player at the same position over and over again.您一遍又一遍地在同一个 position 处绘制玩家。 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.实际上玩家正在移动,但您永远看不到移动,因为在起始 position 会立即创建一个新玩家来替换第一个玩家。
You must create the instance object of the Player class before the application loop instead of in the application loop:您必须在应用程序循环之前而不是应用程序循环中创建Player class 的实例 object:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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