目录

1.搭建界面和键盘检测

2.添加背景音乐

3.运行优化

4.控制玩具飞机-面向过程

5.控制玩具飞机-面向对象

6.玩家飞机发射子弹

7.显示敌机

8.敌机发射子弹

9.抽象基类


飞机大战-要实现的效果

控制玩具飞机-面向过程

控制玩具飞机-面向对象

玩家飞机发射子弹

显示敌机

敌机发射子弹

控制玩具飞机

显示敌机

敌机发送子弹

1.搭建界面和键盘检测

街机游戏相信很多人玩过,比如图中的恐龙快打、飞机游戏,但是之前我们一直玩别人做的游戏,不知道大家有没有想过,这种游戏是怎么做出来的,使用什么样语言做出来的,Python能做游戏开发吗?答案是肯定的,接下来我就带领大家来一起使用python开发一个飞机大战的游戏

import pygame
from pygame.locals import *
'''
1.搭建界面,主要完成窗口和背景图的显示
'''
def main():#1.创建一个窗口,用来显示内容screen=pygame.display.set_mode((350,500),0,32)#2.加载一张和窗口大小一样的图片,用来充当背景background=pygame.image.load("./feiji/background.png")#3.把背景图片放到窗口中显示#设置一个titlepygame.display.set_caption('阶段总结-飞机小游戏')while True:#设定需要显示的背景图screen.blit(background,(0,0))#更新需要显示的内容pygame.display.update()
if __name__=='__main__':main()

运行结果

键盘检测

            #获取事件,比如按键等for event in pygame.event.get():#判断是否点击了退出按钮if event.type==QUIT:print('exit')exit()#判断是否按下了键elif event.type == KEYDOWN:# 检测按键是否是a或者left,左键if event.key == K_a or event.key == K_LEFT:print('left')# 检测按键是否是d或者right 右键elif event.key == K_d or event.key == K_RIGHT:print('right')# 检测按键是否是空格键elif event.key == K_SPACE:print('space')

输出结果

pygame介绍

Pygame是一个利用SDL库的写的游戏库,SDL呢,全名Simple DirectMedia Layer,是一位叫做Sam Lantinga的大牛写的

SDL是用C写的,不过它也可以使用C++进行开发,当然还有很多其它的语言,Pygame就是Python中使用它的一个库

pygame安装

安装命令:pip install pygame

pygame 使用

Pygame有很多的模块,下面是一张一览表:

具体教程可参考官网:https://www.pygame.org/docs/

2.添加背景音乐

import pygame
from pygame.locals import *
'''
1.搭建界面,主要完成窗口和背景图的显示
'''
def main():#1.创建一个窗口,用来显示内容screen=pygame.display.set_mode((350,500),0,32)#2.加载一张和窗口大小一样的图片,用来充当背景background=pygame.image.load("./feiji/background.png")#3.把背景图片放到窗口中显示#4.设置一个titlepygame.display.set_caption('阶段总结-飞机小游戏')#5.添加背景音乐pygame.mixer.init()pygame.mixer.music.load("./feiji/background.mp3")pygame.mixer.music.set_volume(0.2)pygame.mixer.music.play(-1) #循环次数,-1表示无限循环#6.载入玩家的飞机图片hero=pygame.image.load("./feiji/hero.png")#6.1初始化玩家图标的位置x,y=0,0while True:#设定需要显示的背景图/显示玩家图片screen.blit(background,(0,0))#显示玩家飞机的图片screen.blit(hero, (x, y))#更新需要显示的内容pygame.display.update()#获取事件,比如按键等for event in pygame.event.get():#判断是否点击了退出按钮if event.type==QUIT:print('exit')exit()#判断是否按下了键elif event.type == KEYDOWN:# 检测按键是否是a或者left,左键if event.key == K_a or event.key == K_LEFT:print('left')if x>0:x-=5# 检测按键是否是d或者right 右键elif event.key == K_d or event.key == K_RIGHT:print('right')if x<310:x+=5# 检测按键是否是空格键elif event.key == K_SPACE:print('space')if __name__=='__main__':main()

3.运行优化,玩家飞机--面向对象

import pygame
from pygame.locals import *
'''
1.实现飞机的显示,并且可以控制飞机的移动【面向对象】
'''
class HeroPlane(object):def __init__(self,screen):#设定飞机的默认位置self.x=150self.y=450#设置要显示内容的窗口self.screen=screenself.imageName="./feiji/hero.png"self.image=pygame.image.load(self.imageName)passdef moveLeft(self): #左移动if self.x>0:self.x-=10passdef moveRight(self):  #右移动if self.x<<310:self.x+=10passdef display(self):  #飞机在主窗口的显示self.screen.blit(self.image,(self.x,self.y))pass
'''
2.键盘控制
'''
def key_control(HeroObj):for event in pygame.event.get():# 判断是否点击了退出按钮if event.type == QUIT:print('exit')exit()# 判断是否按下了键elif event.type == KEYDOWN:# 检测按键是否是a或者left,左键if event.key == K_a or event.key == K_LEFT:print('left')HeroObj.moveLeft()  #调用函数实现左移动elif event.key == K_d or event.key == K_RIGHT:print('right')HeroObj.moveRight()  #调用函数实现左移动# 检测按键是否是空格键elif event.key == K_SPACE:print('space')
'''
3.搭建界面,主要完成窗口和背景图的显示
'''
def main():#1.创建一个窗口,用来显示内容screen=pygame.display.set_mode((350,500),0,32)#2.加载一张和窗口大小一样的图片,用来充当背景background=pygame.image.load("./feiji/background.png")#3.把背景图片放到窗口中显示#4.设置一个titlepygame.display.set_caption('阶段总结-飞机小游戏')#5.添加背景音乐pygame.mixer.init()pygame.mixer.music.load("./feiji/background.mp3")pygame.mixer.music.set_volume(0.2)pygame.mixer.music.play(-1) #循环次数,-1表示无限循环#创建一个飞机对象hero=HeroPlane(screen)while True:#设定需要显示的背景图/显示玩家图片screen.blit(background,(0,0))#显示玩家飞机的图片hero.display()key_control(hero)#更新需要显示的内容pygame.display.update()if __name__=='__main__':main()

4.效果完成

import timeimport pygame
import random
from pygame.locals import *
'''
1.实现飞机的显示,并且可以控制飞机的移动【面向对象】
'''
class HeroPlane(object):def __init__(self,screen):#设定飞机的默认位置self.x=150self.y=450#设置要显示内容的窗口self.screen=screenself.imageName="./feiji/hero.png"self.image=pygame.image.load(self.imageName)#用于存放子弹的列表self.bulletList=[]passdef moveLeft(self): #左移动if self.x>0:self.x-=10passdef moveRight(self):  #右移动if self.x<<310:self.x+=10passdef display(self):  #飞机在主窗口的显示self.screen.blit(self.image,(self.x,self.y))#完善子弹的展示逻辑needDelItemList=[]for item in self.bulletList:if item.judge():needDelItemList.append(item)pass#重新遍历for i in needDelItemList:self.bulletList.remove(i)for bullet in self.bulletList:bullet.display()  #显示子弹的位置bullet.move()  #让子弹移动def sheBullet(self):#创建一个新的子弹对象newbullet=Bullet(self.x,self.y,self.screen)self.bulletList.append(newbullet)
'''
2.创建敌人飞机
'''
class EnemyPlane():def __init__(self,screen):#默认设定一个子弹的方向self.direction='right'# 设定飞机的默认位置self.x = 0self.y = 0# 设置要显示内容的窗口self.screen = screenself.imageName = "./feiji/enemy0.png"self.image = pygame.image.load(self.imageName)self.bulletList=[]passdef display(self):self.screen.blit(self.image,(self.x,self.y))# 完善子弹的展示逻辑needDelItemList = []for item in self.bulletList:if item.judge():needDelItemList.append(item)pass# 重新遍历for i in needDelItemList:self.bulletList.remove(i)for bullet in self.bulletList:bullet.display()  # 显示子弹的位置bullet.move()  # 让子弹移动def sheBullet(self):num=random.randint(1,100)if num==3:newBullet=EnemyBullet(self.x,self.y,self.screen)self.bulletList.append(newBullet)passdef move(self):if self.direction=='right':self.x+=0.1elif self.direction=='left':self.x-=0.1if self.x>350-20:self.direction='left'elif self.x<0:self.direction='right''''
3.创建玩家子弹类
'''
class Bullet(object):def __init__(self,x,y,screen):self.x=x+13self.y=y-20self.screen=screenself.image=pygame.image.load("./feiji/bullet.png")passdef display(self):self.screen.blit(self.image,(self.x,self.y))passdef move(self):self.y-=3pass#判断子弹是否越界def judge(self):if self.y<0:return Trueelse:return Falsepass
'''
4.创建敌人飞机子弹
'''
class EnemyBullet(object):def __init__(self,x,y,screen):self.x=xself.y=y+10self.screen=screenself.image=pygame.image.load("./feiji/bullet1.png")passdef display(self):self.screen.blit(self.image,(self.x,self.y))passdef move(self):self.y+=1pass#判断子弹是否越界def judge(self):if self.y>500:return Trueelse:return Falsepass
'''
4..键盘控制
'''
def key_control(HeroObj):for event in pygame.event.get():# 判断是否点击了退出按钮if event.type == QUIT:print('exit')exit()# 判断是否按下了键elif event.type == KEYDOWN:# 检测按键是否是a或者left,左键if event.key == K_a or event.key == K_LEFT:print('left')HeroObj.moveLeft()  #调用函数实现左移动elif event.key == K_d or event.key == K_RIGHT:print('right')HeroObj.moveRight()  #调用函数实现左移动# 检测按键是否是空格键elif event.key == K_SPACE:print('按下空格键,发射子弹')HeroObj.sheBullet()
'''
5.搭建界面,主要完成窗口和背景图的显示
'''
def main():#1.创建一个窗口,用来显示内容screen=pygame.display.set_mode((350,500),0,32)#2.加载一张和窗口大小一样的图片,用来充当背景background=pygame.image.load("./feiji/background.png")#3.把背景图片放到窗口中显示#4.设置一个titlepygame.display.set_caption('阶段总结-飞机小游戏')#5.添加背景音乐pygame.mixer.init()pygame.mixer.music.load("./feiji/background.mp3")pygame.mixer.music.set_volume(0.2)pygame.mixer.music.play(-1) #循环次数,-1表示无限循环#创建一个玩家飞机对象hero=HeroPlane(screen)#创建一个敌人飞机对象enemyplane=EnemyPlane(screen)while True:#设定需要显示的背景图/显示玩家图片screen.blit(background,(0,0))#显示玩家飞机的图片hero.display()enemyplane.display()enemyplane.move()enemyplane.sheBullet()key_control(hero)#更新需要显示的内容pygame.display.update()
if __name__=='__main__':main()

5.结构优化

import time
import pygame
import random
from pygame.locals import *
class BasePlane():def __init__(self,screen,imageName):self.screen=screenself.image=pygame.image.load(imageName)self.bulletList=[]def display(self):self.screen.blit(self.image, (self.x, self.y))# 完善子弹的展示逻辑needDelItemList = []for item in self.bulletList:if item.judge():needDelItemList.append(item)pass# 重新遍历for i in needDelItemList:self.bulletList.remove(i)for bullet in self.bulletList:bullet.display()  # 显示子弹的位置bullet.move()  # 让子弹移动pass
'''
1.实现飞机的显示,并且可以控制飞机的移动【面向对象】
'''
class HeroPlane(BasePlane):def __init__(self,screen):#设定飞机的默认位置self.x=150self.y=450#设置要显示内容的窗口super().__init__(screen,"./feiji/hero.png") #调用父类的构造方法def moveLeft(self): #左移动if self.x>0:self.x-=10passdef moveRight(self):  #右移动if self.x<310:self.x+=10passdef sheBullet(self):#创建一个新的子弹对象newbullet=CommonBullet(self.x,self.y,self.screen,'hero')self.bulletList.append(newbullet)
'''
2.创建敌人飞机
'''
class EnemyPlane(BasePlane):def __init__(self,screen):super().__init__(screen,"./feiji/enemy0.png")#默认设定一个子弹的方向self.direction='right'# 设定飞机的默认位置self.x = 0self.y = 0passdef sheBullet(self):num=random.randint(1,100)if num==3:newBullet=CommonBullet(self.x,self.y,self.screen,'enemy')self.bulletList.append(newBullet)passdef move(self):if self.direction=='right':self.x+=0.1elif self.direction=='left':self.x-=0.1if self.x>350-20:self.direction='left'elif self.x<0:self.direction='right'
class CommonBullet():def __init__(self,x,y,screen,bulletType):self.type=bulletTypeself.screen=screenif self.type=='hero':self.x = x + 13self.y = y - 20self.imagePath="./feiji/bullet.png"elif self.type=='enemy':self.x = xself.y = y + 10self.imagePath="./feiji/bullet1.png"self.image=pygame.image.load(self.imagePath)def move(self):if self.type=='hero':self.y-=1elif self.type=='enemy':self.y+=1def display(self):self.screen.blit(self.image,(self.x,self.y))passdef judge(self):if self.y>500 or self.y<0:return Trueelse:return False
'''
5..键盘控制
'''
def key_control(HeroObj):for event in pygame.event.get():# 判断是否点击了退出按钮if event.type == QUIT:print('exit')exit()# 判断是否按下了键elif event.type == KEYDOWN:# 检测按键是否是a或者left,左键if event.key == K_a or event.key == K_LEFT:print('left')HeroObj.moveLeft()  #调用函数实现左移动elif event.key == K_d or event.key == K_RIGHT:print('right')HeroObj.moveRight()  #调用函数实现左移动# 检测按键是否是空格键elif event.key == K_SPACE:print('按下空格键,发射子弹')HeroObj.sheBullet()
'''
5.搭建界面,主要完成窗口和背景图的显示
'''
def main():#1.创建一个窗口,用来显示内容screen=pygame.display.set_mode((350,500),0,32)#2.加载一张和窗口大小一样的图片,用来充当背景background=pygame.image.load("./feiji/background.png")#3.把背景图片放到窗口中显示#4.设置一个titlepygame.display.set_caption('阶段总结-飞机小游戏')#5.添加背景音乐pygame.mixer.init()pygame.mixer.music.load("./feiji/background.mp3")pygame.mixer.music.set_volume(0.2)pygame.mixer.music.play(-1) #循环次数,-1表示无限循环#创建一个玩家飞机对象hero=HeroPlane(screen)#创建一个敌人飞机对象enemyplane=EnemyPlane(screen)while True:#设定需要显示的背景图/显示玩家图片screen.blit(background,(0,0))#显示玩家飞机的图片hero.display()enemyplane.display()enemyplane.move()enemyplane.sheBullet()key_control(hero)#更新需要显示的内容pygame.display.update()
if __name__=='__main__':main()

Python阶段总结 飞机案例—Python Day10相关推荐

  1. python自动化办公实战案例,python 自动化办公 案例

    推荐几个适合新手练手的Python项目 谷歌人工智能写作项目:小发猫 python编程:输入一个自然数n,如果n为奇数,输出表达式1+1/3+-+1/n的值 def summ(n): if n%2: ...

  2. python io密集型应用案例-Python中单线程、多线程和多进程的效率对比实验实例

    python的多进程性能要明显优于多线程,因为cpython的GIL对性能做了约束. Python是运行在解释器中的语言,查找资料知道,python中有一个全局锁(GIL),在使用多进程(Thread ...

  3. 基于python的情感分析案例-python snownlp情感分析简易demo(分享)

    SnowNLP是国人开发的python类库,可以方便的处理中文文本内容,是受到了TextBlob的启发而写的,由于现在大部分的自然语言处理库基本都是针对英文的,于是写了一个方便处理中文的类库,并且和T ...

  4. python数据分析5个案例-Python数据分析-案例分析

    两个学习道具: 1)这个网页可以调用全球最大的搜索引擎(长按此处可以复制): 事先准备: 在notebook中想要导入Excel文件,要先安装一个读取Excel文件的包:xlrd 安装步骤: 1> ...

  5. 基于python的情感分析案例-python自然语言处理情感分析案例

    产品价值 自然语言处理是为各类企业及开发者提供的用于文本分析及挖掘的核心工具,已经广泛应用在电商.文化娱乐.金融.物流等行业客户的多项业务中.自然语言处理API可帮助用户搭建内容搜索.内容推荐.舆情识 ...

  6. 飞机大战python代码_飞机大战Python程序

    import pygame from plane_sprites import * class PlaneGame( object ): # 初始化 开始游戏类方法 启动游戏 def __init__ ...

  7. Python——飞机大战(day10)

    目录 一.面向过程实现 二.面向对象 plane pro需求的描述: 存在四个对象: 我方飞机.敌方飞机.我方子弹.敌方子弹 功能: 背景音乐的添加 我方飞机可以移动[根据按键来控制的] 敌方飞机也可 ...

  8. python与人工智能编程-总算明白python人工智能编程入门案例

    Python是非常简洁的一种脚本语言,写同样的程序,代码量仅为java的三分一,除了性能没有Java强之外,它的优点还是相当多的.以下是小编为你整理的python人工智能编程入门案例 下载Active ...

  9. python项目开发案例-Python项目开发案例集锦 PDF 全彩超清版

    给大家带来的一篇关于Python案例相关的电子书资源,介绍了关于Python.项目开发.Python案例方面的内容,本书是由吉林大学出版社出版,格式为PDF,资源大小99.1 MB,明日科技编写,目前 ...

最新文章

  1. 基于SignalR的消息推送与二维码描登录实现
  2. Eclipse设置条件断点
  3. LeetCode 289. 生命游戏
  4. JavaSE的输入流、输出流
  5. python是什么专业学的-什么样的人适合学Python,应该怎么学?
  6. 每日算法系列【LeetCode 289】生命游戏
  7. PX4模块设计之八:Ubuntu 20.04搭建FlightGear模拟器
  8. FIFO设计中的注意问题与技巧
  9. 《深度学习之美》第2章
  10. 读书笔记|| 类继承
  11. 惠普g7服务器硬盘阵列,HP DL388 G7 服务器重新做RAID
  12. 打计算机游戏用英语怎么说,打游戏用英语怎么说
  13. fairyGUI的学习记录2
  14. Linux系统中systemctl命令的使用
  15. 区块链概念正宗龙头股
  16. DBeaver连接mysql数据库执行.sql脚本,Windows
  17. Http状态码大全(100、200、300、404、500等)
  18. 伦敦大学计算机图形学博士,GAMES Webinar 2018 -73期(Siggraph Asia 2018论文报告)| 王杨抟风(伦敦大学学院),李昌健(香港大学)...
  19. java检查word文档内容缺失_恢复Word文档内容需要了解的知识
  20. 【蓝桥备赛】七星填空

热门文章

  1. Python爬取豆瓣音乐存储MongoDB数据库(Python爬虫实战1)
  2. 护牙剂大揭秘--牙医的“谎言”有哪些?
  3. i.MX6ULL驱动开发 | 33 - NXP原厂网络设备驱动浅读(LAN8720 PHY)
  4. n+=1和n=n+1的区别
  5. 携程、美团“抢食”精致周边游
  6. C#使用aforge框架打开摄像头(续)
  7. OSChina 周日乱弹 —— 如何证明“女生=恶魔”?
  8. 汉中管道在管掌柜上架PPR管、PVC排水管、HDPE管、镀锌钢管
  9. Flutter InkWell 和 Ink --按钮“水波纹”效果
  10. basename函数 linux,Linux C中的basename函数用法示例