微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尽管我已经按下了它,但我的密钥不起作用 Python Pygame

如何解决尽管我已经按下了它,但我的密钥不起作用 Python Pygame

    import pygame,sys
    
    pygame.init()
    pygame.display.set_caption("test 1")
    
    #main Variables
    clock = pygame.time.Clock()
    window_size = (700,700)
    screen = pygame.display.set_mode(window_size,32)
    
    #player variables
    playerx = 150
    playery = -250
    player_location = [playerx,playery]
    player_image = pygame.image.load("player/player.png").convert_alpha()
    player_rect = player_image.get_rect(center = (80,50))
    
    #button variables
    move_right = False
    move_left = False
    move_up = False
    move_down = False
    
    while True:
        screen.fill((4,124,32))
        screen.blit(player_image,player_location,player_rect)
    
        if move_right == True:
            playerx += 4
        if move_left == True:
            playerx -= 4
        if move_up == True:
            playery -= 4
        if move_down == True:
             playery += 4
    
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_d:
                    move_right = True
                if event.key == pygame.K_a:
                    move_left = True
                if event.key == pygame.K_w:
                    move_up = True
                if event.key == pygame.K_s:
                    move_down = True
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_d:
                    move_right = False
                if event.key == pygame.K_a:
                    move_left = False
                if event.key == pygame.K_w:
                    move_up = False
                if event.key == pygame.K_s:
                    move_down = False
    
        pygame.display.update()
        clock.tick(120)

我无法让它工作。我按下了按钮,但它不会上升或下降。当我没有为播放器使用矩形时,它运行良好。我想要这样我也可以在 y 轴上上下移动角色。我刚开始学习如何使用 PyGame,请帮助我,谢谢。

解决方法

当您移动播放器时,您会更改 playerxplayery 变量。但是,玩家 id 绘制到存储在 player_location 中的位置。您必须在绘制播放器之前更新 player_location

while True:
    screen.fill((4,124,32))
    player_location = [playerx,playery]
    screen.blit(player_image,player_location,player_rect)

    # [...]

请注意,您根本不需要 player_location。在 [playerx,playery] 处绘制玩家:

while True:
    screen.fill((4,32))
    screen.blit(player_image,[playerx,playery],player_rect)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。