​​​​​​​

# coding:utf-8
import pygame, sys, random, time, easygui
from pygame.locals import *
# 初始化pygame环境
pygame.init()# 创建一个长宽分别为480/650窗口
canvas = pygame.display.set_mode((480, 650))
canvas.fill((255, 255, 255))# 设置窗口标题
pygame.display.set_caption("飞机大战")
bg = pygame.image.load("images/bg1.png")
enemy1 = pygame.image.load("images/enemy1.png")
enemy2 = pygame.image.load("images/enemy2.png")
enemy3 = pygame.image.load("images/enemy3.png")
b = pygame.image.load("images/bullet1.png")
h = pygame.image.load("images/hero.png")
#开始游戏图片
startgame=pygame.image.load("images/startGame.png")
#logo图片
logo=pygame.image.load("images/LOGO.png")
#暂停图片
pause = pygame.image.load("images/game_pause_nor.png")# 添加时间间隔的方法
def isActionTime(lastTime, interval):if lastTime == 0:return TruecurrentTime = time.time()return currentTime - lastTime >= interval# 定义Sky类
class Sky():def __init__(self):self.width = 480self.height = 852self.img = bgself.x1 = 0self.y1 = 0self.x2 = 0self.y2 = -self.height# 创建paint方法def paint(self):canvas.blit(self.img, (self.x1, self.y1))canvas.blit(self.img, (self.x2, self.y2))# 创建step方法def step(self):self.y1 = self.y1 + 1self.y2 = self.y2 + 1if self.y1 > self.height:self.y1 = -self.heightif self.y2 > self.height:self.y2 = -self.height# 定义父类FlyingObject
class FlyingObject(object):def __init__(self, x, y, width, height, life, img):self.x = xself.y = yself.width = widthself.height = heightself.life = lifeself.img = img# 敌飞机移动的时间间隔self.lastTime = 0self.interval = 0.01# 添加删除属性self.canDelete = False# 定义paint方法def paint(self):canvas.blit(self.img, (self.x, self.y))# 定义step方法def step(self):# 判断是否到了移动的时间间隔if not isActionTime(self.lastTime, self.interval):returnself.lastTime = time.time()# 控制移动速度self.y = self.y + 2# 定义hit方法判断两个对象之间是否发生碰撞def hit(self, component):c = componentreturn c.x > self.x - c.width and c.x < self.x + self.width and \c.y > self.y - c.height and c.y < self.y + self.height# 定义bang方法处理对象之间碰撞后的处理def bang(self, bangsign):# 敌机和英雄机碰撞之后的处理if bangsign:if hasattr(self, 'score'):GameVar.score += self.scoreif bangsign == 2:self.life -= 1# 设置删除属性为Trueself.canDelete = True# 敌机和子弹碰撞之后的处理else:self.life -= 1if self.life == 0:# 设置删除属性为Trueself.canDelete = Trueif hasattr(self, 'score'):GameVar.score += self.score # 定义outOfBounds方法判断对象是否越界def outOfBounds(self):return self.y > 650# 重构Enemy类
class Enemy(FlyingObject):def __init__(self, x, y, width, height, type, life, score, img):FlyingObject.__init__(self, x, y, width, height, life, img)self.type = typeself.score = score# 重构Hero类
class Hero(FlyingObject):def __init__(self, x, y, width, height, life, img):FlyingObject.__init__(self, x, y, width, height, life, img)self.x = 480 / 2 - self.width / 2self.y = 650 - self.height - 30self.shootLastTime = 0self.shootInterval = 0def shoot(self):if not isActionTime(self.shootLastTime, self.shootInterval):returnself.shootLastTime = time.time()GameVar.bullets.append(Bullet(self.x + self.width / 2 - 5, self.y - 10, 10, 10, 1, b))# 重构Bullet类
class Bullet(FlyingObject):def __init__(self, x, y, width, height, life, img):FlyingObject.__init__(self, x, y, width, height, life, img)def step(self):self.y = self.y - 2# 重写outOfBounds方法判断子弹是否越界def outOfBounds(self):return self.y < -self.height# 创建componentEnter方法
def componentEnter():# 随机生成坐标x = random.randint(0, 480 - 57)x1 = random.randint(0, 480 - 50)x2 = random.randint(0, 480 - 100)# 根据随机整数的值生成不同的敌飞机n = random.randint(0, 9)# 判断是否到了产生敌飞机的时间if not isActionTime(GameVar.lastTime, GameVar.interval):returnGameVar.lastTime = time.time()if n <= 7:GameVar.enemies.append(Enemy(x, 0, 57, 45, 1, 1, 1, enemy1))elif n == 8:GameVar.enemies.append(Enemy(x1, 0, 50, 68, 2, 3, 5, enemy2))elif n == 9: if len(GameVar.enemies) == 0 or GameVar.enemies[0].type != 3: GameVar.enemies.insert(0, Enemy(x2, 0, 100, 153, 3, 10, 20, enemy3))# 创建画组件方法
def componentPaint():# 判断是否到了飞行物重绘的时间if not isActionTime(GameVar.paintLastTime, GameVar.paintInterval):returnGameVar.paintLastTime = time.time()# 调用sky对象的paint方法GameVar.sky.paint()for enemy in GameVar.enemies:enemy.paint()# 画出英雄机GameVar.hero.paint()# 画出子弹对象for bullet in GameVar.bullets:bullet.paint()# 写出分数和生命值fillText('SCORE:' + str(GameVar.score), (0, 0))fillText('LIFE:' + str(GameVar.heroes), (380, 0))# 创建组件移动的方法
def componentStep():# 调用sky对象的step方法GameVar.sky.step()for enemy in GameVar.enemies:enemy.step()# 使子弹移动for bullet in GameVar.bullets:bullet.step()# 创建删除组件的方法
def componentDelete():for enemy in GameVar.enemies:if enemy.canDelete or enemy.outOfBounds():GameVar.enemies.remove(enemy)for bullet in GameVar.bullets:if bullet.canDelete or bullet.outOfBounds():GameVar.bullets.remove(bullet)# 从列表中删除英雄机if GameVar.hero.canDelete == True:GameVar.heroes -= 1if GameVar.heroes == 0:easygui.msgbox('游戏结束')else:GameVar.hero = Hero(0, 0, 60, 75, 1, h)# 定义GameVar类
class GameVar():sky = Sky()enemies = []# 产生敌飞机的时间间隔lastTime = 0interval = 1# 重绘飞行物的时间间隔paintLastTime = 0paintInterval = 0.01# 创建英雄机对象hero = Hero(0, 0, 60, 75, 1, h)# 创建列表存储子弹对象bullets = []# 添加分数和生命值score = 0heroes = 3#创建字典存储游戏状态STATES = {'START':1,'RUNNING':2,'PAUSE':3,'GAME_OVER':4}state = STATES['START']
print(GameVar.state)# 定义fillText方法
def fillText(text, position):my_font = pygame.font.SysFont("微软雅黑", 40)newText = my_font.render(text, True, (255, 255, 255))canvas.blit(newText, position)# 创建游戏退出事件处理方法
def handleEvent():for event in pygame.event.get():if event.type == pygame.QUIT or event.type == KEYDOWN and event.key == K_ESCAPE:pygame.quit()sys.exit()  if event.type==MOUSEBUTTONDOWN and event.button==1:if GameVar.state==GameVar.STATES['START']:GameVar.state=GameVar.STATES['RUNNING']# 英雄机跟随鼠标移动if event.type == MOUSEMOTION:GameVar.hero.x = event.pos[0] - GameVar.hero.width / 2GameVar.hero.y = event.pos[1] - GameVar.hero.height / 2 # 创建方法判断鼠标移出画布
def isMouseOut(x, y):if x >= 479 or x <= 0 or y >= 649 or y <= 0:return Trueelse:return False
# 创建方法判断鼠标移入画布
def isMouseOver(x, y):if x > 1 and x < 479 and y > 1 and y < 649:return Trueelse:return False# 创建checkHit方法
def checkHit():# 判断英雄机是否与每一架敌飞机发生碰撞for enemy in GameVar.enemies:if GameVar.hero.hit(enemy):# 敌机和英雄机调用bang方法enemy.bang(1)GameVar.hero.bang(2)# 判断每一架敌飞机是否与每一颗子弹发生碰撞for bullet in GameVar.bullets:if enemy.hit(bullet):# 敌机和子弹调用bang方法enemy.bang(0)bullet.bang(0)#创建controlState方法控制游戏状态
def controlState():#游戏开始状态if GameVar.state == GameVar.STATES['START']:GameVar.sky.paint()GameVar.sky.step()canvas.blit(logo,(-40,200))canvas.blit(startgame,(150,400))#游戏运行状态elif GameVar.state == GameVar.STATES['RUNNING']:componentEnter()componentPaint()componentStep()checkHit()GameVar.hero.shoot()componentDelete()#游戏暂停状态elif GameVar.state == GameVar.STATES['PAUSE']:componentPaint()GameVar.sky.step()canvas.blit(pause,(0,0))#游戏结束状态elif GameVar.state == GameVar.STATES['GAME_OVER']:componentPaint()GameVar.sky.step()renderText('gameOver',(180,320))while True:#调用控制游戏状态的方法controlState()# 刷新屏幕pygame.display.update()# 调用handleEvent方法handleEvent()# 延迟处理pygame.time.delay(15)

Python飞机大战+图片相关推荐

  1. python飞机大战设计思路_python飞机大战pygame游戏背景设计详解

    本文实例讲述了python飞机大战pygame游戏背景设计.分享给大家供大家参考,具体如下: 目标 背景交替滚动的思路确定 显示游戏背景 01. 背景交替滚动的思路确定 运行 备课代码,观察 背景图像 ...

  2. python飞机大战联网版_Python 飞机大战搞怪版本

    python 飞机大战搞怪版本 (飞机为迷你亚索,外星人为迷你小诺手,由于时间关系和图片素材较难寻找,仅仅做了简易版,没有贴上背景图片.由于篇幅原因,对于函数讲解较为简略,可以自行搜索相应函数的用法) ...

  3. python飞机大战功能模块图_基于Python的飞机大战游戏设计

    第 2 3 卷 第 1 期 2019年 3 月 扬 州 职 业 大 学 学 报 Journal of Yangzhou Polytechnic College Vol .23 No . 1 Mar . ...

  4. python飞机大战没有运行界面_python3实现飞机大战

    本文实例为大家分享了python3实现飞机大战的具体代码,供大家参考,具体内容如下 以下是亲测Python飞机大战全部代码,在保证有pygame环境支持并且有Python3解释器的话完全没问题! 如果 ...

  5. Python 飞机大战游戏中 获取被击中飞机的坐标位置信息

    Python 飞机大战游戏中 获取被击中飞机的坐标位置信息 在参考现有的飞机大战游戏代码,写第一个python游戏,子弹击中飞机后,飞机消失,想着如果能有爆照效果就好了. 于是新建了一个爆炸效果的sp ...

  6. python飞机大战计分代码_Python 飞机大战代码练习

    Python 飞机大战代码练习 最近在自学Python,参照代码自己写了一遍飞机大战游戏的代码.主要应用的模块为pygame.整个代码如下所示,主要分为主模块和各种精灵类定义模块,记录一下自己的学习历 ...

  7. python飞机大战创建多个敌机_python飞机大战敌机爆炸怎么编写?

    问题描述 python开发飞机大战时出现以下错误: Traceback (most recent call last): File "D:/python/飞机大战.py", lin ...

  8. Python“飞机大战”上下左右移动空格发射子弹

    下载点此去 最后面有运行视频 一.项目背景 作为一名学习计算机的学生,在以往,我认为学习计算机要么就是无所不能的黑客,要么就是能制作出各种软件程序的大神.我选择pygame板块,制作一款能随意更改游戏 ...

  9. Python飞机大战(完整版)

    简介:一共分为2个py文件,分别是主类.和精灵类 飞机大战图片地址:链接: https://pan.baidu.com/s/18T6n9JFIDxBqYX9CnHi7ZQ  密码: tqbr 注释:项 ...

  10. python飞机大战任务报告_Python飞机大战实战项目案例

    都说实践是检验知识掌握程度的最好测试.随着Python学习者的增长,越来越多的零基础入门课程让人眼花缭乱.虽然说基础理论的学习十分重要,但是如果仅仅只学习理论知识,也是远远不够的.飞机大战的项目实战可 ...

最新文章

  1. C++ set 的使用
  2. 中国信通院发布《区块链基础设施研究报告(2021年)》
  3. 同一个事务里面对同一条数据做2次修改_要我说,多线程事务它必须就是个伪命题!
  4. #!/usr/bin/env python与#!/usr/bin/python
  5. 如何解决回归任务数据不均衡的问题?
  6. js数组获取index_通过事例重温一下常见的 JS 中 15 种数组操作(备忘清单)
  7. jquery href属性和click事件冲突
  8. 请解释一下 str db 0dh,0ah,‘$‘ 这个汇编语句什么意思?
  9. 微信小程序的总结(我学到了什么?我有了哪些成就?)
  10. 报表工具的演示录像发布
  11. u-boot-2010.09-for-tiny6410-v1.0支持sd卡SDHC卡启动
  12. 学习github的网站
  13. iSCSI Initiator命名规范
  14. 指数和个股的对数收益率正态性检验
  15. 2021-2025年中国物理疗法电子病历和计费软件行业市场供需与战略研究报告
  16. Web课程设计之学生成绩管理系统
  17. MathType Translation Error
  18. unity shader学习---光照模型(二)
  19. 学习编程需要什么基础?从基础到高级?
  20. jquery.photoClip.js图片上传插件带拖动裁剪

热门文章

  1. 1660用哪个驱动稳定_安装驱动软件我认为哪个最好?
  2. 指导老师对计算机论文的评语,指导老师对论文的评语
  3. SIR模型的应用(2) - Influence maximization in social networks based on TOPSIS(3)
  4. Lighthouse
  5. centos7安装中文字体
  6. Office 2019 正式版 下載
  7. flutter加载本地图片
  8. html主题网站设计代码示例,网页设计参考:很不错的15个HTML网页表单设计实例
  9. chap1统计学习及监督学习
  10. tomcat 环境迁移至weblogic 下载文件失败