python项目(课设)——飞机大战小游戏项目源码(pygame)

2024-06-21 18:04

本文主要是介绍python项目(课设)——飞机大战小游戏项目源码(pygame),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 主程序


import pygame

from plane_sprites import *

class PlaneGame:
    """
    游戏类
    """
    def __init__(self):
        print("游戏初始化")
        # 初始化字体模块
        pygame.font.init()
        # 创建游戏窗口
        self.screen = pygame.display.set_mode(SCREEN_RECT.size)
        # 常见游戏时钟
        self.clock = pygame.time.Clock()
        # 调用私有创建精灵的方法,创建精灵和精灵组
        self.__create_sprites()
        # 设置定时器事件,创建敌机,时间1s
        pygame.time.set_timer(CREATE_ENEMY_EVENT,1000)
        # 设置定时器事件,发射子弹
        pygame.time.set_timer(HERO_FIRE_EVENT,500)

    def __create_sprites(self):
        # 创建精灵和精灵组
        bg1 = Background()
        bg2 = Background(True)
        # bg2.rect.y = -SCREEN_RECT.height
        self.back_group = pygame.sprite.Group(bg1, bg2)
        # 创建敌机的精灵组
        self.enemy_group = pygame.sprite.Group()
        # 建立英雄飞机精灵和精灵组
        self.hero = Hero()
        self.hero_groups = pygame.sprite.Group(self.hero)

    def start_game(self):
        print("游戏开始")
        while True:
            # 1.设置刷新帧率
            self.clock.tick(FRAME_PER_SECTION)
            # 2.事件监听
            self.__event_handle()
            # 3.碰撞检测
            self.__check_collide()
            # 4.更新/绘制精灵组
            self.__update_sprites()
            # 5.更新显示
            pygame.display.update()

    def __event_handle(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                PlaneGame.__game_over()
            elif event.type == CREATE_ENEMY_EVENT:
                print("敌机出现")
                # 创建敌机精灵
                enemy = Enemy()
                # 将精灵添加到精灵组中
                self.enemy_group.add(enemy)
            # elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
            #     self.hero.rect.x += 5
            # elif event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
            #     self.hero.rect.x -= 5
            elif event.type == HERO_FIRE_EVENT:
                self.hero.fire()
        # 使用键盘的方法获取按键
        key_pressed = pygame.key.get_pressed() # 获取按键元组
        # 判断元组中对应按键索引
        if key_pressed[pygame.K_RIGHT]:
            self.hero.speed_x = 2
            self.hero.update()
            self.hero.speed_x = 0
        if key_pressed[pygame.K_LEFT]:
            self.hero.speed_x = -2
            self.hero.update()
            self.hero.speed_x = 0
        if key_pressed[pygame.K_UP]:
            self.hero.speed_y = -3
            self.hero.update()
            self.hero.speed_y = 0
        if key_pressed[pygame.K_DOWN]:
            self.hero.speed_y = 3
            self.hero.update()
            self.hero.speed_y = 0

    def __check_collide(self):
        # 1.子弹打飞机
        pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)
        # 2.英雄飞机撞敌机
        enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)
        # 3.判断列表内容
        if len(enemies) > 0:
            #self.hero.kill()
            # 结束游戏
            PlaneGame.__game_over()

    def __update_sprites(self):
        self.back_group.update()
        self.back_group.draw(self.screen)
        self.enemy_group.update()
        self.enemy_group.draw(self.screen)
        self.hero_groups.update()
        self.hero_groups.draw(self.screen)
        self.hero.bullets.update()
        self.hero.bullets.draw(self.screen)

    @staticmethod
    def __game_over():
        print("游戏结束")
        # 清屏
        pygame.display.get_surface().fill((0, 0, 0))
        # 设置字体
        font = pygame.font.SysFont("arial", 72)  # 字体和字号
        # 渲染文本
        text_surface = font.render("GAME_OVER", True, (255, 0, 0))
        # 获取文本矩形
        text_rect = text_surface.get_rect(center=(SCREEN_RECT.width // 2, SCREEN_RECT.height // 2))
        # 将文本绘制到窗口
        pygame.display.get_surface().blit(text_surface, text_rect)
        # 更新显示
        pygame.display.update()
        # 等3秒
        pygame.time.delay(3000)
        pygame.quit()  # 卸载所有模块
        exit()

if __name__ == "__main__":
    print("游戏开始")
    # 创建游戏对象
    game = PlaneGame()
    # 启动游戏
    game.start_game()

辅助程序

import pygame
import random
# 屏幕大小的常量
SCREEN_RECT = pygame.Rect(0, 0, 480, 700)
FRAME_PER_SECTION = 60
# 创建敌机定时器常量
CREATE_ENEMY_EVENT = pygame.USEREVENT
# 英雄发射子弹的事件
HERO_FIRE_EVENT = pygame.USEREVENT + 1class GameSprite(pygame.sprite.Sprite):"""游戏精灵类"""def __init__(self, image_name, speed=1):# 调用父类的初始化方法super().__init__()self.image = pygame.image.load(image_name)self.speed = speedself.rect = self.image.get_rect() # 默认位置(0,0)def update(self):# 屏幕垂直方向移动self.rect.y += self.speedclass Background(GameSprite):"""游戏背景"""def __init__(self, is_alt = False):# 1.调用父类的初始方法,指定图片super().__init__("images/background.png")# 2.判断是否为第二张图片,如果是需要指定.if is_alt:self.rect.y = -self.rect.heightdef update(self):# 1.调用父类方法super().update()# 2.判断背景是否移出屏幕,如果移出屏幕则移动到屏幕的上方if self.rect.y >= SCREEN_RECT.height:self.rect.y = -SCREEN_RECT.heightclass Enemy(GameSprite):"""创建敌机类"""def __init__(self):# 1.调用父类的初始方法,指定图片super().__init__("images/enemy1.png")# 2.指定敌机的初始随机速度self.speed = random.randint(1,3)# 3.指定敌机的初始随机位置self.rect.bottom = 0max_x = SCREEN_RECT.width - self.rect.widthself.rect.x = random.randint(0,max_x)def update(self):# 1.调用父类方法,保证垂直移动super().update()# 2.判断是否飞出屏幕,飞出则从敌机精灵组删除if self.rect.y >= SCREEN_RECT.height:# print("飞出屏幕")# 飞出屏幕,kill来删除self.kill()def __del__(self):# print("飞机坠机了")passclass Hero(GameSprite):"""英雄飞机"""def __init__(self):# 1.调用父类方法,竖直方向上不移动super().__init__("images/me1.png",speed = 0)# 2.设置初始位置self.rect.centerx = SCREEN_RECT.centerxself.rect.bottom = SCREEN_RECT.bottom - 120# 3.创建子弹精灵组self.bullets = pygame.sprite.Group()self.speed_x = 0self.speed_y = 0def update(self):# 水平移动self.rect.x += self.speed_x# 垂直移动self.rect.y += self.speed_y# 控制飞机飞出边界if self.rect.x <= 0 or self.rect.right >= SCREEN_RECT.width:self.rect.x -= self.speed_xself.rect.y -= self.speed_ydef fire(self):print("发射子弹")for i in range(0, 3):# 1.创建子弹精灵bullet = Bullet()# 2.设置子弹精灵的位置bullet.rect.bottom = self.rect.y - i * 20bullet.rect.centerx = self.rect.centerx# 3.子弹加入到子弹精灵组self.bullets.add(bullet)class Bullet(GameSprite):"""子弹类"""def __init__(self):# 调用父类方法设置子弹图片和位置super().__init__("images/bullet1.png", speed=-2)def update(self):# 调用父类方法,垂直飞行super().update()# 判断子弹是否飞出屏幕if self.rect.bottom < 0:self.kill()def __del__(self):print("子弹销毁")

这篇关于python项目(课设)——飞机大战小游戏项目源码(pygame)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1081933

相关文章

Python进行JSON和Excel文件转换处理指南

《Python进行JSON和Excel文件转换处理指南》在数据交换与系统集成中,JSON与Excel是两种极为常见的数据格式,本文将介绍如何使用Python实现将JSON转换为格式化的Excel文件,... 目录将 jsON 导入为格式化 Excel将 Excel 导出为结构化 JSON处理嵌套 JSON:

Python操作PDF文档的主流库使用指南

《Python操作PDF文档的主流库使用指南》PDF因其跨平台、格式固定的特性成为文档交换的标准,然而,由于其复杂的内部结构,程序化操作PDF一直是个挑战,本文主要为大家整理了Python操作PD... 目录一、 基础操作1.PyPDF2 (及其继任者 pypdf)2.PyMuPDF / fitz3.Fre

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统

python中列表应用和扩展性实用详解

《python中列表应用和扩展性实用详解》文章介绍了Python列表的核心特性:有序数据集合,用[]定义,元素类型可不同,支持迭代、循环、切片,可执行增删改查、排序、推导式及嵌套操作,是常用的数据处理... 目录1、列表定义2、格式3、列表是可迭代对象4、列表的常见操作总结1、列表定义是处理一组有序项目的

python运用requests模拟浏览器发送请求过程

《python运用requests模拟浏览器发送请求过程》模拟浏览器请求可选用requests处理静态内容,selenium应对动态页面,playwright支持高级自动化,设置代理和超时参数,根据需... 目录使用requests库模拟浏览器请求使用selenium自动化浏览器操作使用playwright

python使用try函数详解

《python使用try函数详解》Pythontry语句用于异常处理,支持捕获特定/多种异常、else/final子句确保资源释放,结合with语句自动清理,可自定义异常及嵌套结构,灵活应对错误场景... 目录try 函数的基本语法捕获特定异常捕获多个异常使用 else 子句使用 finally 子句捕获所

Python极速搭建局域网文件共享服务器完整指南

《Python极速搭建局域网文件共享服务器完整指南》在办公室或家庭局域网中快速共享文件时,许多人会选择第三方工具或云存储服务,但这些方案往往存在隐私泄露风险或需要复杂配置,下面我们就来看看如何使用Py... 目录一、android基础版:HTTP文件共享的魔法命令1. 一行代码启动HTTP服务器2. 关键参

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

Python获取浏览器Cookies的四种方式小结

《Python获取浏览器Cookies的四种方式小结》在进行Web应用程序测试和开发时,获取浏览器Cookies是一项重要任务,本文我们介绍四种用Python获取浏览器Cookies的方式,具有一定的... 目录什么是 Cookie?1.使用Selenium库获取浏览器Cookies2.使用浏览器开发者工具

Python实现批量提取BLF文件时间戳

《Python实现批量提取BLF文件时间戳》BLF(BinaryLoggingFormat)作为Vector公司推出的CAN总线数据记录格式,被广泛用于存储车辆通信数据,本文将使用Python轻松提取... 目录一、为什么需要批量处理 BLF 文件二、核心代码解析:从文件遍历到数据导出1. 环境准备与依赖库