python实现飞机大战小游戏


Posted in Python onNovember 08, 2019

本文实例为大家分享了python实现飞机大战的具体代码,供大家参考,具体内容如下

初学Python,写了一个简单的Python小游戏。

师出bilibili某前辈

pycharm自带了第三方库pygame,安装一下就好了,很方便。

虽然很多大佬已经给出了步骤,我这里还是??乱幌拢?参?俗约汗?桃幌隆?/p>

上图:

python实现飞机大战小游戏

python实现飞机大战小游戏

这里再给出代码的逻辑架构

python实现飞机大战小游戏

plane_main.py

import pygame
from plane_sprites import *

class PlaneGame(object):
 """飞机大战主游戏"""
 def __init__(self):
 print("游戏初始化")
 #1.创建游戏窗口
 self.screen=pygame.display.set_mode(SCREEN_RECT.size)
 #2.创建游戏的时钟
 self.clock=pygame.time.Clock()
 #3.调用私有方法,精灵和精灵组的创建
 self.__creat_sprites()
 #4.设置定时器事件-1s敌机出现
 pygame.time.set_timer(CREATE_ENEMY_EVENT,1000)
 pygame.time.set_timer(HERO_FIRE_EVENT, 500)

 def __creat_sprites(self):
 # 创建精灵
 bg1 = Background()
 bg2 = Background(True)
 # 创建精灵组
 self.back_group = pygame.sprite.Group(bg1,bg2)
 #创建敌机的精灵组
 self.enemy_group=pygame.sprite.Group()
 #创建英雄的精灵和精灵组
 self.hero=Hero()
 self.hero_group=pygame.sprite.Group(self.hero)
 self.enemy_hit_group=pygame.sprite.Group();



 def start_game(self):
 print("游戏开始.....")
 while True:
 #1.设置刷新帧率
 self.clock.tick(FRAME_PER_SEC)

 #2.事件监听
 self.__event_handler()

 #3.碰撞检测
 self.__check_collide()

 #4.更新绘制精灵组
 self.__update_sprites()

 #5.更新显示
 pygame.display.update()

 def __event_handler(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==HERO_FIRE_EVENT:
 self.hero.fire()
 #elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
 #print("向右移动....")
 #使用键盘模块
 keys_pressed=pygame.key.get_pressed()
 #判断元组中对应的按键索引值
 if keys_pressed[pygame.K_RIGHT]:
 self.hero.speed=3
 elif keys_pressed[pygame.K_LEFT]:
 self.hero.speed = -3
 else:
 self.hero.speed = 0


 def __check_collide(self):
 #1.子弹摧毁敌机
 enemy_hit = pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)

 

 #2.敌机撞毁英雄
 enemies=pygame.sprite.spritecollide(self.hero,self.enemy_group,True)
 if len(enemies)>0:
 #让英雄牺牲
 # self.hero.explode()
 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_group.update()
 self.hero_group.draw(self.screen)
 self.hero.bullets.update()
 self.hero.bullets.draw(self.screen)

 @staticmethod
 def __game_over():
 print("游戏结束")
 pygame.quit()
 exit()


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

plane_sprites.py

import random
import pygame
#屏幕大小常量
SCREEN_RECT=pygame.Rect(0,0,480,700)
#刷新帧率
FRAME_PER_SEC=60
explode_index=0
#创建定时器常量
CREATE_ENEMY_EVENT=pygame.USEREVENT
#创建发射子弹事件
HERO_FIRE_EVENT=pygame.USEREVENT+1
class GameSprite(pygame.sprite.Sprite):
 """飞机大战游戏精灵"""
 def __init__(self,image_name,speed=1):

 # 调用父类的初始化方法
 super().__init__()
 # 定义对象的属性
 self.image=pygame.image.load(image_name)
 self.rect=self.image.get_rect()
 self.speed=speed
 def update(self):
 #在屏幕的垂直方向运动
 self.rect.y+=self.speed

class Background(GameSprite):
 """游戏背景精灵"""
 def __init__(self,is_alt=False):
 #1.调用父类方法,实现精灵创建(image/rect/speed)
 super().__init__("./images/background.png")
 #2.判断是否是交替图像
 if is_alt:
 self.rect.y = -self.rect.height
 def update(self):
 #1.调用父类方法实现
 super().update()
 #2.判断图像是否移除屏幕,若移除,则设置到屏幕上面
 if self.rect.y>=SCREEN_RECT.height:
 self.rect.y= -self.rect.height

class Enemy(GameSprite):
 """敌机精灵"""

 def __init__(self):
 #1.调用父类方法,创建敌机精灵,指定敌机图片
 super().__init__("./images/enemy1.png")
 #2.指定敌机的初始随机速度1-3
 self.speed=random.randint(1,3)
 #3.指定敌机的初始随机位置
 self.rect.bottom=0
 max_x=SCREEN_RECT.width-self.rect.width
 self.rect.x=random.randint(0,max_x)
 self.explode_index=0
 def update(self):
 #1.调用父类方法,保持垂直方向飞行
 super().update()
 #2.判断是否飞出屏幕,如果是,则删除精灵
 if self.rect.y>=SCREEN_RECT.height:
 #kill方法可以将精灵从精灵组中移出,精灵就会被自动销毁,然后调用下面方法
 self.kill()
 #if self.explode_index==5:
 #return
 if self.explode_index!=0:
 new_rect=self.rect
 super.__init__("./images/enemy1_down1.png")
 self.explode_index=self.explode_index+1
 self.rect=new_rect


 def __del__(self):
 # print("敌机挂了%s"% self.rect)
 pass
class Hero(GameSprite):
 """英雄精灵"""
 def __init__(self):
 #1.调用父类方法
 super().__init__("./images/me1.png",0)
 #2.设置英雄的初始位置
 self.rect.centerx=SCREEN_RECT.centerx
 self.rect.bottom=SCREEN_RECT.bottom-120
 #创建子弹精灵组
 self.bullets=pygame.sprite.Group()
 def update(self):
 self.rect.x+=self.speed
 if self.rect.x<0:
 self.rect.x=0
 elif self.rect.right>SCREEN_RECT.right:
 self.rect.right=SCREEN_RECT.right
 def fire(self):
 print("发射子弹...")
 for i in (0,1,2):
 #1.创建精灵组
 bullet=Bullet()
 #2.设置精灵位置
 bullet.rect.bottom=self.rect.y-i*20
 bullet.rect.centerx=self.rect.centerx
 #3.添加到精灵组
 self.bullets.add(bullet)
 def explode(self,screen):
 new_rect=self.rect
 for i in (1,2,3,4):
 super.__init__("./images/me_destroy_2.png")
 self.rect.centerx=new_rect.centerx
 self.rect.centery=new_rect.centery
 screen.blit(self.image,(self.rect.x,self.rect.y))
 pygame.display.update()
class Bullet(GameSprite):
 """子弹精灵"""
 def __init__(self):
 #调用父类方法,设置子弹图片,设置初始速度
 super().__init__("./images/bullet1.png",-2)
 def update(self):
 #让子弹垂直运行
 super().update()
 if self.rect.bottom<0:
 self.kill()
 def __del__(self):
 print("子弹被销毁")

运行结果:

python实现飞机大战小游戏

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python的Django框架中TEMPLATES项的设置教程
May 29 Python
分享Python字符串关键点
Dec 13 Python
python 安装virtualenv和virtualenvwrapper的方法
Jan 13 Python
Python数据结构之双向链表的定义与使用方法示例
Jan 16 Python
python判断一个集合是否为另一个集合的子集方法
May 04 Python
python使用celery实现异步任务执行的例子
Aug 28 Python
详解python中*号的用法
Oct 21 Python
Python通过VGG16模型实现图像风格转换操作详解
Jan 16 Python
python时间日期操作方法实例小结
Feb 06 Python
Python打包工具PyInstaller的安装与pycharm配置支持PyInstaller详细方法
Feb 27 Python
scrapy中如何设置应用cookies的方法(3种)
Sep 22 Python
如何在scrapy中集成selenium爬取网页的方法
Nov 18 Python
python 基于dlib库的人脸检测的实现
Nov 08 #Python
numpy数组做图片拼接的实现(concatenate、vstack、hstack)
Nov 08 #Python
python实现身份证实名认证的方法实例
Nov 08 #Python
Python Django框架模板渲染功能示例
Nov 08 #Python
Python Django中间件,中间件函数,全局异常处理操作示例
Nov 08 #Python
Django框架下静态模板的继承操作示例
Nov 08 #Python
python中自带的三个装饰器的实现
Nov 08 #Python
You might like
基于命令行执行带参数的php脚本并取得参数的方法
2016/01/25 PHP
win10环境PHP 7 安装配置【教程】
2016/05/09 PHP
php的无刷新操作实现方法分析
2020/02/28 PHP
JS中产生20位随机数以0-9为例也可以是a-z A-Z
2014/08/01 Javascript
AngularJS实现分页显示数据库信息
2016/07/01 Javascript
jquery插件bootstrapValidator表单验证详解
2016/12/15 Javascript
javascript稀疏数组(sparse array)和密集数组用法分析
2016/12/28 Javascript
JavaScript实现水平进度条拖拽效果
2017/01/18 Javascript
Bootstrap输入框组件简单实现代码
2017/03/06 Javascript
基于canvas粒子系统的构建详解
2017/08/31 Javascript
从对象列表中获取一个对象的方法,依据关键字和值
2017/09/20 Javascript
Vue实现搜索 和新闻列表功能简单范例
2018/03/16 Javascript
react+redux仿微信聊天界面
2019/06/21 Javascript
解决vue项目中页面调用数据 在数据加载完毕之前出现undefined问题
2019/11/14 Javascript
JavaScript 面向对象程序设计详解【类的创建、实例对象、构造函数、原型等】
2020/05/12 Javascript
[54:15]DOTA2-DPC中国联赛 正赛 DLG vs Dragon BO3 第二场2月1日
2021/03/11 DOTA
在Python中使用CasperJS获取JS渲染生成的HTML内容的教程
2015/04/09 Python
python控制台中实现进度条功能
2015/11/10 Python
Fabric 应用案例
2016/08/28 Python
Pycharm学习教程(1) 定制外观
2017/05/02 Python
Python 实现Windows开机运行某软件的方法
2018/10/14 Python
Python3中编码与解码之Unicode与bytes的讲解
2019/02/28 Python
python 中如何获取列表的索引
2019/07/02 Python
pandas DataFrame 警告(SettingWithCopyWarning)的解决
2019/07/23 Python
检测浏览器对HTML5和CSS3支持度的方法
2015/06/25 HTML / CSS
韩国著名的在线综合购物网站:Akmall
2016/08/07 全球购物
ECCO爱步美国官网:来自丹麦的鞋履品牌
2016/11/23 全球购物
《鱼游到了纸上》教学反思
2014/02/20 职场文书
2014年父亲节活动方案
2014/03/06 职场文书
副护士长竞聘演讲稿
2014/04/30 职场文书
主题党日活动总结
2014/07/08 职场文书
无刑事犯罪记录证明
2014/09/18 职场文书
2015年关爱留守儿童工作总结
2015/05/22 职场文书
运动会宣传稿50字
2015/07/23 职场文书
2016中秋节晚会开场白
2015/11/26 职场文书
MySQL 逻辑备份与恢复测试的相关总结
2021/05/14 MySQL