学习 Python 之 Pygame 开发魂斗罗(三)

news2024/9/29 15:19:54

学习 Python 之 Pygame 开发魂斗罗(三)

    • 继续编写魂斗罗
      • 1. 角色站立
      • 2. 角色移动
      • 3. 角色跳跃
      • 4. 角色下落

继续编写魂斗罗

在上次的博客学习 Python 之 Pygame 开发魂斗罗(二)中,我们完成了角色的创建和更新,现在具体实现一下更新函数中的角色状态函数

下面是图片的素材

链接:https://pan.baidu.com/s/1X7tESkes_O6nbPxfpHD6hQ?pwd=hdly
提取码:hdly

1. 角色站立

在写角色站立函数时,先把其他状态函数注释了,方便测试
在这里插入图片描述

在角色站立函数中,首先设置当前角色的状态

站立时,其他状态都是False,只有isStanding = True

# 设置角色状态
self.isStanding = True
self.isWalking = False
self.isJumping = False
self.isSquating = False
self.isUp = False
self.isDown = False
self.isFiring = False

其次,修改人物的速度,站立时速度均为0

# 设置速度
self.ySpeed = 0
self.xSpeed = 0

再次,我们设置按键响应事件

# 按下A键
if keys[pygame.K_a]:
    # A按下,角色方向向左
    self.direction = Direction.LEFT
    # 改变角色的状态,角色进入移动状态
    self.state = State.WALK
    # 设置站立状态为False,移动状态为True
    self.isStanding = False
    self.isWalking = True
    # 向左移动,速度为负数,这样玩家的x坐标是减小的
    self.xSpeed = -PLAYER_X_SPEED
# 按下D键
elif keys[pygame.K_d]:
    # D按下,角色方向向右
    self.direction = Direction.RIGHT
    # 改变角色的状态,角色进入移动状态
    self.state = State.WALK
    # 设置站立状态为False,移动状态为True
    self.isStanding = False
    self.isWalking = True
    # 向右移动,速度为正数
    self.xSpeed = PLAYER_X_SPEED
# 按下k键
elif keys[pygame.K_k]:
    # K按下,角色进入跳跃状态,但是不会改变方向
    self.state = State.JUMP
    # 设置站立状态为False,跳跃状态为True
    # 不改变移动状态,因为移动的时候也可以跳跃
    self.isStanding = False
    self.isJumping = True
    # 设置速度,速度为负数,因为角色跳起后,要下落
    self.ySpeed = self.jumpSpeed
# 没有按下按键
else:
    # 没有按下按键,角色依然是站立状态
    self.state = State.STAND
    self.isStanding = True

# 按下w键
if keys[pygame.K_w]:
    # W按下,角色向上,改变方向状态
    self.isUp = True
    self.isStanding = True
    self.isDown = False
    self.isSquating = False
# 按下s键
elif keys[pygame.K_s]:
    # S按下,角色蹲下,改变方向状态,并且蹲下状态设置为True
    self.isUp = False
    self.isStanding = False
    self.isDown = True
    self.isSquating = True

完整的角色类

import pygame
from Constants import *


class PlayerOne(pygame.sprite.Sprite):

    def __init__(self, currentTime):
        pygame.sprite.Sprite.__init__(self)
        # 加载角色图片
        self.standRightImage = loadImage('../Image/Player/Player1/Right/stand.png')
        self.standLeftImage = loadImage('../Image/Player/Player1/Left/stand.png')
        self.upRightImage = loadImage('../Image/Player/Player1/Up/upRight(small).png')
        self.upLeftImage = loadImage('../Image/Player/Player1/Up/upLeft(small).png')
        self.downRightImage = loadImage('../Image/Player/Player1/Down/down.png')
        self.downLeftImage = loadImage('../Image/Player/Player1/Down/down.png', True)
        self.obliqueUpRightImages = [
            loadImage('../Image/Player/Player1/Up/rightUp1.png'),
            loadImage('../Image/Player/Player1/Up/rightUp2.png'),
            loadImage('../Image/Player/Player1/Up/rightUp3.png'),
        ]
        self.obliqueUpLeftImages = [
            loadImage('../Image/Player/Player1/Up/rightUp1.png', True),
            loadImage('../Image/Player/Player1/Up/rightUp2.png', True),
            loadImage('../Image/Player/Player1/Up/rightUp3.png', True),
        ]
        self.obliqueDownRightImages = [
            loadImage('../Image/Player/Player1/ObliqueDown/1.png'),
            loadImage('../Image/Player/Player1/ObliqueDown/2.png'),
            loadImage('../Image/Player/Player1/ObliqueDown/3.png'),
        ]
        self.obliqueDownLeftImages = [
            loadImage('../Image/Player/Player1/ObliqueDown/1.png', True),
            loadImage('../Image/Player/Player1/ObliqueDown/2.png', True),
            loadImage('../Image/Player/Player1/ObliqueDown/3.png', True),
        ]
        # 角色向右的全部图片
        self.rightImages = [
            loadImage('../Image/Player/Player1/Right/run1.png'),
            loadImage('../Image/Player/Player1/Right/run2.png'),
            loadImage('../Image/Player/Player1/Right/run3.png')
        ]
        # 角色向左的全部图片
        self.leftImages = [
            loadImage('../Image/Player/Player1/Left/run1.png'),
            loadImage('../Image/Player/Player1/Left/run2.png'),
            loadImage('../Image/Player/Player1/Left/run3.png')
        ]
        # 角色跳跃的全部图片
        self.upRightImages = [
            loadImage('../Image/Player/Player1/Jump/jump1.png'),
            loadImage('../Image/Player/Player1/Jump/jump2.png'),
            loadImage('../Image/Player/Player1/Jump/jump3.png'),
            loadImage('../Image/Player/Player1/Jump/jump4.png'),
        ]
        self.upLeftImages = [
            loadImage('../Image/Player/Player1/Jump/jump1.png', True),
            loadImage('../Image/Player/Player1/Jump/jump2.png', True),
            loadImage('../Image/Player/Player1/Jump/jump3.png', True),
            loadImage('../Image/Player/Player1/Jump/jump4.png', True),
        ]
        self.rightFireImages = [
            loadImage('../Image/Player/Player1/Right/fire1.png'),
            loadImage('../Image/Player/Player1/Right/fire2.png'),
            loadImage('../Image/Player/Player1/Right/fire3.png'),
        ]
        self.leftFireImages = [
            loadImage('../Image/Player/Player1/Right/fire1.png', True),
            loadImage('../Image/Player/Player1/Right/fire2.png', True),
            loadImage('../Image/Player/Player1/Right/fire3.png', True),
        ]
        # 角色左右移动下标
        self.imageIndex = 0
        # 角色跳跃下标
        self.upImageIndex = 0
        # 角色斜射下标
        self.obliqueImageIndex = 0
        # 上一次显示图片的时间
        self.runLastTimer = currentTime
        self.fireLastTimer = currentTime

        # 选择当前要显示的图片
        self.image = self.standRightImage
        # 获取图片的rect
        self.rect = self.image.get_rect()
        # 设置角色的状态
        self.state = State.STAND
        # 角色的方向
        self.direction = Direction.RIGHT
        # 速度
        self.xSpeed = PLAYER_X_SPEED
        self.ySpeed = 0
        self.jumpSpeed = -11
        # 人物当前的状态标志
        self.isStanding = False
        self.isWalking = False
        self.isJumping = True
        self.isSquating = False
        self.isFiring = False
        # 重力加速度
        self.gravity = 0.7

        self.isUp = False
        self.isDown = False

    def update(self, keys, currentTime):
        # 更新站或者走的状态
        # 根据状态响应按键
        if self.state == State.STAND:
            self.standing(keys, currentTime)
        # elif self.state == State.WALK:
        #   self.walking(keys, currentTime)
        # elif self.state == State.JUMP:
        #     self.jumping(keys, currentTime)
        # elif self.state == State.FALL:
        #     self.falling(keys, currentTime)

        # 更新位置
        # 记录前一次的位置坐标
        pre = self.rect.x
        self.rect.x += self.xSpeed
        self.rect.y += self.ySpeed
        # 如果x位置小于0了,就不能移动,防止人物跑到屏幕左边
        if self.rect.x <= 0:
            self.rect.x = pre

        # 更新动画
        # 跳跃状态
        if self.isJumping:
            # 根据方向
            if self.direction == Direction.RIGHT:
                # 方向向右,角色加载向右跳起的图片
                self.image = self.upRightImages[self.upImageIndex]
            else:
                # 否则,方向向左,角色加载向左跳起的图片
                self.image = self.upLeftImages[self.upImageIndex]

        # 角色蹲下
        if self.isSquating:
            if self.direction == Direction.RIGHT:
                # 加载向右蹲下的图片
                self.image = self.downRightImage
            else:
                # 加载向左蹲下的图片
                self.image = self.downLeftImage

        # 角色站着
        if self.isStanding:
            if self.direction == Direction.RIGHT:
                if self.isUp:
                    # 加载向右朝上的图片
                    self.image = self.upRightImage
                elif self.isDown:
                    # 加载向右蹲下的图片
                    self.image = self.downRightImage
                else:
                    # 加载向右站着的图片
                    self.image = self.standRightImage
            else:
                # 向左也是同样的效果
                if self.isUp:
                    self.image = self.upLeftImage
                elif self.isDown:
                    self.image = self.downLeftImage
                else:
                    self.image = self.standLeftImage

        # 角色移动
        if self.isWalking:
            if self.direction == Direction.RIGHT:
                if self.isUp:
                    # 加载斜右上的图片
                    self.image = self.obliqueUpRightImages[self.obliqueImageIndex]
                elif self.isDown:
                    # 加载斜右下的图片
                    self.image = self.obliqueDownRightImages[self.obliqueImageIndex]
                else:
                    # 加载向右移动的图片,根据开火状态是否加载向右开火移动的图片
                    if self.isFiring:
                        self.image = self.rightFireImages[self.imageIndex]
                    else:
                        self.image = self.rightImages[self.imageIndex]
            else:
                if self.isUp:
                    self.image = self.obliqueUpLeftImages[self.obliqueImageIndex]
                elif self.isDown:
                    self.image = self.obliqueDownLeftImages[self.obliqueImageIndex]
                else:
                    if self.isFiring:
                        self.image = self.leftFireImages[self.imageIndex]
                    else:
                        self.image = self.leftImages[self.imageIndex]

    def standing(self, keys, currentTime):
        """角色站立"""

        # 设置角色状态
        self.isStanding = True
        self.isWalking = False
        self.isJumping = False
        self.isSquating = False
        self.isUp = False
        self.isDown = False
        self.isFiring = False

        # 设置速度
        self.ySpeed = 0
        self.xSpeed = 0

        # 按下A键
        if keys[pygame.K_a]:
            # A按下,角色方向向左
            self.direction = Direction.LEFT
            # 改变角色的状态,角色进入移动状态
            self.state = State.WALK
            # 设置站立状态为False,移动状态为True
            self.isStanding = False
            self.isWalking = True
            # 向左移动,速度为负数,这样玩家的x坐标是减小的
            self.xSpeed = -PLAYER_X_SPEED
        # 按下D键
        elif keys[pygame.K_d]:
            # D按下,角色方向向右
            self.direction = Direction.RIGHT
            # 改变角色的状态,角色进入移动状态
            self.state = State.WALK
            # 设置站立状态为False,移动状态为True
            self.isStanding = False
            self.isWalking = True
            # 向右移动,速度为正数
            self.xSpeed = PLAYER_X_SPEED
        # 按下k键
        elif keys[pygame.K_k]:
            # K按下,角色进入跳跃状态,但是不会改变方向
            self.state = State.JUMP
            # 设置站立状态为False,跳跃状态为True
            # 不改变移动状态,因为移动的时候也可以跳跃
            self.isStanding = False
            self.isJumping = True
            # 设置速度,速度为负数,因为角色跳起后,要下落
            self.ySpeed = self.jumpSpeed
        # 没有按下按键
        else:
            # 没有按下按键,角色依然是站立状态
            self.state = State.STAND
            self.isStanding = True

        # 按下w键
        if keys[pygame.K_w]:
            # W按下,角色向上,改变方向状态
            self.isUp = True
            self.isStanding = True
            self.isDown = False
            self.isSquating = False
        # 按下s键
        elif keys[pygame.K_s]:
            # S按下,角色蹲下,改变方向状态,并且蹲下状态设置为True
            self.isUp = False
            self.isStanding = False
            self.isDown = True
            self.isSquating = True

完成角色站立后,我们试一下效果怎么样

在主类中创建角色,并放入pygame.sprite.Group中

class MainGame:

    player1 = None
    allSprites = None

在__init__()函数中添加代码

# 初始化角色
MainGame.player1 = PlayerOne(pygame.time.get_ticks())
# 设置角色的初始位置
# 这里设置为(0,80),可以实现一开始玩家掉下来的动画,目前没有实现掉落,所以直接设置为(80,300)
# MainGame.player1.rect.x = 80
# MainGame.player1.rect.bottom = 0
MainGame.player1.rect.x = 80
MainGame.player1.rect.bottom = 300

# 把角色放入组中,方便统一管理
MainGame.allSprites = pygame.sprite.Group(MainGame.player1)

之后在循环中调用角色的update函数

为了方便,我把物体的更新全部放在一起,创建一个update()函数

在主类中添加函数

def update(self, window):
    # 更新物体
    currentTime = pygame.time.get_ticks()
    MainGame.allSprites.update(self.keys, currentTime)
    # 显示物体
    MainGame.allSprites.draw(window)

pygame.sprite.Group()中的物体,可以统一更新,这就是它的方便之处

因为魂斗罗中玩家移动的时候,场景中的物体也是要移动的,所以地图是一个长条状,当玩家向右移动时,实际上是地图向左移动,玩家不动,创建中的物体向左移动,如果不把全部物体放到组中,不好统一管理

完整的主类代码

import sys
import pygame
from Constants import *
from PlayerOne import PlayerOne


class MainGame:

    player1 = None
    allSprites = None

    window = None

    def __init__(self):
        # 初始化展示模块
        pygame.display.init()

        SCREEN_SIZE = (SCREEN_WIDTH, SCREEN_HEIGHT)
        # 初始化窗口
        MainGame.window = pygame.display.set_mode(SCREEN_SIZE)
        # 设置窗口标题
        pygame.display.set_caption('魂斗罗角色')
        # 是否结束游戏
        self.isEnd = False
        # 获取按键
        self.keys = pygame.key.get_pressed()
        # 帧率
        self.fps = 60
        self.clock = pygame.time.Clock()

        # 初始化角色
        MainGame.player1 = PlayerOne(pygame.time.get_ticks())
        # 设置角色的初始位置
        # 这里设置为(0,80),可以实现一开始玩家掉下来的动画
        MainGame.player1.rect.x = 80
        MainGame.player1.rect.bottom = 300

        # 把角色放入组中,方便统一管理
        MainGame.allSprites = pygame.sprite.Group(MainGame.player1)

    def run(self):
        while not self.isEnd:

            # 设置背景颜色
            pygame.display.get_surface().fill((0, 0, 0))

            # 游戏场景和景物更新函数
            self.update(MainGame.window)

            # 获取窗口中的事件
            self.getPlayingModeEvent()

            # 更新窗口
            pygame.display.update()

            # 设置帧率
            self.clock.tick(self.fps)
            fps = self.clock.get_fps()
            caption = '魂斗罗 - {:.2f}'.format(fps)
            pygame.display.set_caption(caption)
        else:
            sys.exit()

    def getPlayingModeEvent(self):
        # 获取事件列表
        for event in pygame.event.get():
            # 点击窗口关闭按钮
            if event.type == pygame.QUIT:
                self.isEnd = True
            # 键盘按键按下
            elif event.type == pygame.KEYDOWN:
                self.keys = pygame.key.get_pressed()
            # 键盘按键抬起
            elif event.type == pygame.KEYUP:
                self.keys = pygame.key.get_pressed()

    def update(self, window):
        # 更新物体
        currentTime = pygame.time.get_ticks()
        MainGame.allSprites.update(self.keys, currentTime)
        # 显示物体
        MainGame.allSprites.draw(window)


if __name__ == '__main__':
    MainGame().run()

我们现在运行一下,看看效果

在这里插入图片描述
我们发现角色处于跳跃的样子,并且向前移动,这不符合我们的预期,预期应该是站在那里

原因在于角色一开始创建时的状态不对
在这里插入图片描述
当前没有实现falling()函数,所以下落状态没有办法显示,所以我们修改一下,修改角色类中__init__()函数

# 设置角色的状态
self.state = State.FALL 改为 self.state = State.STAND

在这里插入图片描述
改完后运行一下,看看结果

在这里插入图片描述
按a和d键玩家会一直移动,不会停下来

在这里插入图片描述
到此,我们就写好了玩家站立函数了,下面我们来写玩家移动函数

完整的玩家类__init__()函数代码

def __init__(self, currentTime):
    pygame.sprite.Sprite.__init__(self)
    # 加载角色图片
    self.standRightImage = loadImage('../Image/Player/Player1/Right/stand.png')
    self.standLeftImage = loadImage('../Image/Player/Player1/Left/stand.png')
    self.upRightImage = loadImage('../Image/Player/Player1/Up/upRight(small).png')
    self.upLeftImage = loadImage('../Image/Player/Player1/Up/upLeft(small).png')
    self.downRightImage = loadImage('../Image/Player/Player1/Down/down.png')
    self.downLeftImage = loadImage('../Image/Player/Player1/Down/down.png', True)
    self.obliqueUpRightImages = [
        loadImage('../Image/Player/Player1/Up/rightUp1.png'),
        loadImage('../Image/Player/Player1/Up/rightUp2.png'),
        loadImage('../Image/Player/Player1/Up/rightUp3.png'),
    ]
    self.obliqueUpLeftImages = [
        loadImage('../Image/Player/Player1/Up/rightUp1.png', True),
        loadImage('../Image/Player/Player1/Up/rightUp2.png', True),
        loadImage('../Image/Player/Player1/Up/rightUp3.png', True),
    ]
    self.obliqueDownRightImages = [
        loadImage('../Image/Player/Player1/ObliqueDown/1.png'),
        loadImage('../Image/Player/Player1/ObliqueDown/2.png'),
        loadImage('../Image/Player/Player1/ObliqueDown/3.png'),
    ]
    self.obliqueDownLeftImages = [
        loadImage('../Image/Player/Player1/ObliqueDown/1.png', True),
        loadImage('../Image/Player/Player1/ObliqueDown/2.png', True),
        loadImage('../Image/Player/Player1/ObliqueDown/3.png', True),
    ]
    # 角色向右的全部图片
    self.rightImages = [
        loadImage('../Image/Player/Player1/Right/run1.png'),
        loadImage('../Image/Player/Player1/Right/run2.png'),
        loadImage('../Image/Player/Player1/Right/run3.png')
    ]
    # 角色向左的全部图片
    self.leftImages = [
        loadImage('../Image/Player/Player1/Left/run1.png'),
        loadImage('../Image/Player/Player1/Left/run2.png'),
        loadImage('../Image/Player/Player1/Left/run3.png')
    ]
    # 角色跳跃的全部图片
    self.upRightImages = [
        loadImage('../Image/Player/Player1/Jump/jump1.png'),
        loadImage('../Image/Player/Player1/Jump/jump2.png'),
        loadImage('../Image/Player/Player1/Jump/jump3.png'),
        loadImage('../Image/Player/Player1/Jump/jump4.png'),
    ]
    self.upLeftImages = [
        loadImage('../Image/Player/Player1/Jump/jump1.png', True),
        loadImage('../Image/Player/Player1/Jump/jump2.png', True),
        loadImage('../Image/Player/Player1/Jump/jump3.png', True),
        loadImage('../Image/Player/Player1/Jump/jump4.png', True),
    ]
    self.rightFireImages = [
        loadImage('../Image/Player/Player1/Right/fire1.png'),
        loadImage('../Image/Player/Player1/Right/fire2.png'),
        loadImage('../Image/Player/Player1/Right/fire3.png'),
    ]
    self.leftFireImages = [
        loadImage('../Image/Player/Player1/Right/fire1.png', True),
        loadImage('../Image/Player/Player1/Right/fire2.png', True),
        loadImage('../Image/Player/Player1/Right/fire3.png', True),
    ]
    # 角色左右移动下标
    self.imageIndex = 0
    # 角色跳跃下标
    self.upImageIndex = 0
    # 角色斜射下标
    self.obliqueImageIndex = 0
    # 上一次显示图片的时间
    self.runLastTimer = currentTime
    self.fireLastTimer = currentTime

    # 选择当前要显示的图片
    self.image = self.standRightImage
    # 获取图片的rect
    self.rect = self.image.get_rect()
    # 设置角色的状态
    self.state = State.STAND
    # 角色的方向
    self.direction = Direction.RIGHT
    # 速度
    self.xSpeed = PLAYER_X_SPEED
    self.ySpeed = 0
    self.jumpSpeed = -11
    # 人物当前的状态标志
    self.isStanding = False
    self.isWalking = False
    self.isJumping = True
    self.isSquating = False
    self.isFiring = False
    # 重力加速度
    self.gravity = 0.7

    self.isUp = False
    self.isDown = False

2. 角色移动

打开注释,开始编写角色移动函数
在这里插入图片描述
同样的,先设置角色的状态,因为是角色移动,所以只有isWalking为真,其他都是假

self.isStanding = False
self.isWalking = True
self.isJumping = False
self.isSquating = False
self.isFiring = False

设置速度

self.ySpeed = 0
self.xSpeed = PLAYER_X_SPEED

判断当前状态,根据当前状态准备下一状态的图片

# 如果当前是站立的图片
if self.isStanding:
    # 方向向右,方向向上
    if self.direction == Direction.RIGHT and self.isUp:
        # 设置为向右朝上的图片
        self.image = self.upRightImage
    # 方向向右
    elif self.direction == Direction.RIGHT and not self.isUp:
        # 设置为向右站立的图片
        self.image = self.standRightImage
    elif self.direction == Direction.LEFT and self.isUp:
        self.image = self.upLeftImage
    elif self.direction == Direction.LEFT and not self.isUp:
        self.image = self.standLeftImage
    # 记下当前时间
    self.runLastTimer = currentTime
else:
    # 如果是走动的图片,先判断方向
    if self.direction == Direction.RIGHT:
        # 设置速度
        self.xSpeed = PLAYER_X_SPEED
        # 根据上下方向觉得是否角色要加载斜射的图片
        if self.isUp or self.isDown:
            # isUp == True表示向上斜射
            # isDown == True表示向下斜射
            # 计算上一次加载图片到这次的时间,如果大于115,即11.5帧,即上次加载图片到这次加载图片之间,已经加载了11张图片
            if currentTime - self.runLastTimer > 115:
                # 那么就可以加载斜着奔跑的图片
                # 如果角色加载的图片不是第三张,则加载下一张就行
                if self.obliqueImageIndex < 2:
                    self.obliqueImageIndex += 1
                # 否则就加载第一张图片
                else:
                    self.obliqueImageIndex = 0
                # 记录变换图片的时间,为下次变换图片做准备
                self.runLastTimer = currentTime
        # 不是斜射
        else:
            # 加载正常向右奔跑的图片
            if currentTime - self.runLastTimer > 115:
                if self.imageIndex < 2:
                    self.imageIndex += 1
                else:
                    self.imageIndex = 0
                self.runLastTimer = currentTime
    else:
        self.xSpeed = -PLAYER_X_SPEED
        if self.isUp or self.isDown:
            if currentTime - self.runLastTimer > 115:
                if self.obliqueImageIndex < 2:
                    self.obliqueImageIndex += 1
                else:
                    self.obliqueImageIndex = 0
                self.runLastTimer = currentTime
        else:
            if currentTime - self.runLastTimer > 115:
                if self.imageIndex < 2:
                    self.imageIndex += 1
                else:
                    self.imageIndex = 0
                self.runLastTimer = currentTime

完成图片加载后,处理按键响应

# 按下D键
if keys[pygame.K_d]:
    self.direction = Direction.RIGHT
    self.xSpeed = PLAYER_X_SPEED
# 按下A键
elif keys[pygame.K_a]:
    self.direction = Direction.LEFT
    self.xSpeed = -PLAYER_X_SPEED
 # 按下S键
elif keys[pygame.K_s]:
    self.isStanding = False
    self.isDown = True

# 按下W键
if keys[pygame.K_w]:
    self.isUp = True
    self.isDown = False
# 没有按键按下
else:
    self.state = State.STAND

# 移动时按下K键
if keys[pygame.K_k]:
    # 角色状态变为跳跃
    self.state = State.JUMP
    self.ySpeed = self.jumpSpeed
    self.isJumping = True
    self.isStanding = False

完整的walking()函数代码

    def walking(self, keys, currentTime):
        """角色行走,每10帧变换一次图片"""
        self.isStanding = False
        self.isWalking = True
        self.isJumping = False
        self.isSquating = False
        self.isFiring = False
        self.ySpeed = 0
        self.xSpeed = PLAYER_X_SPEED

        # 如果当前是站立的图片
        if self.isStanding:
            # 方向向右,方向向上
            if self.direction == Direction.RIGHT and self.isUp:
                # 设置为向右朝上的图片
                self.image = self.upRightImage
            # 方向向右
            elif self.direction == Direction.RIGHT and not self.isUp:
                # 设置为向右站立的图片
                self.image = self.standRightImage
            elif self.direction == Direction.LEFT and self.isUp:
                self.image = self.upLeftImage
            elif self.direction == Direction.LEFT and not self.isUp:
                self.image = self.standLeftImage
            # 记下当前时间
            self.runLastTimer = currentTime
        else:
            # 如果是走动的图片,先判断方向
            if self.direction == Direction.RIGHT:
                # 设置速度
                self.xSpeed = PLAYER_X_SPEED
                # 根据上下方向觉得是否角色要加载斜射的图片
                if self.isUp or self.isDown:
                    # isUp == True表示向上斜射
                    # isDown == True表示向下斜射
                    # 计算上一次加载图片到这次的时间,如果大于115,即11.5帧,即上次加载图片到这次加载图片之间,已经加载了11张图片
                    if currentTime - self.runLastTimer > 115:
                        # 那么就可以加载斜着奔跑的图片
                        # 如果角色加载的图片不是第三张,则加载下一张就行
                        if self.obliqueImageIndex < 2:
                            self.obliqueImageIndex += 1
                        # 否则就加载第一张图片
                        else:
                            self.obliqueImageIndex = 0
                        # 记录变换图片的时间,为下次变换图片做准备
                        self.runLastTimer = currentTime
                # 不是斜射
                else:
                    # 加载正常向右奔跑的图片
                    if currentTime - self.runLastTimer > 115:
                        if self.imageIndex < 2:
                            self.imageIndex += 1
                        else:
                            self.imageIndex = 0
                        self.runLastTimer = currentTime
            else:
                self.xSpeed = -PLAYER_X_SPEED
                if self.isUp or self.isDown:
                    if currentTime - self.runLastTimer > 115:
                        if self.obliqueImageIndex < 2:
                            self.obliqueImageIndex += 1
                        else:
                            self.obliqueImageIndex = 0
                        self.runLastTimer = currentTime
                else:
                    if currentTime - self.runLastTimer > 115:
                        if self.imageIndex < 2:
                            self.imageIndex += 1
                        else:
                            self.imageIndex = 0
                        self.runLastTimer = currentTime

        # 按下D键
        if keys[pygame.K_d]:
            self.direction = Direction.RIGHT
            self.xSpeed = PLAYER_X_SPEED
        # 按下A键
        elif keys[pygame.K_a]:
            self.direction = Direction.LEFT
            self.xSpeed = -PLAYER_X_SPEED
         # 按下S键
        elif keys[pygame.K_s]:
            self.isStanding = False
            self.isDown = True

        # 按下W键
        if keys[pygame.K_w]:
            self.isUp = True
            self.isDown = False
        # 没有按键按下
        else:
            self.state = State.STAND

        # 移动时按下K键
        if keys[pygame.K_k]:
            # 角色状态变为跳跃
            self.state = State.JUMP
            self.ySpeed = self.jumpSpeed
            self.isJumping = True
            self.isStanding = False

运行一下,看看效果

在这里插入图片描述
哇,实现了,我们就完成了角色移动了

3. 角色跳跃

首先设置状态标志

# 设置标志
self.isJumping = True
self.isStanding = False
self.isDown = False
self.isSquating = False
self.isFiring = False

更新速度

self.ySpeed += self.gravity

跳跃后,角色的y坐标是减少的,所以速度原来是负数,由于跳起到最高点速度一直减小,所以这里我们设置了重力,保证速度慢慢减少到0

根据时间决定是否显示下一张图片

if currentTime - self.runLastTimer > 115:
    if self.upImageIndex < 3:
        self.upImageIndex += 1
    else:
        self.upImageIndex = 0
    # 记录变换图片的时间,为下次变换图片做准备
    self.runLastTimer = currentTime

设置按键响应事件

if keys[pygame.K_d]:
    self.direction = Direction.RIGHT

elif keys[pygame.K_a]:
    self.direction = Direction.LEFT

# 按下W键
if keys[pygame.K_w]:
    self.isUp = True
    self.isDown = False
elif keys[pygame.K_s]:
    self.isUp = False
    self.isDown = True

# 当速度变为正数,玩家进入下落状态
if self.ySpeed >= 0:
    self.state = State.FALL

if not keys[pygame.K_k]:
    self.state = State.FALL

完整jumping()函数代码

def jumping(self, keys, currentTime):
    """跳跃"""
    # 设置标志
    self.isJumping = True
    self.isStanding = False
    self.isDown = False
    self.isSquating = False
    self.isFiring = False
    # 更新速度
    self.ySpeed += self.gravity
    if currentTime - self.runLastTimer > 115:
        if self.upImageIndex < 3:
            self.upImageIndex += 1
        else:
            self.upImageIndex = 0
        # 记录变换图片的时间,为下次变换图片做准备
        self.runLastTimer = currentTime

    if keys[pygame.K_d]:
        self.direction = Direction.RIGHT

    elif keys[pygame.K_a]:
        self.direction = Direction.LEFT

    # 按下W键
    if keys[pygame.K_w]:
        self.isUp = True
        self.isDown = False
    elif keys[pygame.K_s]:
        self.isUp = False
        self.isDown = True

    if self.ySpeed >= 0:
        self.state = State.FALL

    if not keys[pygame.K_k]:
        self.state = State.FALL

4. 角色下落

def falling(self, keys, currentTime):
    # 下落时速度越来越快,所以速度需要一直增加
    self.ySpeed += self.gravity
    if currentTime - self.runLastTimer > 115:
        if self.upImageIndex < 3:
            self.upImageIndex += 1
        else:
            self.upImageIndex = 0
        self.runLastTimer = currentTime

    # 防止落到窗口外面,当落到一定高度时,就不会再掉落了
    if self.rect.bottom > SCREEN_HEIGHT - GROUND_HEIGHT:
        self.state = State.WALK
        self.ySpeed = 0
        self.rect.bottom = SCREEN_HEIGHT - GROUND_HEIGHT
        self.isJumping = False

    if keys[pygame.K_d]:
        self.direction = Direction.RIGHT
        self.isWalking = False

    elif keys[pygame.K_a]:
        self.direction = Direction.LEFT
        self.isWalking = False

我们现在来看看效果,运行一下

不要忘记打开注释

在这里插入图片描述

在这里插入图片描述
到现在,我们实现了角色移动、跳跃啦,下面就是发射子弹了

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/370839.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

MySQL高级第一讲

目录 一、MySQL高级01 1.1 索引 1.1.1 索引概述 1.1.2 索引特点 1.1.3 索引结构 1.1.4 BTREE结构(B树) 1.1.5 BTREE结构(B树) 1.1.6 索引分类 1.1.7 索引语法 1.1.8 索引设计原则 1.2 视图 1.2.1 视图概述 1.2.2 创建或修改视图 1.3 存储过程和函数 1.3.1 存储过…

openresty的部署、nginx高速缓存的配置、nginx日志的可视化

文章目录一、openresty1.OpenResty简介2.OpenResty的技术3.OpenResty的优势4.openresty部署实验二、nginx配置高效缓存三、nginx日志可视化一、openresty 1.OpenResty简介 OpenResty官网 http://openresty.org/cn/ OpenResty是一个基于 Nginx 与 Lua 的高性能 Web 平台&#x…

shell基础学习

文章目录查看shell解释器写hello world多命令处理执行变量常用系统变量自定义变量撤销变量静态变量变量提升为全局环境变量特殊变量$n$#$* $$?运算符:条件判断比较流程控制语句ifcasefor 循环while 循环read读取控制台输入基本语法:函数系统函数basenamedirname自定义函数shel…

FL StudioV21电脑版水果编曲音乐编辑软件

这是一款功能十分丰富和强大的音乐编辑软件&#xff0c;能够帮助用户进行编曲、剪辑、录音、混音等操作&#xff0c;让用户能够全面地调整音频。FL水果最新版是一款专业级别的音乐编曲软件&#xff0c;集合更多的编曲功能为一身&#xff0c;可以进行录音、编辑、制作、混音、调…

计算机网络(六): HTTP,HTTPS,DNS,网页解析全过程

文章目录一、HTTP头部包含的信息通用头部请求头部响应头部实体头部二、Keep-Alive和非Keep-Alive的区别三、HTTP的方法四、HTTP和HTTPS建立连接的过程4.1 HTTP4.2 HTTPS五、HTTP和HTTPS的区别六、HTTPS的加密方式七、cookie和sessionsessioncookie八、HTTP状态码状态码200&…

【微信小程序】-- WXML 模板语法 - 数据绑定(九)

&#x1f48c; 所属专栏&#xff1a;【微信小程序开发教程】 &#x1f600; 作  者&#xff1a;我是夜阑的狗&#x1f436; &#x1f680; 个人简介&#xff1a;一个正在努力学技术的CV工程师&#xff0c;专注基础和实战分享 &#xff0c;欢迎咨询&#xff01; &…

DPDK系列之四DPDK整体框架分析说明

一、网络发展和DPDK 在上篇分析过网络应用对DPDK出现的影响。而具体体现在技术上&#xff0c;从最简单来看就是从C10K到c100K甚至更多。而相应的计算的发展也从挖掘单CPU的性能发展到了瓶颈&#xff0c;同样&#xff0c;对于网络设备也遇到了类似的问题。而目前解决问题的方法…

MySQL到Elasticsearch实时同步构建数据检索服务的选型与思考[转载]

前言 本文具体探讨 MySQL 数据实时同步到 Elasticsearch (以下简称 ES ) 技术方案和思考&#xff0c;同时使用一定篇幅介绍一些前置知识&#xff0c;从理论到实践&#xff0c;让读者更好的理解这块内容和相关问题。包括&#xff1a; 为什么我们要将数据从 MySQL 实时同步到 ES …

Day899.Join语句优化 -MySQL实战

Join语句优化 Hi&#xff0c;我是阿昌&#xff0c;今天学习记录的是关于Join语句优化的内容。 join 语句的两种算法&#xff0c;分别是 Index Nested-Loop Join(NLJ) 和 Block Nested-Loop Join(BNL)。 发现在使用 NLJ 算法的时候&#xff0c;其实效果还是不错的&#xff0c…

【手把手一起学习】(五) Altium Designer 20 STM32核心板Demo----PCB封装库添加元件

1 PCB封装库添加元件 元件的PCB封装非常重要&#xff0c;关系到实际电子元件能否焊接到制作的电路板上。PCB封装的引脚顺序&#xff0c;引脚间距&#xff0c;焊盘大小&#xff0c;焊盘形状等都需要与元件实物严格对应&#xff0c;因此绘制PCB封装库时&#xff0c;需要参考元件…

在Windows上编译Nginx

《在Windows上编译Nginx》视频教程官方编译说明 Building nginx on the Win32 platform with Visual C 环境准备 1. Microsoft Visual Studio(Microsoft Visual C 编译器)&#xff0c;下载地址&#xff1a;https://visualstudio.microsoft.com/zh-hans/。 2. Git(备用)&…

OSS存储使用之centOS系统ossfs挂载

以CentOS7系统为例 下载CentOS系统支持的ossfs工具的版本&#xff0c;以下载CentOS 7.0 (x64)版本为例&#xff0c;可以通过wget命令进行安装包的下载 wget http://gosspublic.alicdn.com/ossfs/ossfs_1.80.6_centos7.0_x86_64.rpm 也可以通过yum命令来进行安装包的下载 sud…

【网络原理9】HTTP响应篇

在前两篇文章当中&#xff0c;已经分别介绍了HTTP是什么&#xff0c;以及常见的请求头当中的属性。【网络原理7】认识HTTP_革凡成圣211的博客-CSDN博客HTTP抓包&#xff0c;Fiddler的使用https://blog.csdn.net/weixin_56738054/article/details/129148515?spm1001.2014.3001.…

excel格式调整:表格应用中格式刷技法汇总

格式刷很简单&#xff0c;点一下&#xff0c;就可以把格式复制到其他单元格、图形、文字上。但是格式刷的用法又不仅仅这么一点&#xff0c;它还可以实现快速隔行填色、隔行隐藏&#xff0c;实现“无损”合并单元格等。在excel中&#xff0c;位于开始菜单中左侧的格式刷&#x…

澜沧古茶再冲刺港交所上市:多项核心指标下滑,杜春峄为董事长

近日&#xff0c;普洱澜沧古茶股份有限公司&#xff08;下称“澜沧古茶”&#xff09;向港交所主板提交上市申请&#xff0c;中信建投国际、招商证券国际为其联席保荐人。据贝多财经了解&#xff0c;这已经是澜沧古茶第二次在港交所递表&#xff0c;此前曾于2022年5月30日在港交…

不同方案特性对比

特性对比项 2.4G 蓝牙 868M WIFI 通信速率 低 低 低 高 距离&#xff08;实用可靠&#xff09; 20米 10米 30米 15米 确定性 高 低 高 高 可靠性&#xff08;距离内&#xff09; 高 低 高 高 刷新一个标签时间&#xff08;通常&#xff09; 0.5-1s …

西北工业大学大学物理(I)下2019-2020选填考题解析

单选题12个&#xff0c;24分。1量子数考查前三个量子数由薛定谔方程决定&#xff0c;最后一个关于自旋的由狄拉克方程决定由这些量子数可以给出原子的壳层结构。考试其实考的不深&#xff0c;记住这个表就够了。2 书上18、19章量子物理的著名实验&#xff1a;光电效应&#xff…

如何安装和使用oecp工具?

运行环境&#xff1a;python3>3.7.9、sqlite>v3.7.17 下载安装与部署的要求&#xff1a; install abidiff (centos): yum install -y epel-release; yum install -y libabigail install createrepo: yum install -y createrepo install binutils: yum install -…

【Redis】初探Redis

【Redis】初探Redis 前言 很早之前写的文章&#xff0c;最近考虑到面试可能涉及到Redis&#xff0c;所以拿出来再看一遍 Redis概述 Redis是啥&#xff1f; Redis是Remote Dicitionary Server的缩写&#xff0c;翻译过来就叫做远程字典服务 是开源的、使用C完成的、支持网路…

推荐算法——NCF知识总结代码实现

NCF知识总结代码实现1. NeuralCF 模型的结构1.1 回顾CF和MF1.2 NCF 模型结构1.3 NeuralCF 模型的扩展---双塔模型2. NCF代码实现2.1 tensorflow2.2 pytorchNeuralCF&#xff1a;如何用深度学习改造协同过滤&#xff1f; 随着技术的发展&#xff0c;协同过滤相比深度学习模型的…