首页 > 编程问答 >如何让精灵表动画在不同的键盘输入处加载?

如何让精灵表动画在不同的键盘输入处加载?

时间:2024-07-27 04:36:32浏览次数:11  
标签:python pygame

我正在用 python 制作一个基于冒险家的视频游戏。我让冒险家通过跳跃冷却时间四处移动,并且能够向左或向右移动。

import pygame
from sys import exit as end

import random
import time

pygame.init()

HEIGHT = 1200
WIDTH = 600
screen = pygame.display.set_mode((HEIGHT, WIDTH))
center_screen = (int(HEIGHT // 2), int(WIDTH // 2))

player_scale = 3

clock = pygame.time.Clock()
FPS = 60

# Land
class Land():
    def __init__(self, x, y, type):
        self.x = x
        self.y = y
        self.type = type

# Player
class Player(pygame.sprite.Sprite):
    def __init__(self, x, y, speed, grav):
        pygame.sprite.Sprite.__init__(self)
        self.x = x
        self.y = y

        self.jumping = False
        self.grav = grav

        self.moving_left = False
        self.moving_right = False

        self.speed = speed

        self.animation_list = []
        self.frame_index = 0
        self.time = pygame.time.get_ticks() 
        self.type = "idle"

        for i in range(3):       
            img = pygame.image.load(f"player/{self.type}/{i}.png")
            img = pygame.transform.scale(img, (int(img.get_width() * player_scale), int(img.get_height() * player_scale)))
            self.animation_list.append(img)

        self.player = img
        self.player_rect = img.get_rect(center = (self.x, self.y))

    def moving(self):
        dx = 0
        dy = 0

        self.jump_cooldown = 1

        if self.moving_left:
            dx = -self.speed
        if self.moving_right:
            dx = self.speed

        if self.jumping:
            self.jump_cooldown = 0
            dy = player.grav
            player.grav += 1
            if player.grav == 21:
                self.jumping = False
                self.jump_cooldown = 1
                self.type = "idle"

        self.player_rect.x += dx
        self.player_rect.y += dy

    def update_animation(self):
        ANIMATION_COOLDOWN = 200
        self.player = self.animation_list[self.frame_index]
        if pygame.time.get_ticks() - self.time > ANIMATION_COOLDOWN:
            self.time = pygame.time.get_ticks()
            self.frame_index += 1
        if self.frame_index == len(self.animation_list):
            self.frame_index = 0

    def draw(self):
        screen.blit(self.player, self.player_rect)

player = Player(center_screen[0], center_screen[1], 5, 1)

run = True
while True:
    screen.fill((1, 255, 122))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            end()

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                player.moving_left = True
            if event.key == pygame.K_d:
                player.moving_right = True

            if event.key == pygame.K_SPACE and player.jump_cooldown == 1:
                player.type = "jump"
                player.jumping = True
                player.grav = -20

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_a:
                player.moving_left = False
            if event.key == pygame.K_d:
                player.moving_right = False

                
    if run:
        player.moving()
        player.draw()
        player.update_animation()


    else:
        pass

    clock.tick(FPS)
    pygame.display.update()

现在我想做的是让 self.type 在我按空格键时切换到“跳跃”。| ||(用于跳转和空闲的字符精灵是3个imgs,全部名称为0.png、1.png和2.png)

我尝试将其更改为函数来更改它。还是没用。

I tried changing it into a function to change it. It still didn't work.


几乎实现了!在代码中正确更改了 self.type ,但需要根据当前的 self.type 重新加载动画。

以下是如何修改的代码以实现此目的的方法:

import pygame
from sys import exit as end

import random
import time

pygame.init()

HEIGHT = 1200
WIDTH = 600
screen = pygame.display.set_mode((HEIGHT, WIDTH))
center_screen = (int(HEIGHT // 2), int(WIDTH // 2))

player_scale = 3

clock = pygame.time.Clock()
FPS = 60

# Land
class Land():
    def __init__(self, x, y, type):
        self.x = x
        self.y = y
        self.type = type

# Player
class Player(pygame.sprite.Sprite):
    def __init__(self, x, y, speed, grav):
        pygame.sprite.Sprite.__init__(self)
        self.x = x
        self.y = y

        self.jumping = False
        self.grav = grav

        self.moving_left = False
        self.moving_right = False

        self.speed = speed

        self.animation_list = []
        self.frame_index = 0
        self.time = pygame.time.get_ticks() 
        self.type = "idle"
        self.load_animation() # 加载初始动画

        self.player = self.animation_list[0] # 初始化 self.player
        self.player_rect = self.player.get_rect(center = (self.x, self.y))

    def load_animation(self):
        """根据 self.type 加载动画列表"""
        self.animation_list.clear() # 清除之前的动画列表
        for i in range(3):       
            img = pygame.image.load(f"player/{self.type}/{i}.png")
            img = pygame.transform.scale(img, (int(img.get_width() * player_scale), int(img.get_height() * player_scale)))
            self.animation_list.append(img)

    def moving(self):
        dx = 0
        dy = 0

        self.jump_cooldown = 1

        if self.moving_left:
            dx = -self.speed
        if self.moving_right:
            dx = self.speed

        if self.jumping:
            self.jump_cooldown = 0
            dy = self.grav
            self.grav += 1
            if self.grav == 21:
                self.jumping = False
                self.jump_cooldown = 1
                self.type = "idle"
                self.load_animation() # 착지 시 애니메이션 다시 로드

        self.player_rect.x += dx
        self.player_rect.y += dy

    def update_animation(self):
        ANIMATION_COOLDOWN = 200
        self.player = self.animation_list[self.frame_index]
        if pygame.time.get_ticks() - self.time > ANIMATION_COOLDOWN:
            self.time = pygame.time.get_ticks()
            self.frame_index += 1
        if self.frame_index == len(self.animation_list):
            self.frame_index = 0

    def draw(self):
        screen.blit(self.player, self.player_rect)

player = Player(center_screen[0], center_screen[1], 5, 1)

run = True
while True:
    screen.fill((1, 255, 122))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            end()

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                player.moving_left = True
            if event.key == pygame.K_d:
                player.moving_right = True

            if event.key == pygame.K_SPACE and player.jump_cooldown == 1:
                player.type = "jump"
                player.load_animation() # 加载跳跃动画
                player.jumping = True
                player.grav = -20

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_a:
                player.moving_left = False
            if event.key == pygame.K_d:
                player.moving_right = False


    if run:
        player.moving()
        player.draw()
        player.update_animation()


    else:
        pass

    clock.tick(FPS)
    pygame.display.update()

更改说明:

  1. load_animation 函数: 此函数现在清除之前的 animation_list 并根据当前的 self.type 加载新的动画帧。
  2. __init__ 中加载初始动画: 我们在 __init__ 中调用 self.load_animation() 来加载玩家的默认“空闲”动画。
  3. 在更改 self.type 后重新加载动画: moving 函数中,当玩家着陆并将 self.type 设置回“空闲”时,以及在按下空格键并将 self.type 设置为“跳跃”时,我们调用 self.load_animation()

现在,的代码应该在按下空格键时正确切换到跳跃动画,并在玩家着陆时切换回空闲动画。

标签:python,pygame
From: 78799760

相关文章

  • 使用类型提示将 Python 转换为 Cython
    类型提示现在在Python3.5版本中可用。在规范(PEP484)中,目标(和非目标)被明确暴露:#RationaleandGoals此PEP旨在为类型注释提供标准语法,开放Python代码更容易静态分析和重构、潜在的运行时类型检查以及(也许在某些情况下)利用类型信息生成代码。......
  • 在 Python 类型提示中区分 PySpark 和 Pandas DataFrame (PyCharm)
    在PyCharm中,如果使用apyspark.sql.DataFrame代替pandas.DataFrame,类型提示似乎不会触发警告,反之亦然。例如以下代码根本不会生成任何警告:frompyspark.sqlimportDataFrameasSparkDataFramefrompandasimportDataFrameasPandasDataFramedef......
  • 如何在Python中继承类型提示?
    所以我的问题是,当我有一个A类型的类来做事情并且我使用这些函数作为subclass(B)时,它们仍然是类A的类型,并且不接受我的类B对象作为参数或作为函数签名。我的问题简化了:fromtypingimportTypeVar,Generic,CallableT=TypeVar('T'......
  • Python - 如何传递类对象的函数参数类型(打字)
    我想python3.7附带了(不确定),不仅可以将变量名传递给函数,还可以传递变量的类型。我想知道的是是否有可能传递特定类的类型。以同样的方式传递:deffoo_func(i:int)->None:pass如果我有一个类,让我们说:classfoo_class(object):pass我如何转换fo......
  • 使用 Python 构建简单 REST API
    使用Python构建简单RESTAPI1.概述本技术文档旨在指导开发者使用Python框架Flask构建一个基本的RESTAPI。通过学习本指南,您将掌握创建、读取、更新和删除(CRUD)操作的基本知识,并能够使用Python构建自己的API。2.安装依赖首先,您需要确保已安装Python和Flask......
  • Python——Pandas(第二讲)
    文章目录变量类型的转换Pandas支持的数据类型在不同数据类型间转换建立索引新建数据框时建立索引读入数据时建立索引指定某列为索引列将索引还原变量列引用和修改索引引用索引修改索引修改索引名修改索引值更新索引Series的索引和切片DataFrame的索引和切片选择列按......
  • 基于Python+Django的红色文化研学网站设计与实现
    ......
  • 【python】对网站进行请求-初识
    python实现对网站进行请求代码如下importrequestsdefget_data(url,headers=None,params=None,timeout=10):try:res=requests.get(url,headers=headers,params=params,timeout=timeout)res.raise_for_status()returnres.text......
  • 【python】Django初识-从未有如此美妙的开局
    Django初识python、Django安装与验证python安装Python官网https://www.python.org/Django安装pipinstallDjango验证python是否安装成功python--version验证Django是否安装成功python3-mdjango--version创建第一个Django项目项目创建与服务器启动打开cmd,输......
  • Python虚拟环境创建、激活、使用,项目依赖导出、安装requestments.txt
    Python虚拟环境通过命令行终端创建python虚拟环境:新建一个文件夹,可以专门用来存放虚拟环境,这里在D盘创建Python_Virtual_Environment_test文件夹然后在这里输入cmd按回车键进入命令行终端此时打开的位置就是当前的路径,当然也可以 cd一步步进入到目标路径创建环境......