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

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

    • 继续编写魂斗罗
      • 1. 创建子弹类
      • 2. 根据玩家方向和状态设置子弹发射的位置
        • (1). 站立向右发射子弹
        • (2). 站立向左发射子弹
        • (3). 站立朝上发射子弹
        • (4). 蹲下发射子弹
        • (5). 向斜方发射子弹
        • (6). 奔跑时发射子弹
        • (7). 跳跃时发射子弹
      • 3. 在玩家类中加入开火
      • 4. 修改主类实现玩家开火

继续编写魂斗罗

在上次的博客学习 Python 之 Pygame 开发魂斗罗(三)中,我们完成了角色的移动和跳跃,下面我们来继续写魂斗罗。

下面是图片的素材

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

1. 创建子弹类

发射子弹首先要有子弹类
我们来创建一下

import pygame
from Constants import *

class Bullet(pygame.sprite.Sprite):

    def __init__(self, person):
        pygame.sprite.Sprite.__init__(self)
        self.images = [
            loadImage('../Image/Bullet/bullet1.png')
        ]
        self.index = 0
        self.image = self.images[self.index]
        # 速度
        self.xSpeed = 1
        self.ySpeed = 1
        self.rect = pygame.Rect(person.rect)

        # 销毁开关
        self.isDestroy = False

    def move(self):
        self.rect.x += self.xSpeed
        self.rect.y += self.ySpeed
        self.checkBullet()

    def draw(self, window):
        window.blit(self.image, self.rect)

    def checkBullet(self):
        toDestroy = False
        if self.rect.top < 0 or self.rect.top > 600:
            toDestroy = True
        if self.rect.left < 0 or self.rect.right > 900:
            toDestroy = True
        if toDestroy:
            self.isDestroy = True

2. 根据玩家方向和状态设置子弹发射的位置

由于玩家的方向和状态不一样,所以玩家开火后,子弹发射的位置也不一样

下面我们来看看角色状态和发射子弹的位置

(1). 站立向右发射子弹

(x,y) 是图片的位置,我们计算出,此状态下,子弹发射的位置是 (x+24,y+11)

在这里插入图片描述
下面我们来设置一下

self.rect.x += 24 * 2.5
self.rect.y += 11 * 2.5
self.ySpeed = 0
self.xSpeed = 7

2.5是人物放大的倍数,加载图像的时候把图像放大了2.5倍,所以设置子弹发射位置的时候,同样要乘以2.5

if person.isStanding:
	# 判断方向
	# 方向向右
    if person.direction == Direction.RIGHT:
    	# 向上
        if person.isUp:
            pass
        # 向右
        else:
            self.rect.x += 24 * 2.5
            self.rect.y += 11 * 2.5
            self.ySpeed = 0
            self.xSpeed = 7
    # 方向向左
    else:
        if person.isUp:
            pass
        else:
            pass

elif person.isSquating and not person.isWalking:
    if person.direction == Direction.RIGHT:
        pass
    else:
        pass

elif person.isWalking:
    if person.direction == Direction.RIGHT:
        if person.isUp:
            pass
        elif person.isDown:
            pass
        else:
            pass
    else:
        if person.isUp:
            pass
        elif person.isDown:
            pass
        else:
            pass

elif person.isJumping or person.state == State.FALL:
    if person.direction == Direction.RIGHT:
        pass
    else:
        pass

(2). 站立向左发射子弹

在这里插入图片描述

self.rect.y += 11 * 2.5
self.ySpeed = 0
self.xSpeed = -7
# 根据角色的方向和状态设置子弹发射的位置
# 角色站着
if person.isStanding:
	# 判断方向
    if person.direction == Direction.RIGHT:
    	# 向上
        if person.isUp:
            pass
        else:
            self.rect.x += 24 * 2.5
            self.rect.y += 11 * 2.5
            self.ySpeed = 0
            self.xSpeed = 7
    else:
        if person.isUp:
            pass
        else:
            self.rect.y += 11 * 2.5
            self.ySpeed = 0
            self.xSpeed = -7

elif person.isSquating and not person.isWalking:
    if person.direction == Direction.RIGHT:
        pass
    else:
        pass

elif person.isWalking:
    if person.direction == Direction.RIGHT:
        if person.isUp:
            pass
        elif person.isDown:
            pass
        else:
            pass
    else:
        if person.isUp:
            pass
        elif person.isDown:
            pass
        else:
            pass

elif person.isJumping or person.state == State.FALL:
    if person.direction == Direction.RIGHT:
        pass
    else:
        pass

(3). 站立朝上发射子弹

站立向右朝上发射子弹
在这里插入图片描述

self.rect.x += 10 * 2.5
self.rect.y += -1 * 2.5
self.ySpeed = -7
self.xSpeed = 0

这里我微微调整了一下y的值,方向向上,所以子弹的y是逐渐减小的,所以y速度是负数

# 根据角色的方向和状态设置子弹发射的位置
# 角色站着
if person.isStanding:
	# 判断方向
    if person.direction == Direction.RIGHT:
    	# 向上
        if person.isUp:
            self.rect.x += 10 * 2.5
			self.rect.y += -1 * 2.5
			self.ySpeed = -7
			self.xSpeed = 0
        else:
            self.rect.x += 24 * 2.5
            self.rect.y += 11 * 2.5
            self.ySpeed = 0
            self.xSpeed = 7
    else:
        if person.isUp:
            pass
        else:
            self.rect.y += 11 * 2.5
            self.ySpeed = 0
            self.xSpeed = -7

elif person.isSquating and not person.isWalking:
    if person.direction == Direction.RIGHT:
        pass
    else:
        pass

elif person.isWalking:
    if person.direction == Direction.RIGHT:
        if person.isUp:
            pass
        elif person.isDown:
            pass
        else:
            pass
    else:
        if person.isUp:
            pass
        elif person.isDown:
            pass
        else:
            pass

elif person.isJumping or person.state == State.FALL:
    if person.direction == Direction.RIGHT:
        pass
    else:
        pass

站立向左朝上发射子弹也是同样的计算方式

self.rect.x += 10 * 2.5
self.rect.y += -1 * 2.5
self.ySpeed = -7
self.xSpeed = 0
# 根据角色的方向和状态设置子弹发射的位置
# 角色站着
if person.isStanding:
	# 判断方向
    if person.direction == Direction.RIGHT:
    	# 向上
        if person.isUp:
            self.rect.x += 10 * 2.5
			self.rect.y += -1 * 2.5
			self.ySpeed = -7
			self.xSpeed = 0
        else:
            self.rect.x += 24 * 2.5
            self.rect.y += 11 * 2.5
            self.ySpeed = 0
            self.xSpeed = 7
    else:
        if person.isUp:
            self.rect.x += 10 * 2.5
            self.rect.y += -1 * 2.5
            self.ySpeed = -7
            self.xSpeed = 0
        else:
            self.rect.y += 11 * 2.5
            self.ySpeed = 0
            self.xSpeed = -7

elif person.isSquating and not person.isWalking:
    if person.direction == Direction.RIGHT:
        pass
    else:
        pass

elif person.isWalking:
    if person.direction == Direction.RIGHT:
        if person.isUp:
            pass
        elif person.isDown:
            pass
        else:
            pass
    else:
        if person.isUp:
            pass
        elif person.isDown:
            pass
        else:
            pass

elif person.isJumping or person.state == State.FALL:
    if person.direction == Direction.RIGHT:
        pass
    else:
        pass

(4). 蹲下发射子弹

向右示意图

在这里插入图片描述

self.rect.x += 34 * 2.5
self.rect.y += 25 * 2.5
self.ySpeed = 0
self.xSpeed = 7
# 根据角色的方向和状态设置子弹发射的位置
# 角色站着
if person.isStanding:
	# 判断方向
    if person.direction == Direction.RIGHT:
    	# 向上
        if person.isUp:
            self.rect.x += 10 * 2.5
			self.rect.y += -1 * 2.5
			self.ySpeed = -7
			self.xSpeed = 0
        else:
            self.rect.x += 24 * 2.5
            self.rect.y += 11 * 2.5
            self.ySpeed = 0
            self.xSpeed = 7
    else:
        if person.isUp:
            self.rect.x += 10 * 2.5
            self.rect.y += -1 * 2.5
            self.ySpeed = -7
            self.xSpeed = 0
        else:
            self.rect.y += 11 * 2.5
            self.ySpeed = 0
            self.xSpeed = -7

elif person.isSquating and not person.isWalking:
    if person.direction == Direction.RIGHT:
        self.rect.x += 34 * 2.5
		self.rect.y += 25 * 2.5
		self.ySpeed = 0
		self.xSpeed = 7
    else:
        pass

elif person.isWalking:
    if person.direction == Direction.RIGHT:
        if person.isUp:
            pass
        elif person.isDown:
            pass
        else:
            pass
    else:
        if person.isUp:
            pass
        elif person.isDown:
            pass
        else:
            pass

elif person.isJumping or person.state == State.FALL:
    if person.direction == Direction.RIGHT:
        pass
    else:
        pass

同样的,设置向左的发射位置

self.rect.y += 25 * 2.5
self.ySpeed = 0
self.xSpeed = -7
# 根据角色的方向和状态设置子弹发射的位置
# 角色站着
if person.isStanding:
	# 判断方向
    if person.direction == Direction.RIGHT:
    	# 向上
        if person.isUp:
            self.rect.x += 10 * 2.5
			self.rect.y += -1 * 2.5
			self.ySpeed = -7
			self.xSpeed = 0
        else:
            self.rect.x += 24 * 2.5
            self.rect.y += 11 * 2.5
            self.ySpeed = 0
            self.xSpeed = 7
    else:
        if person.isUp:
            self.rect.x += 10 * 2.5
            self.rect.y += -1 * 2.5
            self.ySpeed = -7
            self.xSpeed = 0
        else:
            self.rect.y += 11 * 2.5
            self.ySpeed = 0
            self.xSpeed = -7

elif person.isSquating and not person.isWalking:
    if person.direction == Direction.RIGHT:
        self.rect.x += 34 * 2.5
		self.rect.y += 25 * 2.5
		self.ySpeed = 0
		self.xSpeed = 7
    else:
        self.rect.y += 25 * 2.5
		self.ySpeed = 0
		self.xSpeed = -7

elif person.isWalking:
    if person.direction == Direction.RIGHT:
        if person.isUp:
            pass
        elif person.isDown:
            pass
        else:
            pass
    else:
        if person.isUp:
            pass
        elif person.isDown:
            pass
        else:
            pass

elif person.isJumping or person.state == State.FALL:
    if person.direction == Direction.RIGHT:
        pass
    else:
        pass

(5). 向斜方发射子弹

向斜右上方发射子弹示意图
在这里插入图片描述

self.rect.x += 20 * 2.5
self.rect.y += -1 * 2.5
self.ySpeed = -7
self.xSpeed = 7

向斜左上方发射子弹时的子弹位置

self.rect.x += -3 * 2.5
self.rect.y += -1 * 2.5
self.ySpeed = -7
self.xSpeed = -7

向斜右下方发射子弹示意图
在这里插入图片描述

self.rect.x += 21 * 2.5
self.rect.y += 20 * 2.5
self.ySpeed = 7
self.xSpeed = 7

向斜左下方发射子弹时的子弹位置

self.rect.x += -3 * 2.5
self.rect.y += 20 * 2.5
self.ySpeed = 7
self.xSpeed = -7

(6). 奔跑时发射子弹

奔跑时发射子弹和站立发射子弹是一样的

向右

self.rect.x += 24 * 2.5
self.rect.y += 11 * 2.5
self.ySpeed = 0
self.xSpeed = 7

向左

self.rect.y += 11 * 2.5
self.ySpeed = 0
self.xSpeed = -7

完整的代码

if person.isStanding:
    if person.direction == Direction.RIGHT:
        if person.isUp:
            self.rect.x += 10 * 2.5
            self.rect.y += -1 * 2.5
            self.ySpeed = -7
            self.xSpeed = 0
        else:
            self.rect.x += 24 * 2.5
            self.rect.y += 11 * 2.5
            self.ySpeed = 0
            self.xSpeed = 7
    else:
        if person.isUp:
            self.rect.x += 10 * 2.5
            self.rect.y += -1 * 2.5
            self.ySpeed = -7
            self.xSpeed = 0
        else:
            self.rect.y += 11 * 2.5
            self.ySpeed = 0
            self.xSpeed = -7

elif person.isSquating and not person.isWalking:
    if person.direction == Direction.RIGHT:
        self.rect.x += 34 * 2.5
        self.rect.y += 25 * 2.5
        self.ySpeed = 0
        self.xSpeed = 7
    else:
        self.rect.y += 25 * 2.5
        self.ySpeed = 0
        self.xSpeed = -7

elif person.isWalking:
    if person.direction == Direction.RIGHT:
        if person.isUp:
            self.rect.x += 20 * 2.5
            self.rect.y += -1 * 2.5
            self.ySpeed = -7
            self.xSpeed = 7
        elif person.isDown:
            self.rect.x += 21 * 2.5
            self.rect.y += 20 * 2.5
            self.ySpeed = 7
            self.xSpeed = 7
        else:
            self.rect.x += 24 * 2.5
            self.rect.y += 11 * 2.5
            self.ySpeed = 0
            self.xSpeed = 7
    else:
        if person.isUp:
            self.rect.x += -3 * 2.5
            self.rect.y += -1 * 2.5
            self.ySpeed = -7
            self.xSpeed = -7
        elif person.isDown:
            self.rect.x += -3 * 2.5
            self.rect.y += 20 * 2.5
            self.ySpeed = 7
            self.xSpeed = -7
        else:
            self.rect.y += 11 * 2.5
            self.ySpeed = 0
            self.xSpeed = -7

elif person.isJumping or person.state == State.FALL:
    if person.direction == Direction.RIGHT:
        pass
    else:
        pass

(7). 跳跃时发射子弹

在这里插入图片描述

elif person.isJumping or person.state == State.FALL:
    if person.direction == Direction.RIGHT:
        self.rect.x += 16 * 2.5
        self.rect.y += 8 * 2.5
        self.ySpeed = 0
        self.xSpeed = 7
    else:
        self.rect.x += -2 * 2.5
        self.rect.y += 8 * 2.5
        self.ySpeed = 0
        self.xSpeed = -7

完整子弹类代码

import pygame
from Constants import *

class Bullet(pygame.sprite.Sprite):

    def __init__(self, person):
        pygame.sprite.Sprite.__init__(self)
        self.images = [
            loadImage('../Image/Bullet/bullet1.png')
        ]
        self.index = 0
        self.image = self.images[self.index]
        # 速度
        self.xSpeed = 1
        self.ySpeed = 1
        self.rect = pygame.Rect(person.rect)

        if person.isStanding:
            if person.direction == Direction.RIGHT:
                if person.isUp:
                    self.rect.x += 10 * 2.5
                    self.rect.y += -1 * 2.5
                    self.ySpeed = -7
                    self.xSpeed = 0
                else:
                    self.rect.x += 24 * 2.5
                    self.rect.y += 11 * 2.5
                    self.ySpeed = 0
                    self.xSpeed = 7
            else:
                if person.isUp:
                    self.rect.x += 10 * 2.5
                    self.rect.y += -1 * 2.5
                    self.ySpeed = -7
                    self.xSpeed = 0
                else:
                    self.rect.y += 11 * 2.5
                    self.ySpeed = 0
                    self.xSpeed = -7

        elif person.isSquating and not person.isWalking:
            if person.direction == Direction.RIGHT:
                self.rect.x += 34 * 2.5
                self.rect.y += 25 * 2.5
                self.ySpeed = 0
                self.xSpeed = 7
            else:
                self.rect.y += 25 * 2.5
                self.ySpeed = 0
                self.xSpeed = -7

        elif person.isWalking:
            if person.direction == Direction.RIGHT:
                if person.isUp:
                    self.rect.x += 20 * 2.5
                    self.rect.y += -1 * 2.5
                    self.ySpeed = -7
                    self.xSpeed = 7
                elif person.isDown:
                    self.rect.x += 21 * 2.5
                    self.rect.y += 20 * 2.5
                    self.ySpeed = 7
                    self.xSpeed = 7
                else:
                    self.rect.x += 24 * 2.5
                    self.rect.y += 11 * 2.5
                    self.ySpeed = 0
                    self.xSpeed = 7
            else:
                if person.isUp:
                    self.rect.x += -3 * 2.5
                    self.rect.y += -1 * 2.5
                    self.ySpeed = -7
                    self.xSpeed = -7
                elif person.isDown:
                    self.rect.x += -3 * 2.5
                    self.rect.y += 20 * 2.5
                    self.ySpeed = 7
                    self.xSpeed = -7
                else:
                    self.rect.y += 11 * 2.5
                    self.ySpeed = 0
                    self.xSpeed = -7

        elif person.isJumping or person.state == State.FALL:
            if person.direction == Direction.RIGHT:
                self.rect.x += 16 * 2.5
                self.rect.y += 8 * 2.5
                self.ySpeed = 0
                self.xSpeed = 7
            else:
                self.rect.x += -2 * 2.5
                self.rect.y += 8 * 2.5
                self.ySpeed = 0
                self.xSpeed = -7

        # 销毁开关
        self.isDestroy = False

    def move(self):
        self.rect.x += self.xSpeed
        self.rect.y += self.ySpeed
        self.checkBullet()

    def draw(self, window):
        window.blit(self.image, self.rect)

    def checkBullet(self):
        toDestroy = False
        if self.rect.top < 0 or self.rect.top > 600:
            toDestroy = True
        if self.rect.left < 0 or self.rect.right > 900:
            toDestroy = True
        if toDestroy:
            self.isDestroy = True

3. 在玩家类中加入开火

在常量文件中设置子弹上限

# 设置玩家子弹上限
PLAYER_BULLET_NUMBER = 15

在玩家类的四个状态函数中加入发射的代码

if keys[pygame.K_j]:
    self.isFiring = True
    if len(playerBulletList) < PLAYER_BULLET_NUMBER:
    	# 设置子弹发射的间隔为150
        if currentTime - self.fireLastTimer  > 150:
            playerBulletList.append(Bullet(self))
            self.fireLastTimer = currentTime

完整的玩家类

import pygame
from Constants import *
from Bullet import Bullet


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, playerBulletList):
        # 更新站或者走的状态
        # 根据状态响应按键
        if self.state == State.STAND:
            self.standing(keys, currentTime, playerBulletList)
        elif self.state == State.WALK:
            self.walking(keys, currentTime, playerBulletList)
        elif self.state == State.JUMP:
            self.jumping(keys, currentTime, playerBulletList)
        elif self.state == State.FALL:
            self.falling(keys, currentTime, playerBulletList)

        # 更新位置
        # 记录前一次的位置坐标
        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, playerBulletList):
        """角色站立"""

        # 设置角色状态
        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
            
        if keys[pygame.K_j]:
            self.isFiring = True
            if len(playerBulletList) < PLAYER_BULLET_NUMBER:
                if currentTime - self.fireLastTimer  > 150:
                    playerBulletList.append(Bullet(self))
                    self.fireLastTimer = currentTime


    def walking(self, keys, currentTime, playerBulletList):
        """角色行走,每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
            
        if keys[pygame.K_j]:
            self.isFiring = True
            if len(playerBulletList) < PLAYER_BULLET_NUMBER:
                if currentTime - self.fireLastTimer  > 150:
                    playerBulletList.append(Bullet(self))
                    self.fireLastTimer = currentTime

    def jumping(self, keys, currentTime, playerBulletList):
        """跳跃"""
        # 设置标志
        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
            
        if keys[pygame.K_j]:
            self.isFiring = True
            if len(playerBulletList) < PLAYER_BULLET_NUMBER:
                if currentTime - self.fireLastTimer  > 150:
                    playerBulletList.append(Bullet(self))
                    self.fireLastTimer = currentTime

    def falling(self, keys, currentTime, playerBulletList):
        # 下落时速度越来越快,所以速度需要一直增加
        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
            
        if keys[pygame.K_j]:
            self.isFiring = True
            if len(playerBulletList) < PLAYER_BULLET_NUMBER:
                if currentTime - self.fireLastTimer  > 150:
                    playerBulletList.append(Bullet(self))
                    self.fireLastTimer = currentTime


4. 修改主类实现玩家开火

由于玩家类中的update()方法多了一个子弹列表的参数,现在要修改主类

在主类中加入子弹列表

# 子弹
player1BulletList = []

在这里插入图片描述
修改run()函数,把子弹列表传入update()函数

def run(self):

    while not self.isEnd:

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

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

        # 更新窗口
        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()

修改update()函数

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

创建显示子弹函数,在类外创建

def drawPlayerOneBullet(player1BulletList):
    for bullet in player1BulletList:
        if bullet.isDestroy:
            player1BulletList.remove(bullet)
        else:
            bullet.draw(MainGame.window)
            bullet.move()

完整的主类代码

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


def drawPlayerOneBullet(player1BulletList):
    for bullet in player1BulletList:
        if bullet.isDestroy:
            player1BulletList.remove(bullet)
        else:
            bullet.draw(MainGame.window)
            bullet.move()

class MainGame:

    player1 = None
    allSprites = None

    window = None

    # 子弹
    player1BulletList = []

    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, MainGame.player1BulletList)

            # 获取窗口中的事件
            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, player1BulletList):
        # 更新物体
        currentTime = pygame.time.get_ticks()
        MainGame.allSprites.update(self.keys, currentTime, player1BulletList)
        drawPlayerOneBullet(player1BulletList)
        # 显示物体
        MainGame.allSprites.draw(window)


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

运行一下,看看效果
在这里插入图片描述
哈哈,完成了

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

图片的美白与美化

博主简介 博主是一名大二学生&#xff0c;主攻人工智能研究。感谢让我们在CSDN相遇&#xff0c;博主致力于在这里分享关于人工智能&#xff0c;c&#xff0c;Python&#xff0c;爬虫等方面知识的分享。 如果有需要的小伙伴可以关注博主&#xff0c;博主会继续更新的&#xff0c…

Python雪花代码

前言 用python画个雪花玩玩&#xff0c;源码在文末公众号哈。 雪花类 class Snow(): #雪花类 def __init__(self): self.r 6 #雪花的半径 self.x ra.randint(-1000,1000) #雪花的横坐标 self.y ra.randint(-500,5…

读书笔记——《富爸爸穷爸爸》

《富爸爸穷爸爸》&#xff0c;以前不屑读这种书。这种书就是那种走进书店放在门口展销位的成功学著作&#xff0c;一眼看上去没什么实在的内容&#xff0c;看上去很不靠谱&#xff0c;感觉就是骗一些社会底层又做着暴富梦的人来买的&#xff0c;但是由于自身原因或环境局限根本…

MySQL基本查询

文章目录表的增删查改Create&#xff08;创建&#xff09;单行数据 全列插入多行数据 指定列插入插入否则更新替换Retrieve&#xff08;读取&#xff09;SELECT列全列查询指定列查询查询字段为表达式查询结果指定别名结果去重WHERE 条件基本比较BETWEEN AND 条件连接OR 条件连…

【面试题】Python软件工程师能力评估试题(一)

文章目录前言应试者需知&#xff08;一&#xff09;Python 语言基础能力评估1、理解问题并完成代码&#xff1a;2、阅读理解代码&#xff0c;并在空白处补充完整代码&#xff1a;3、编写一个装饰器&#xff1a;exposer4、阅读代码并在空白处补充完整代码&#xff1a;5、自行用P…

嵌入式 串口通信

目录 1、通信的基本概念 1.1 串行通信 1.2 并行通信 2、串行通信的特点 2.1 单工 2.2 半双工 2.3 全双工 3、串口在STM32的引脚 4、STM32的串口的接线 4.1 STM32的串口1和电脑通信的接线方式 4.2 单片机和具备串口的设备连接图 5、串口通信协议 6、串口通信…

linux进程管理

进程管理 进程是启动的可执行程序的一个指令 1、进程简介 &#xff08;1&#xff09;进程的组成部分 已分配内存的地址空间安全属性&#xff0c;包括所有权凭据和特权程序代码的一个或多个执行线程进程状态 &#xff08;2&#xff09;程序和进程的区别 程序是一个静态的二进制…

第十四届蓝桥杯第三期模拟赛 C/C++ B组 原题与详解

文章目录 一、填空题 1、1 找最小全字母十六进制数 1、1、1 题目描述 1、1、2 题解关键思路与解答 1、2 给列命名 1、2、1 题目描述 1、2、2 题解关键思路与解答 1、3 日期相等 1、3、1 题目描述 1、3、2 题解关键思路与解答 1、4 乘积方案数 1、4、1 题目描述 1、4、2 题解关…

28岁小公司程序员,无车无房不敢结婚,要不要转行?

大家好&#xff0c;这里是程序员晚枫&#xff0c;又来分享程序员的职场故事了~ 今天分享的这位朋友叫小青&#xff0c;我认识他2年多了。以前从事的是土木行业&#xff0c;2年前找我咨询转行程序员的学习路线和职业规划后&#xff0c;通过自学加入了一家创业公司&#xff0c;成…

分享几个常用的运维 shell 脚本

今天咸鱼给大家分享几个不错的 Linux 运维脚本&#xff0c;这些脚本中大量使用了 Linux 的文本三剑客&#xff1a; awkgrepsed 建议大家这三个工具都要了解并最好能够较为熟练的使用 根据 PID 显示进程所有信息 根据用户输入的PID&#xff0c;过滤出该PID所有的信息 #! /b…

第十四届蓝桥杯三月真题刷题训练——第 11 天

目录 第 1 题&#xff1a;卡片 题目描述 运行限制 第 2 题&#xff1a;路径_dpgcd 运行限制 第 3 题&#xff1a;字符统计 问题描述 输入格式 输出格式 样例输入 样例输出 评测用例规模与约定 运行限制 第 4 题&#xff1a;费用报销 第 1 题&#xff1a;卡片 题…

我今天要彻底搞懂线程状态的变化

&#x1f497;推荐阅读文章&#x1f497; &#x1f338;JavaSE系列&#x1f338;&#x1f449;1️⃣《JavaSE系列教程》&#x1f33a;MySQL系列&#x1f33a;&#x1f449;2️⃣《MySQL系列教程》&#x1f340;JavaWeb系列&#x1f340;&#x1f449;3️⃣《JavaWeb系列教程》…

MATLAB | 这些花里胡哨的热图怎么画

好早之前写过一个绘制相关系数矩阵的代码&#xff0c;但是会自动求相关系数&#xff0c;而且画出来的热图只能是方形&#xff0c;这里写一款允许nan值出现&#xff0c;任意形状的热图绘制代码&#xff0c;绘制效果如下&#xff1a; 如遇到bug请后台提出&#xff0c;并去gitee下…

出道即封神的ChatGPT,现在怎么样了?

从互联网的普及到智能手机&#xff0c;都让广袤的世界触手而及&#xff0c;如今身在浪潮中的我们&#xff0c;已深知其力。前阵子爆火的ChatGPT&#xff0c;不少人保持观望态度。现如今&#xff0c;国内关于ChatGPT的各大社群讨论&#xff0c;似乎沉寂了不少&#xff0c;现在怎…

Linux IPC:匿名管道 与 命名管道

目录一、管道的理解二、匿名管道三、命名管道四、管道的通信流程五、管道的特性进程间通信方式有多种&#xff0c;本文介绍的是管道&#xff0c;管道分为匿名管道和命名管道。 一、管道的理解 生活中的管道用来传输资源&#xff0c;例如水、石油之类的资源。而进程间通信的管道…

学习C++这几个网站足矣

文章目录cppreferencecplusplus[C 之父的网站](https://www.stroustrup.com/bs_faq.html)C提案[Cpp Core Guidelines](http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines)[C Super-FAQ](https://isocpp.org/faq)[learn c](https://www.learncpp.com/)[Awesome C](h…

【YOLOv8/YOLOv7/YOLOv5/YOLOv4/Faster-rcnn系列算法改进NO.59】引入ASPP模块

前言作为当前先进的深度学习目标检测算法YOLOv8&#xff0c;已经集合了大量的trick&#xff0c;但是还是有提高和改进的空间&#xff0c;针对具体应用场景下的检测难点&#xff0c;可以不同的改进方法。此后的系列文章&#xff0c;将重点对YOLOv8的如何改进进行详细的介绍&…

1.10-1.12 Makefile

1. Makefile简介 举个栗子&#xff0c;如下为redis-5.0.10的项目目录&#xff0c;有很多的文件 有了Makefile文件&#xff0c;可以简单的make一下就可以对项目文件进行编译&#xff0c;最终生成可执行程序。 2. Makefile栗子1 首先&#xff0c;创建vim Makefile按照PPT里的格…

C++STL set/multiset容器 构造和赋值 大小和交换 插入和删除 查找和统计

文章目录set/multiset容器1 set容器 基本概念2 set容器 构造和赋值3 set容器 大小和交换4 set容器 插入和删除5 set容器 查找和统计set/multiset容器 1 set容器 基本概念 简介&#xff1a; 所有元素都会在插入时会被自动排序&#xff0c;例如&#xff0c;在set容器放入元素1、…

成本降低90%,OpenAI正式开放ChαtGΡΤ

今天凌晨&#xff0c;OpenAI官方发布ChαtGΡΤ和Whisper的接囗&#xff0c;开发人员现在可以通过API使用最新的文本生成和语音转文本功能。OpenAI称&#xff1a;通过一系列系统级优化&#xff0c;自去年12月以来&#xff0c;ChαtGΡΤ的成本降低了90%&#xff1b;现在OpenAI用…