如何使用pygame基于按钮点击显示不同的图像?

时间:2017-12-06 23:55:38

标签: python pygame

我正在编写一个学校项目的游戏。我编写了它,以便我使用wasd来移动我的角色。我有四个不同的图像:一个面向左,一个面向右,一个面向前,一个面向后。我需要根据我按下的按钮将显示的图像更改为字符。我有一个定义每个图像的函数,我尝试根据按下的按钮调用该函数,然后当按钮重新启动时,我想再次显示正面图像。它所做的只是每按一次,相应的面对图像显示,消失,然后显示正面图像,然后很快消失。这只是实际处理角色的部分:

howieImg = pygame.image.load('howie front.PNG')
howieImg_back = pygame.image.load('howie back.PNG')
howieImg_left = pygame.image.load('howie left.PNG')
howieImg_right = pygame.image.load('howie right.PNG')

def howie(x, y):
gameDisplay.blit(howieImg, (x, y))
def howie_back(x, y):
gameDisplay.blit(howieImg_back, (x, y))
def howie_left(x, y):
gameDisplay.blit(howieImg_left, (x, y))
def howie_right(x, y):
gameDisplay.blit(howieImg_right, (x, y))

while not gameExit:
        startx = (display_width/2)
        starty = (display_height/2)
        thing_width = 25
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w and y > 0:
                    howie_back(x, y)
                    y_change = -3
                if event.key == pygame.K_s and y < display_height - character_height:
                    howie(x, y)
                    y_change = 3
                if event.key == pygame.K_a and x > 0:
                    howie_left(x, y)
                    x_change = -3
                if event.key == pygame.K_d and x < display_width - character_width:
                    howie_right(x, y)
                    x_change = 3                       
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_w or event.key == pygame.K_s:
                    howie(x, y)
                    y_change = 0
                if event.key == pygame.K_a or event.key == pygame.K_d:
                    howie(x, y)
                    x_change = 0

        x += x_change
        y += y_change

        if x > display_width - character_width or x < 0:
            x_change = 0
        if y > display_height - character_height or y < 0:
            y_change = 0

        clock.tick(60)
        gameDisplay.blit(background1Img, [0, 0])
        button1()
        howie(x, y)
        things_collected(collected)
        pygame.display.update()

1 个答案:

答案 0 :(得分:0)

我将摆脱这些功能,只将当前图像存储在变量中(以下示例中为function line_break_for_posts_filter($title){ if ( is_singular() ) { return str_replace(' | ', '<br />', $title); } else { return str_replace(' | ', '', $title); } } add_filter('the_title', 'line_break_for_posts_filter'); )。当用户按下其中一个键时,您可以简单地将其中一个图像指定给当前图像变量。

howieImg