欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python实现飞机大战游戏

程序员文章站 2022-07-22 09:08:41
飞机大战(python)代码分为两个python文件,工具类和主类,需要安装pygame模块,能完美运行(网上好多不完整的,调试得心累。实现出来,成就感还是满满的),如图所...

为了熟悉Python基础语法,学习了一个经典的案例:飞机大战,最后实现效果如下:

Python实现飞机大战游戏
实现步骤:

①下载64位对应python版本的pygamepygame-1.9.6-cp38-cp38-win_amd64.whl

② 更新pippython -m pip install --upgrade pip

③ 安装pygamepip install pygame-1.9.6-cp38-cp38-win_amd64.whl

④ 实现代码如下:

import sys  # 导入系统模块
import random  # 随机数模块
import pygame  # 导入pygame模块
import pygame.locals  # 导入pygame本地策略

ICO_PATH = "images/app.ico"  # APP_ICO
APP_NAME = "飞机大战V1.0"  # APP_NAME
Enemy_IMGS = ("images/enemy1.png", "images/enemy2.png")  # ENEMY_IMGS


# TODO 定义一个公共类
class Model:
    window = None  # 主窗体window对象

    # 初始化函数
    def __init__(self, img_path, x, y):
        self.img = pygame.image.load(img_path)
        self.x = x
        self.y = y

    # 将图片填充到背景中
    def display(self):
        Model.window.blit(self.img, (self.x, self.y))


# TODO 背景
class Background(Model):
    # 背景移动
    def move(self):
        if self.y <= Game.WINDOW_HEIGHT:
            self.y += 1
        else:
            self.y = 0

    # 背景图片展示
    def display(self):
        Model.window.blit(self.img, (self.x, self.y))  # 填充背景
        Model.window.blit(self.img, (self.x, self.y - Game.WINDOW_HEIGHT))  # 填充辅助背景


# TODO 玩家类
class PlayerPlane(Model):
    def __init__(self, img_path, x, y):
        super().__init__(img_path, x, y)
        # 子弹
        self.bullets = []

    def display(self, enemys):
        super().display()
        remove_bullets = []
        for bullet in self.bullets:

            bullet.move()
            bullet.display()
            # 如果子弹小于消失于屏幕,删除子弹
            if bullet.y < -11:
                remove_bullets.append(bullet)
            # 子弹的矩阵
            bullet_rect = pygame.locals.Rect(bullet.x, bullet.y, 5, 11)
            # TODO 进行碰撞检测
            for enemy in enemys:
                # 敌机的矩阵
                enemy_rect = pygame.locals.Rect(enemy.x, enemy.y, 57, 43)
                # 如果碰撞
                if pygame.Rect.colliderect(bullet_rect, enemy_rect):
                    # 随机修改敌机的位置模拟敌机销毁并生成新敌机并删除子弹
                    enemy.img = pygame.image.load(Enemy_IMGS[random.randint(0, 1)])
                    enemy.x = random.randint(0, Game.WINDOW_WIDTH - 57)
                    enemy.y = random.randint(-Game.WINDOW_WIDTH, -43)
                    remove_bullets.append(bullet)
                    break

        for bullet in remove_bullets:
            self.bullets.remove(bullet)


# TODO 敌机类
class EnemyPlane(Model):
    def __init__(self):
        self.img = pygame.image.load(Enemy_IMGS[random.randint(0, 1)])
        self.x = random.randint(0, Game.WINDOW_WIDTH - 57)
        self.y = random.randint(-Game.WINDOW_WIDTH, -43)

    def move(self):
        if self.y > Game.WINDOW_HEIGHT:
            self.y = -43  # 返回初始位置
        else:
            self.y += 1


# TODO 子弹类
class Bullet(Model):
    def move(self):
        self.y -= 1


# TODO 游戏类
class Game:
    WINDOW_WIDTH = 410
    WINDOW_HEIGHT = 614

    # 初始化操作
    def __init__(self):
        self.window = pygame.display.set_mode([Game.WINDOW_WIDTH, Game.WINDOW_HEIGHT])  # 窗口的设置
        self.background = Background("images/background.png", 0, 0)  # 窗体模型的设置

        self.player = PlayerPlane("images/me1.png", 180, 400)
        self.enemyPlanes = []
        for _ in range(5):
            self.enemyPlanes.append(EnemyPlane())

    # 游戏的入口函数
    def run(self):
        self.frame_init()
        while True:
            self.background.move()  # 背景向上移动,模拟环境移动
            self.background.display()  # 将图片塞入到窗体中

            self.player.display(self.enemyPlanes)

            for enemy in self.enemyPlanes:
                enemy.move()
                enemy.display()

            pygame.display.update()  # 刷新窗体
            self.event_init()  # 监听事件

    # 初始化窗口
    def frame_init(self):
        Model.window = self.window  # 将window对象赋值给Model公有类
        ico = pygame.image.load(ICO_PATH)  # 加载图片
        pygame.display.set_icon(ico)  # 设置icon
        pygame.display.set_caption(APP_NAME)  # 设置app_name

    # 事件初始化方法
    def event_init(self):
        for event in pygame.event.get():
            # 关闭事件
            if event.type == pygame.locals.QUIT:
                sys.exit()
            # 监听鼠标事件
            if event.type == pygame.locals.MOUSEMOTION:
                pos = pygame.mouse.get_pos()
                self.player.x = pos[0] - 51
                self.player.y = pos[1] - 63
        focus_state = pygame.mouse.get_pressed()
        if focus_state[0] == 1:
            pos = pygame.mouse.get_pos()
            self.player.bullets.append(Bullet("images/bullet1.png", pos[0], pos[1] - 75))


if __name__ == "__main__":
    Game().run()

本文地址:https://blog.csdn.net/qq_38697437/article/details/109246590