python项目:飞机大战已封装(第二部分)第一部分在飞机大战专辑,后期合并

资源

已经上传到文章顶部,本文耗时3小时
ε=(´ο`*)))唉 也不用给我 关注,点赞,谁叫我是良心博主呢,全部学习资源免费

定义敌机主类

class EnemyPlane():
    def __init__(self,x,y,screen):
        self.x = x
        self.y = y
        self.show = screen

        self.enemy_img2 = pygame.image.load('img/enemy2.png')
        # 加载敌机螺旋桨旋转图片
        self.enemy_img1 = pygame.image.load('img/enemy2_hit.png')
        # 敌机子弹列表
        self.di_Bulletlist = []
        # 敌机爆炸条件
        self.is_bomb = False
        # 敌机爆炸索引
        self.di_bomb_index = 0
        # 敌机爆炸图片
        self.di_bomb_list = ["img/enemy2_down1.png",
                            "img/enemy2_down2.png",
                            "img/enemy2_down3.png",
                            "img/enemy2_down4.png"]
        # 定义敌机初始移动方向
        self.direct = "left"

这一部分代码与我第一部分飞机大战博客里面的英雄机窗口属性同理这里就不做过多阐释,不同的地方就是图片与敌机自动移动的方向定义

敌机draw方法

    def draw(self):
        if self.is_bomb == False:
            if self.di_bomb_index == 0:
                screen.blit(self.enemy_img2, (self.x, self.y))
                self.di_bomb_index = 1
            else:
                screen.blit(self.enemy_img1, (self.x, self.y))
                self.di_bomb_index = 0
        else:
            #
            if self.di_bomb_index == len(self.di_bomb_list):
                time.sleep(0.22)
                exit(0)
            di_bomb_img = pygame.image.load(self.di_bomb_list[self.di_bomb_index])
            screen.blit(di_bomb_img, (self.x, self.y))
            self.di_bomb_index += 1
            time.sleep(0.2)
        self.move()
        self.bullet()

这段代码是一个方法draw(self)的实现,根据对象的状态来绘制游戏中的敌人对象。下面是对代码的总结:

  • 如果敌人对象不是炸弹(is_bomb == False):
    • 根据di_bomb_index的值来选择不同的敌人图像进行绘制,实现敌人对象的动画效果。
    • 切换敌人图像后,更新di_bomb_index的值以便下次绘制时使用另一张图像。
  • 如果敌人对象是炸弹(is_bomb == True):
    • 根据di_bomb_index的值选择要显示的炸弹图像,实现炸弹爆炸的动画效果。
    • 更新di_bomb_index的值以便下次绘制时使用下一张炸弹图像。
    • 使用time.sleep(0.2)来控制炸弹爆炸动画的速度。
  • 调用self.move()方法来移动敌人对象。
  • 调用self.bullet()方法来处理敌人对象的子弹行为。

这段代码实现了根据敌人对象的状态来绘制不同的图像,并在游戏中展示敌人对象的动画效果。
与英雄机draw方法同理

敌机自动移动代码实现

    def move(self):
        if self.direct == 'left':
            self.x -= 3
            if self.x <= 0:
                self.direct = 'right'
        elif self.direct == 'right':
            self.x += 3
            if self.x >= 480 - 60:
                self.direct = 'left'

这段代码是一个方法move(self)的实现,用于控制敌人对象在游戏中的移动。下面是对代码的总结:

  • 如果敌人对象的移动方向是向左(direct == 'left'):
    • 将敌人对象的横坐标x减去3,向左移动。
    • 如果敌人对象的横坐标x小于等于0,表示敌人对象已经到达屏幕左边缘,将移动方向设为向右(direct = 'right')。
  • 如果敌人对象的移动方向是向右(direct == 'right'):
    • 将敌人对象的横坐标x加上3,向右移动。
    • 如果敌人对象的横坐标x大于等于480 - 60,表示敌人对象已经到达屏幕右边缘,将移动方向设为向左(direct = 'left')。

这段代码实现了简单的左右移动逻辑,当敌人对象到达屏幕边缘时,会改变移动方向,从而让敌人对象在屏幕内来回移动。

敌机随机生成子弹代码实现

    def bullet(self):
        x = random.randint(1, 60)  # 用随机函数生成敌机子弹列表
        if x == 5 or x == 78:
            enemybullet = DiBullet(self.x + (69 + 5) / 2, self.y + 99, screen)
            self.di_Bulletlist.append(enemybullet)
        # 调用class:DiBullet里面的draw()绘制子弹
        for bullet1 in self.di_Bulletlist:
            bullet1.draw()

这段代码是一个方法bullet(self)的实现,用于控制敌人对象的子弹行为。下面是对代码的总结:

  • 通过random.randint(1, 60)随机生成一个整数x,用于控制敌人子弹的发射频率。
  • 如果生成的随机数x等于5或78:
    • 创建一个DiBullet对象enemybullet,并设置其初始位置为敌人对象的位置偏移量。
    • 将新创建的子弹对象添加到敌人对象的子弹列表di_Bulletlist中。
  • 遍历敌人对象的子弹列表di_Bulletlist
    • 对列表中的每个子弹对象调用draw()方法,以绘制子弹。

这段代码实现了敌人对象发射子弹的逻辑,根据随机数生成的值来控制子弹的发射频率,同时绘制和更新敌人对象发射的子弹。

检查敌机是否被英雄机子弹击中代码实现

    def jiangchepz(self,bullet_list):
        enemy_rect = pygame.rect.Rect(self.x, self.y, 69, 99)
        for bullet in bullet_list:
            bullet_rect = pygame.rect.Rect(bullet.x, bullet.y, 5, 12)
            falg = bullet_rect.colliderect(enemy_rect)
            if falg:
                print("你胜利了")
                self.is_bomb = True
                bullet_list.remove(bullet)

这段代码定义了一个方法jiangchepz(self, bullet_list),用于检测敌人对象和玩家子弹之间的碰撞。下面是对代码的总结:

  • 创建一个矩形enemy_rect来表示敌人对象的位置和大小。
  • 遍历传入的子弹列表bullet_list
    • 对于每个子弹对象,创建一个矩形bullet_rect来表示子弹的位置和大小。
    • 使用colliderect()方法检测敌人对象矩形和子弹矩形是否相交,将结果存储在flag变量中。
    • 如果碰撞发生(flag为True):
      • 打印"你胜利了",表示玩家击中了敌人对象。
      • 将敌人对象的is_bomb属性设置为True,表示敌人被击中。
      • 从子弹列表中移除当前碰撞的子弹对象。

这段代码实现了敌人对象和玩家子弹之间的碰撞检测,当玩家子弹击中敌人对象时,会触发相应的逻辑操作。

结尾调用已封装函数进入主循环

初始化设置

# 初始化游戏
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((480, 650))  # 创建一个480x500的窗口
# 修改游戏的名称和图标
pygame.display.set_caption("飞机大战")  # 设置游戏窗口标题为"飞机大战"
icon = pygame.image.load("img/icon.png")  # 加载游戏图标
pygame.display.set_icon(icon)  # 设置游戏图标
# 加载背景图片
bg_img = pygame.image.load('img/background.png')
hero_plane = HeroPlane(480 // 2 - 102 // 2, 650 - 126,screen)
enemy_plane = EnemyPlane(480 // 2 - 69 // 2, 0,screen)
pygame.key.set_repeat(20, 35)
hero_plane = HeroPlane(480 // 2 - 102 // 2, 650 - 126,screen)
  1. 创建一个英雄飞机对象hero_plane,位置位于屏幕水平中心偏移102的一半,垂直位置在屏幕底部减去126的位置,即居中底部。
enemy_plane = EnemyPlane(480 // 2 - 69 // 2, 0,screen)
  1. 创建一个敌人飞机对象enemy_plane,位置位于屏幕水平中心偏移69的一半,垂直位置在屏幕顶部。
pygame.key.set_repeat(20, 35)
  1. 使用pygame.key.set_repeat(20, 35)设置键盘重复事件的间隔时间,第一个参数20表示初始延迟时间(以毫秒为单位),第二个参数35表示之后的重复间隔时间(以毫秒为单位)。

主循环

clock = pygame.time.Clock()
while True:
    #
    clock.tick(50)
    # 显示背景
    screen.blit(bg_img, (0, 0))
    #
    enemy_plane.jiangchepz(hero_plane.hero_Bulletlist)
    hero_plane.jiangchepz(enemy_plane.di_Bulletlist)
    hero_plane.draw()
    enemy_plane.draw()
    hero_plane.xunghuang(pygame.event.get())
    pygame.display.update()

这段代码展示了一个游戏主循环,其中包含了以下关键步骤:

  1. 创建一个pygame.time.Clock()对象来控制游戏循环的帧率。
  2. 在一个无限循环中,使用clock.tick(50)来限制游戏帧率为每秒50帧。
  3. 使用screen.blit(bg_img, (0, 0))来在屏幕上显示背景图像。
  4. 调用敌人飞机对象enemy_planejiangchepz()方法来检测敌人飞机和玩家飞机子弹的碰撞。
  5. 调用玩家飞机对象hero_planejiangchepz()方法来检测玩家飞机和敌人飞机子弹的碰撞。
  6. 调用hero_planedraw()方法和enemy_planedraw()方法来绘制玩家飞机和敌人飞机。
  7. 调用hero_planexunghuang()方法来处理玩家飞机的移动和射击操作,根据pygame.event.get()获取的事件。
  8. 使用pygame.display.update()来更新屏幕显示。

这段代码组成了游戏的主循环,负责控制游戏的逻辑运行、碰撞检测、绘制和用户输入处理。

完整代码

import random
import time
import pygame
# 定义英雄子弹
class HeroBullet:
    """英雄精灵子弹的类"""
    def __init__(self,x,y,screen):
        self.x = x
        self.y = y
        self.show = screen
        self.pic = pygame.image.load("img/bullet1.png")

        # 画子弹

    def draw(self):
        self.show.blit(self.pic, (self.x, self.y))
        self.move()

        # 子弹移动

    def move(self):
        self.y -= 5
#定义敌机子弹
class DiBullet:
    def __init__(self,x,y,screen):
        self.x = x
        self.y = y
        self.show = screen
        self.pic = pygame.image.load("img/bullet2.png")

    # 画子弹
    def draw(self):
        self.show.blit(self.pic,(self.x,self.y))
        self.move()

    # 子弹移动
    def move(self):
        self.y += 5
#定义英雄类
class HeroPlane():
    """英雄战机类"""
    def __init__(self,x,y,screen):
        self.x = x
        self.y = y
        self.show = screen
        # 英雄机设置
        # 加载背景图片
        self.bg_img = pygame.image.load('img/background.png')
        # 加载英雄机
        self.hero_plane1 = pygame.image.load('img/me2.png')
        self.hero_plane2 = pygame.image.load('img/me1.png')
        self.hero_rect = pygame.Rect(190, 526, 66, 80)  # 创建一个矩形表示英雄机的位置和大小
        self.heroPlaneX = self.hero_rect.x  # 英雄机的x坐标
        self.heroPlaneY = self.hero_rect.y  # 英雄机的y坐标
        # 定义图片切换索引
        self.hero_imgindex = 0

        # 战机子弹列表
        self.hero_Bulletlist = []
        # 战机爆炸条件
        self.hero_bomb = False
        # 战机爆炸索引
        self.hero_bomb_index = 0
        # 定义英雄子弹
        # 加载英雄机爆炸图片
        self.hero_bomb_img = ['img/me_destroy_1.png',
                         'img/me_destroy_2.png',
                         'img/me_destroy_3.png',
                         'img/me_destroy_4.png']

    def draw(self):
        if self.hero_bomb == False:
            # 显示战机
            if self.hero_bomb_index == 0:
                screen.blit(self.hero_plane1, (self.x, self.y))
                self.hero_bomb_index = 1
            else:
                screen.blit(self.hero_plane2, (self.x, self.y))
                self.hero_bomb_index = 0
        else:
            if self.hero_bomb_index == len(self.hero_bomb_img):
                time.sleep(0.22)
                exit()
            self.hero_bomb_imgs = pygame.image.load(self.hero_bomb_img[self.hero_bomb_index])
            screen.blit(self.hero_bomb_imgs, (self.x, self.y))
            self.hero_bomb_index += 1
            time.sleep(0.2)
    def xunghuang(self,event_list):
        # 战机底部飞入
        self.y -= 2
        if self.y <= 0:
            self.y = 500

        # 获取所有监听事件
        self.event_list = pygame.event.get()
        # 获取窗口退出事件
        for event in event_list:
            if event.type == pygame.QUIT:
                print("游戏结束了")
                # 卸载模块
                pygame.quit()
                exit(0)

            # 战机移动
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    self.x = self.x - 10 if self.x >= 5 else 0
                elif event.key == pygame.K_RIGHT:
                    self.x = self.x + 10 if self.x <= 370 else 380
                elif event.key == pygame.K_UP:
                    self.y = self.y - 10 if self.y >= 5 else 0
                elif event.key == pygame.K_DOWN:
                    self.y = self.y + 20 if self.y <= 521 else 526
                elif event.key == pygame.K_SPACE:  # 控制英雄机发射子弹
                    hero_bullet = HeroBullet(self.x + 40 + 10, self.y - 11, screen)
                    self.hero_Bulletlist.append(hero_bullet)
        #
        # 调用函数画出战机子弹并判断子弹是否相交
        for bullet in self.hero_Bulletlist:
            bullet.draw()
    def jiangchepz(self,hero_Bulletlist):
        hero_rect = pygame.rect.Rect(self.x, self.y, 102, 126)
        for bullet in hero_Bulletlist:
            # 定义战机子弹的rect
            bullet_rect = pygame.rect.Rect(bullet.x, bullet.y, 5, 12)
            # 检测敌机和子弹矩形是否相交
            flag = bullet_rect.colliderect(hero_rect)
            # 如果相交
            if flag:
                print("你输了")
                self.hero_bomb = True
                hero_Bulletlist.remove(bullet)
#定义敌机类
class EnemyPlane():
    def __init__(self,x,y,screen):
        self.x = x
        self.y = y
        self.show = screen

        self.enemy_img2 = pygame.image.load('img/enemy2.png')
        # 加载敌机螺旋桨旋转图片
        self.enemy_img1 = pygame.image.load('img/enemy2_hit.png')
        # 敌机子弹列表
        self.di_Bulletlist = []
        # 敌机爆炸条件
        self.is_bomb = False
        # 敌机爆炸索引
        self.di_bomb_index = 0
        # 敌机爆炸图片
        self.di_bomb_list = ["img/enemy2_down1.png",
                            "img/enemy2_down2.png",
                            "img/enemy2_down3.png",
                            "img/enemy2_down4.png"]
        # 定义敌机初始移动方向
        self.direct = "left"

    def draw(self):
        if self.is_bomb == False:
            if self.di_bomb_index == 0:
                screen.blit(self.enemy_img2, (self.x, self.y))
                self.di_bomb_index = 1
            else:
                screen.blit(self.enemy_img1, (self.x, self.y))
                self.di_bomb_index = 0
        else:
            #
            if self.di_bomb_index == len(self.di_bomb_list):
                time.sleep(0.22)
                exit(0)
            di_bomb_img = pygame.image.load(self.di_bomb_list[self.di_bomb_index])
            screen.blit(di_bomb_img, (self.x, self.y))
            self.di_bomb_index += 1
            time.sleep(0.2)
        self.move()
        self.bullet()

    def move(self):
        if self.direct == 'left':
            self.x -= 3
            if self.x <= 0:
                self.direct = 'right'
        elif self.direct == 'right':
            self.x += 3
            if self.x >= 480 - 60:
                self.direct = 'left'

    def bullet(self):
        x = random.randint(1, 60)  # 用随机函数生成敌机子弹列表
        if x == 5 or x == 78:
            enemybullet = DiBullet(self.x + (69 + 5) / 2, self.y + 99, screen)
            self.di_Bulletlist.append(enemybullet)
        # 调用class:DiBullet里面的draw()绘制子弹
        for bullet1 in self.di_Bulletlist:
            bullet1.draw()

    def jiangchepz(self,bullet_list):
        enemy_rect = pygame.rect.Rect(self.x, self.y, 69, 99)
        for bullet in bullet_list:
            bullet_rect = pygame.rect.Rect(bullet.x, bullet.y, 5, 12)
            falg = bullet_rect.colliderect(enemy_rect)
            if falg:
                print("你胜利了")
                self.is_bomb = True
                bullet_list.remove(bullet)




# 初始化游戏
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((480, 650))  # 创建一个480x500的窗口
# 修改游戏的名称和图标
pygame.display.set_caption("飞机大战")  # 设置游戏窗口标题为"飞机大战"
icon = pygame.image.load("img/icon.png")  # 加载游戏图标
pygame.display.set_icon(icon)  # 设置游戏图标
# 加载背景图片
bg_img = pygame.image.load('img/background.png')

#
hero_plane = HeroPlane(480 // 2 - 102 // 2, 650 - 126,screen)
#
enemy_plane = EnemyPlane(480 // 2 - 69 // 2, 0,screen)
#
pygame.key.set_repeat(20, 35)
#
clock = pygame.time.Clock()
while True:
    #
    clock.tick(50)
    # 显示背景
    screen.blit(bg_img, (0, 0))
    #
    enemy_plane.jiangchepz(hero_plane.hero_Bulletlist)
    hero_plane.jiangchepz(enemy_plane.di_Bulletlist)
    hero_plane.draw()
    enemy_plane.draw()
    hero_plane.xunghuang(pygame.event.get())
    pygame.display.update()

  • 40
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值