python实现飞机大战


Posted in Python onSeptember 11, 2018

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

实现的效果如下:

python实现飞机大战 

主程序代码如下:

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.sprite_creat()
  # 4,设置定时器事件,创建敌机
  pygame.time.set_timer(CREATE_ENEMY_EVENT, 400)
  pygame.time.set_timer(HERO_FIRE_EVENT, 200)
 
 def sprite_creat(self):
  bg1 = BackGround()
  bg2 = BackGround(True)
 
  self.bg_group = pygame.sprite.Group(bg1, bg2)
  self.enemy_group = pygame.sprite.Group()
 
  # 创建英雄的精灵和精灵组
  self.hero = Hero()
  self.hero_group = pygame.sprite.Group(self.hero)
 
 def start_game(self):
  print("游戏开始。。。")
  while True:
   # 1,设置刷新帧率
   self.clock.tick(FRAME_PER_SEC)
   # 2,事件监听
   self.__event_handle()
   # 3,碰撞检测
   self.__check_collide()
   # 4,更新/绘制精灵和精灵组
   self.__updtae_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 == HERO_FIRE_EVENT:
    self.hero.fire()
 
  # 移动英雄
  keys_pressed = pygame.key.get_pressed()
  if keys_pressed[pygame.K_RIGHT]:
   self.hero.speed = 5
  elif keys_pressed[pygame.K_LEFT]:
   self.hero.speed = -5
  else:
   self.hero.speed = 0
 
 def __check_collide(self):
  pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)
  enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)
  if len(enemies) > 0:
   self.hero.kill()
   PlaneGame.__game_over()
 
 def __updtae_sprites(self):
 
  self.bg_group.update()
  self.bg_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()

各个类的代码如下:

import pygame
import random
 
# 屏幕大小
SCREEN_RECT = pygame.Rect(0, 0, 480, 700)
# 刷新帧率
FRAME_PER_SEC = 60
# 创建敌机的定时器常量
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):
  super().__init__("./feiji/background.png")
  if is_alt:
   self.rect.y = -self.rect.height
 
 def update(self):
  self.rect.y += self.speed
  # self.speed += 0.0001
  # 判断背景图片是否移出屏幕窗口
  if self.rect.y > SCREEN_RECT.height:
   self.rect.y = -self.rect.height
 
 
class Enemy(GameSprite):
 
 def __init__(self):
  super().__init__("./feiji/enemy0.png")
  # 随机敌机的速度
  self.speed = random.randint(2, 5)
 
  # 随机敌机的水平位置
  self.rect.x = random.randint(0, (SCREEN_RECT.width-self.rect.width))
 
 def update(self):
  super().update()
  # 判断敌机是否移出屏幕
  if self.rect.y > SCREEN_RECT.height:
   print("飞出屏幕。。。")
   # 将敌机从敌机精灵组中删除
   self.kill()
 
 def __del__(self):
  print("删除敌机")
 
 
class Hero(GameSprite):
 """英雄类"""
 
 def __init__(self):
  super(Hero, self).__init__("./feiji/hero1.png", 0)
  self.rect.centerx = SCREEN_RECT.centerx
  self.rect.bottom = SCREEN_RECT.bottom - 80
  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.x >= (SCREEN_RECT.width - self.rect.width):
   self.rect.x = SCREEN_RECT.width - self.rect.width
 
 def fire(self):
  # 创建子弹精灵
  bullet = Bullet()
 
  # 设置子弹精灵的位置
  bullet.rect.bottom = self.rect.y -5
  bullet.rect.centerx = self.rect.centerx
 
  # 将子弹精灵添加到子弹精灵组中去
  self.bullets.add(bullet)
 
 
class Bullet(GameSprite):
 
 def __init__(self):
  super(Bullet, self).__init__('./feiji/bullet.png', -2)
 
 def update(self):
  super(Bullet, self).update()
  if self.rect.y <= 0:
   self.kill()

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

Python 相关文章推荐
python实现DNS正向查询、反向查询的例子
Apr 25 Python
Python中使用md5sum检查目录中相同文件代码分享
Feb 02 Python
Centos Python2 升级到Python3的简单实现
Jun 21 Python
解决PyCharm import torch包失败的问题
Oct 13 Python
django中ORM模型常用的字段的使用方法
Mar 05 Python
50行Python代码获取高考志愿信息的实现方法
Jul 23 Python
利用Python检测URL状态
Jul 31 Python
np.dot()函数的用法详解
Jan 17 Python
python 追踪except信息方式
Apr 25 Python
python文件路径操作方法总结
Dec 21 Python
Python OpenCV实现图像模板匹配详解
Apr 07 Python
python游戏开发Pygame框架
Apr 22 Python
pygame实现简易飞机大战
Sep 11 #Python
python实现飞机大战微信小游戏
Mar 21 #Python
python实现微信小程序自动回复
Sep 10 #Python
python中map的基本用法示例
Sep 10 #Python
python2 与 pyhton3的输入语句写法小结
Sep 10 #Python
django DRF图片路径问题的解决方法
Sep 10 #Python
详解python中Numpy的属性与创建矩阵
Sep 10 #Python
You might like
PHP IN_ARRAY 函数使用注意事项
2010/07/24 PHP
PHP中“=&gt;
2019/03/01 PHP
PHP如何防止用户重复提交表单
2020/12/09 PHP
php慢查询日志和错误日志使用详解
2021/02/27 PHP
JavaScript Perfection kill 测试及答案
2010/03/23 Javascript
AngularJS快速入门
2015/04/02 Javascript
jQuery中实现prop()函数控制多选框(全选,反选)
2016/08/19 Javascript
js正则表达式注册页面表单验证
2016/10/11 Javascript
Bootstrap实现基于carousel.js框架的轮播图效果
2017/05/02 Javascript
bootstrap表单示例代码分享
2017/05/18 Javascript
jQuery中图片展示插件highslide.js的简单dom
2018/04/22 jQuery
基于vue实现一个禅道主页拖拽效果
2019/05/27 Javascript
vue ajax 拦截原理与实现方法示例
2019/11/29 Javascript
JS面向对象之单选框实现
2020/01/17 Javascript
[03:40]DOTA2英雄梦之声_第01期_炼金术士
2014/06/23 DOTA
[54:30]Liquid vs Newbee 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/16 DOTA
[42:20]Secret vs Liquid 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/17 DOTA
用python实现的可以拷贝或剪切一个文件列表中的所有文件
2009/04/30 Python
Python实现打印螺旋矩阵功能的方法
2017/11/21 Python
python基于ID3思想的决策树
2018/01/03 Python
Random 在 Python 中的使用方法
2018/08/09 Python
python中退出多层循环的方法
2018/11/27 Python
python excel转换csv代码实例
2019/08/26 Python
python实现两个文件夹的同步
2019/08/29 Python
快速解决jupyter启动卡死的问题
2020/04/10 Python
Python-jenkins模块获取jobs的执行状态操作
2020/05/12 Python
CSS3旋转——彩色扇子兼容firefox浏览器
2013/06/04 HTML / CSS
ALDO加拿大官网:加拿大女鞋品牌
2018/12/22 全球购物
swtich是否能作用在byte上,是否能作用在long上,是否能作用在String上?
2013/03/30 面试题
我的大学生活职业生涯规划
2014/01/02 职场文书
个人近期表现材料
2014/02/11 职场文书
班主任班级寄语大全
2014/04/04 职场文书
三行辞职书范文
2015/02/26 职场文书
白银帝国观后感
2015/06/17 职场文书
MySQL复制问题的三个参数分析
2021/04/07 MySQL
Python使用BeautifulSoup4修改网页内容
2022/05/20 Python