如何检测 Python Pygame 中的先前运动?

How to detect the previous movement in Python Pygame?

我想检测角色之前的动作以显示与之前动作相关的动画。例如,如果先前的运动是 'move_right',当角色停止时,我想显示一个向右转的图像。左边也一样。你能帮帮我吗?

编辑

我把相关的部分代码给你,希望对你有帮助。

import pygame
import constants
import time


clock = pygame.time.Clock()



class Player(pygame.sprite.Sprite):

    def __init__(self):
        super().__init__()
        self.velocity = 5
        self.HeatBox = constants.S_PLAYER_HEATBOX
        self.rect = self.HeatBox.get_rect()
        self.rect.x = 500
        self.rect.y = 300
        self.WalkCount = 0

    def move_right(self):
        self.rect.x += self.velocity

    def move_left(self):
        self.rect.x -= self.velocity

    def move_up(self):
        self.rect.y -= self.velocity

    def move_down(self):
        self.rect.y += self.velocity


def draw_game():

    global SURFACE_MAIN, Player

    SURFACE_MAIN.fill(constants.COLOR_DEFAULT_BG)

    SURFACE_MAIN.blit(constants.S_BACKGROUND, (0, 0))

    SURFACE_MAIN.blit(constants.S_PLAYER_HEATBOX, game.player.rect)

    if game.player.WalkCount + 1 >= 40:
         game.player.WalkCount = 0

    if game.pressed.get(pygame.K_RIGHT): 

    SURFACE_MAIN.blit(constants.S_PLAYER_W_RIGHT[game.player.WalkCount//10], 
    game.player.rect)
    game.player.move_right()

    if game.pressed.get(pygame.K_LEFT):

    SURFACE_MAIN.blit(constants.S_PLAYER_W_LEFT[game.player.WalkCount//10], 
    game.player.rect)  
    game.player.move_left()

    if game.pressed.get(pygame.K_UP):
        game.player.move_up()

    if game.pressed.get(pygame.K_DOWN):
        game.player.move_down()


    pygame.display.flip()



def game_main_loop():

    game_quit = False

    while not game_quit:

        clock.tick(60)

        events_list = pygame.event.get()

        for event in events_list:
            if event.type == pygame.QUIT:
                game_quit = True

            elif event.type == pygame.KEYDOWN:
                game.pressed[event.key] = True
            elif event.type == pygame.KEYUP:
                game.pressed[event.key] = False

        draw_game()

    pygame.quit()
    exit()


def game_initialize():

    global SURFACE_MAIN, Player

    pygame.init()

    pygame.display.set_caption("RogueLike")
    SURFACE_MAIN = pygame.display.set_mode((constants.GAME_WIDTH, 
    constants.GAME_HEIGHT))

class gameplay:

    def __init__(self):
        self.player = Player()
        self.pressed = {}

game = gameplay()

if __name__ == '__main__':
game_initialize()
game_main_loop()

在一个名为 constants.py 的文件中我有我所有的精灵

S_BACKGROUND = pygame.image.load('Sprites/Map/Map_Test_3.png')                              
S_PLAYER_HEATBOX = pygame.image.load('Sprites/Heros/Knight/HeatBox.png')
S_PLAYER_RIGHT = 
             [pygame.image.load('Sprites/Heros/Knight/Right/sprite_0.png'),
              pygame.image.load('Sprites/Heros/Knight/Right/sprite_1.png'),
              pygame.image.load('Sprites/Heros/Knight/Right/sprite_2.png'),
              pygame.image.load('Sprites/Heros/Knight/Right/sprite_3.png')]
S_PLAYER_LEFT = 
             [pygame.image.load('Sprites/Heros/Knight/Left/sprite_0.png'),
              pygame.image.load('Sprites/Heros/Knight/Left/sprite_1.png'),
              pygame.image.load('Sprites/Heros/Knight/Left/sprite_2.png'),
              pygame.image.load('Sprites/Heros/Knight/Left/sprite_3.png')]
S_PLAYER_W_RIGHT = 
             [pygame.image.load('Sprites/Heros/Knight/W_Right/sprite_0.png'),
              pygame.image.load('Sprites/Heros/Knight/W_Right/sprite_1.png'),
              pygame.image.load('Sprites/Heros/Knight/W_Right/sprite_2.png'),
              pygame.image.load('Sprites/Heros/Knight/W_Right/sprite_3.png')]
S_PLAYER_W_LEFT = 
             [pygame.image.load('Sprites/Heros/Knight/W_Left/sprite_0.png'),
              pygame.image.load('Sprites/Heros/Knight/W_Left/sprite_1.png'),
              pygame.image.load('Sprites/Heros/Knight/W_Left/sprite_2.png'),
              pygame.image.load('Sprites/Heros/Knight/W_Left/sprite_3.png')]

# Left : means sprites turned to the right when the character is stopped.
# Right : means sprites turned to the left when the character is stopped.
# W_Left : means sprites turned to theleft when the character is walking.
# W_Right : means sprites turned to the right when the character is walking.
# S_ : means Sprites

我对你的问题的理解是,你希望 Player 精灵 "face" 移动到最近一次移动的方向。例如,如果玩家最后向左移动,精灵应该显示为面向左。

通过将 Sprite image 值设置为正确的位图,这种事情很容易实现。没有解释,所以我不太明白 "HeatBox" 代表什么,所以我会忽略它。 imagerectPyGame Sprite Class 中都是特殊的。 sprite 库代码使用它们来绘制和检测 sprite 的碰撞。最好将另一个变量名用于其他目的。

class Player(pygame.sprite.Sprite):
    DIR_LEFT = 0 
    DIR_RIGHT= 1       # This might be better as an Enumerated Type
    DIR_UP   = 2
    DIR_DOWN = 3

    def __init__(self):
        super().__init__()
        self.velocity  = 5
        self.heat_box  = constants.S_PLAYER_HEATBOX
        self.heat_rect = self.HeatBox.get_rect()
        self.image     = S_PLAYER_LEFT[0]             # Initially face left
        self.rect      = self.image.get_rect()
        self.rect.x    = 500
        self.rect.y    = 300
        self.walk_count= 0                            # animation frame count
        self.last_dir  = Player.DIR_LEFT              # direction last walked

    def move_right(self):
        if ( self.last_dir != Player.DIR_RIGHT ):     # changed direction?
            self.walk_count = -1                      # so next-frame is 0
            self.last_dir = Player.DIR_RIGHT          # now face right
        # continue walking right
        self.rect.x += self.velocity
        self.walk_count += 1
        if ( walk_count >= len( S_PLAYER_W_RIGHT ) ): # loop the animation
            self.walk_count = 0
        self.image = S_PLAYER_W_RIGHT[ self.walk_count ]

    def move_left(self):
        if ( self.last_dir != Player.DIR_LEFT ):      # changed direction?
            self.walk_count = -1                      # so next-frame is 0
            self.last_dir = Player.DIR_LEFT           # now face left
        # continue walking left
        self.rect.x -= self.velocity
        self.walk_count += 1
        if ( walk_count >= len( S_PLAYER_W_LEFT ) ):  # loop the animation
            self.walk_count = 0
        self.image = S_PLAYER_W_LEFT[ self.walk_count ]

    # TODO: Much the same for Up/Down too

当方向改变时,动画循环计数器(walk_count)被重置,并且新方向的位图分配到Player.image,并记住在Player.last_dir

所以基本上 Player class 会记住精灵面向的方向,以及之前绘制的动画帧。如果玩家继续沿同一方向移动,则每次移动都会逐步显示动画。如果方向已更改,则动画会重置为另一组方向位图。

要将您的播放器绘制到屏幕上,也将其添加到 sprite group, and tell the group to draw itself in your main loop. As a bonus, you can then use all the sprite-group collision 函数中。

player_group = pygame.sprite.GroupSingle()
player_group.add( Player() )                  # create the player

...

# main loop
player_group.draw( screen )

注意:CamelCase 变量名称更改为 lower_case 以匹配 PEP-8 Guidelines.