执剑女角色版本1之造型切换,动作游戏基础 _pygame Action Game Foundation

"""执剑女角色版本1之造型切换,动作游戏基础,本版本只是实现动作切换.,按a或d键实现方向的改变,按空格键实现重击造型变换,按鼠标键实现普通攻击。
   完整的角色为,按鼠标键发普通攻击,会向前位移,按空格键为跃起,然后显示重击效果,并且落地时会有火花等。
"""

import time
import pygame
from pygame.locals import *

class Actor:
    def __init__(self,right_frames,left_frames):
        self.right_frames = right_frames
        self.left_frames = left_frames
        self.frames = [right_frames,left_frames]
        self.heading = 0        # 为0表示朝向为右,使用初始是面向右系列造型
        self.index = 0          # 初始状态系列造型中的索引为0的造型
        self.image = self.frames[self.heading][self.index] # 初始造型
        self.rect = self.image.get_rect()
        self.rect.center = width//2,height//2
        self.status = "stand"    # 初始状态为站立
        self.interval = 0.05     # 帧切换间隔时间
        self.start_time = time.time()

    def update(self):
        if time.time() - self.start_time > self.interval: # 超时则换造型
            if self.status == "attack":
                if self.index < 4 :
                    self.index += 1
                    
                else:
                    self.status = "stand"
                    self.index = 0

            if self.status == "strike":
                if self.index < 10:
                    self.index += 1
                else:
                    self.status = "stand"
                    self.index = 0
            self.image = self.frames[self.heading][self.index]
            self.rect = self.image.get_rect()
            self.rect.center = width//2,height//2             
            self.start_time = time.time()


if __name__ == "__main__":

    width,height = 960,720

    screen = pygame.display.set_mode((width,height))
    pygame.display.set_caption("执剑女角色版本1之造型切换,动作游戏基础 www.lixingqiu.com")

    right_frames = [pygame.image.load(f"right_frames/costume{index}.png") for index in range(5)]
    right_frames.extend([pygame.image.load(f"right_frames/strike down{index}.png") for index in range(6)])

    left_frames = [pygame.transform.flip(image,True,False) for image in right_frames]

    girl = Actor(right_frames,left_frames)
       
    clock = pygame.time.Clock()
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == QUIT:running = False
            if event.type == KEYDOWN:
                if event.key == K_a:girl.heading = 1  # 向左
                if event.key == K_d: girl.heading = 0 # 向右
                if event.key == K_SPACE:
                    girl.status = "strike"
                    girl.index = 6
                    girl.start_time = time.time()
            if event.type == MOUSEBUTTONDOWN:
                    girl.status = "attack"
                    girl.index = 0
                    girl.start_time = time.time()

        girl.update()
        
        screen.fill((0,0,0))
        screen.blit(girl.image,girl.rect)
        pygame.display.update()
        clock.tick(60)

    pygame.quit()

Action Game Foundation