python3实现飞机大战


Posted in Python onNovember 29, 2020

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

以下是亲测Python飞机大战全部代码,在保证有pygame环境支持并且有Python3解释器的话完全没问题!

如果大家喜欢的话麻烦点个赞!

运行效果如下图:

python3实现飞机大战

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 导入需要使用的模块
import pygame
from pygame.locals import *
from sys import exit 
import random

# 设置屏幕大小的变量
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 800
import codecs
# 子弹类
class Bullet(pygame.sprite.Sprite):
 def __init__(self,bullet_img,init_pos):
  # 实现父类的初始化方法
  pygame.sprite.Sprite.__init__(self)
  self.image = bullet_img
  self.rect = self.image.get_rect()
  self.rect.midbottom = init_pos
  self.speed = 10
 def move(self):
  self.rect.top -= self.speed  

# 玩家飞机类
class Player(pygame.sprite.Sprite):
 def __init__(self,plane_img,player_rect,init_pos):
  pygame.sprite.Sprite.__init__(self)
  self.image=[]
  for i in range(len(player_rect)):
   self.image.append(plane_img.subsurface(player_rect[i]).convert_alpha()) 
  self.rect = player_rect[0]
  self.rect.topleft = init_pos
  self.speed = 8
  self.bullets = pygame.sprite.Group() #玩家飞机发射子弹的集合
  self.img_index = 0
  self.is_hit = False 

 # 发射子弹
 def shoot(self,bullet_img):
  bullet = Bullet(bullet_img,self.rect.midtop)
  self.bullets.add(bullet)    # 将子弹放入玩家飞机的子弹集合
 
 # 向上移动
 def moveUp(self):
  if self.rect.top <= 0:
   self.rect.top = 0
  else:
   self.rect.top -= self.speed 
 # 向下移动
 def moveDown(self):
  if self.rect.top >= SCREEN_HEIGHT - self.rect.height:
   self.rect.top = SCREEN_HEIGHT - self.rect.height
  else:
   self.rect.top += self.speed
 # 向左移动
 def moveLeft(self):
  if self.rect.left <= 0:
   self.rect.left = 0
  else:
   self.rect.left -= self.speed
 # 向右移动
 def moveRight(self):
  if self.rect.left >= SCREEN_WIDTH - self.rect.width:
   self.rect.left = SCREEN_WIDTH - self.rect.width
  else:
   self.rect.left += self.speed

# 敌机类
class Enemy(pygame.sprite.Sprite):
 # 飞机的图片 敌机坠毁的图片 敌机的位置
 def __init__(self,enemy_img,enemy_down_imgs,init_pos):
  pygame.sprite.Sprite.__init__(self)
  self.image = enemy_img
  self.rect = self.image.get_rect()
  self.rect.topleft = init_pos
  self.down_imgs = enemy_down_imgs
  self.speed = 2 
  self.down_index = 0
 # 移动
 def move(self):
  self.rect.top += self.speed 

# 对文件的操作
# 写入文本
# 要写入的内容,写入方式,写入文件所在的位置
def write_txt(contert, strim, path):
 f = codecs.open(path,strim, 'utf8')
 f.write(str(contert))
 f.close()

# 读取文本
def read_txt(path):
 with open(path,'r',encoding='utf8') as f:
  lines = f.readlines()
 return lines 




# 初始化pygame
pygame.init()
# 设置游戏界面的大小,背景图片,标题
# 界面startGame(
screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
# 标题
pygame.display.set_caption('飞机大战')
# 图标
ic_launcher = pygame.image.load('resources/image/ic_launcher.png').convert_alpha()
pygame.display.set_icon(ic_launcher)
# 背景图
background = pygame.image.load('resources/image/background.png').convert()
# 游戏结束
game_over = pygame.image.load('resources/image/gameover.png')
# 飞机及子弹的图片
plane_img = pygame.image.load('resources/image/shoot.png')

def startGame():
 # 1.设置玩家飞机不同状态的图片列表,多张图片展示为动画效果
 player_rect = []
 # 玩家飞机的图片
 player_rect.append(pygame.Rect(0,99,102,126))
 player_rect.append(pygame.Rect(165,360,102,126))
 # 玩家飞机爆炸的图片
 player_rect.append(pygame.Rect(165,234,102,126))
 player_rect.append(pygame.Rect(330,634,102,126))
 player_rect.append(pygame.Rect(330,498,102,126))
 player_rect.append(pygame.Rect(432,624,102,126))
 player_pos = [200,600]
 # 生成玩家飞机类
 player = Player(plane_img,player_rect,player_pos)
 # 加入子弹的图片
 bullet_rect = pygame.Rect(69,77,10,21)
 bullet_img = plane_img.subsurface(bullet_rect)

 # 加入敌机图片
 enemy1_rect = pygame.Rect(534,612,57,43) #没有爆炸前的图片
 enemy1_img = plane_img.subsurface(enemy1_rect)
 enemy1_down_imgs = [] #飞机销毁后的图片
 enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(267,347,57,43)))
 enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(873,679,57,43)))
 enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(267,296,57,43)))
 enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(930,697,57,43)))
 # 存储敌机的集合
 enmies1 = pygame.sprite.Group()
 # 存储被击毁的敌机的集合
 enemies_down = pygame.sprite.Group()


 # 初始子弹射击频率
 shoot_frequency = 0
 # 初始化敌机生成频率
 enemy_frequency = 0
 # 玩家飞机被击中后的效果处理
 player_down_index = 16

 # 设置游戏的帧数
 clock = pygame.time.Clock()
 # 初始化成绩
 score = 0
 # 判断循环结束的参数
 running = True
 while running:
  for event in pygame.event.get():
   if event.type == pygame.QUIT:
    exit()
  screen.fill(0)           
  screen.blit(background,(0,0))
  clock.tick(60)

  # 生成子弹 判断玩家有没有被击中
  if not player.is_hit:
   if shoot_frequency % 15 == 0:
    player.shoot(bullet_img)
   shoot_frequency += 1
   if shoot_frequency >= 15:
    shoot_frequency = 0
  for bullet in player.bullets:
   bullet.move()
   if bullet.rect.bottom<0:
    player.bullets.remove(bullet)
  
  # 显示子弹
  player.bullets.draw(screen)

  # 生成敌机,..需要控制频率
  if enemy_frequency % 50 == 0:
   #生成随机的位置
   enemy1_pos = [random.randint(0,SCREEN_WIDTH-enemy1_rect.width),0]
   # 初始化敌机
   enemy1 = Enemy(enemy1_img,enemy1_down_imgs,enemy1_pos)
   # 存储到集合中
   enmies1.add(enemy1) 
  enemy_frequency += 1
  # 敌机生成到 100 则重新循环
  if enemy_frequency >= 100:
   enemy_frequency = 0
  # 敌机的移动
  for enemy in enmies1:
   enemy.move()
   # 敌机与玩家碰撞效果处理
   if pygame.sprite.collide_circle(enemy,player): # pygame判定是否相撞的方法
    enemies_down.add(enemy)  # 将敌机加入到坠毁的集合中
    enmies1.remove(enemy)  # 从敌机集合中移除 
    player.is_hit = True 
    break 
   # 移动出屏幕的敌机
   if enemy.rect.top < 0:
    enmies1.remove(enemy)
  # 与子弹碰撞
  enemies1_down = pygame.sprite.groupcollide(enmies1,player.bullets,1,1)
  for enemy_down in enemies1_down:
   enemies_down.add(enemy_down)
  

  # 绘制玩家飞机
  if not player.is_hit:
   screen.blit(player.image[player.img_index],player.rect)
   # 实现飞机动效
   player.img_index = shoot_frequency // 8
  else:
   # 玩家飞机被击毁后的动画效果
   player.img_index = player_down_index // 8 
   screen.blit(player.image[player.img_index],player.rect)
   player_down_index += 1
   if player_down_index > 47:
    running = False
  # 敌机被击中的效果
  for enemy_down in enemies_down:
   if enemy_down.down_index == 0:
    pass
   if enemy_down.down_index > 7:
    enemies_down.remove(enemy_down)
    score += 100
    continue
   # 绘制碰撞动画
   screen.blit(enemy_down.down_imgs[enemy_down.down_index // 2],enemy_down.rect)
   enemy_down.down_index += 1
  
  # 显示敌机
  enmies1.draw(screen)
  # 绘制当前得分
  score_font = pygame.font.Font(None,36)
  score_text = score_font.render(str(score),True,(128,128,128))
  text_rect = score_text.get_rect()
  text_rect.topleft = [10,10]
  screen.blit(score_text,text_rect)
  # 获取键盘的输入
  key_pressed = pygame.key.get_pressed()
  if key_pressed[K_UP] or key_pressed[K_w]:
   player.moveUp()
  if key_pressed[K_DOWN] or key_pressed[K_s]:
   player.moveDown()
  if key_pressed[K_LEFT] or key_pressed[K_a]:
   player.moveLeft()
  if key_pressed[K_RIGHT] or key_pressed[K_d]:
   player.moveRight()

  pygame.display.update()
 # 绘制游戏结束画面
 screen.blit(game_over,(0,0))
 # 绘制Game Over显示最终分数
 font = pygame.font.Font(None,48)
 text = font.render("Score:"+str(score),True,(255,0,0))
 text_rect = text.get_rect()
 text_rect.centerx = screen.get_rect().centerx # x轴位置
 text_rect.centery = screen.get_rect().centery + 24 # y轴位置
 screen.blit(text,text_rect)
 # 使用字体
 xtfont = pygame.font.SysFont("jamrul",30)
 # 绘制重新开始按钮
 textstart = xtfont.render('Start',True,(255,0,0))
 text_rect = textstart.get_rect()
 text_rect.centerx = screen.get_rect().centerx # x轴位置
 text_rect.centery = screen.get_rect().centery + 120 # y轴位置
 screen.blit(textstart,text_rect)
 # 排行榜按钮
 textstart = xtfont.render('Ranking',True,(255,0,0))
 text_rect = textstart.get_rect()
 text_rect.centerx = screen.get_rect().centerx # x轴位置
 text_rect.centery = screen.get_rect().centery + 180 # y轴位置
 screen.blit(textstart,text_rect)

 # 判断得分更新排行榜
 # 临时变量
 j = 0
 # 读取文件
 arrayscore = read_txt(r'score.txt')[0].split('mr')
 # 循环分数列表在列表里排序
 for i in range(0,len(arrayscore)):
  if score > int(arrayscore[i]):
   # 大于排行榜上的内容 把分数和当前分数进行替换
   j = arraysco.re[i]
   arrayscore[i] = str(score)
   score = 0
  # 替换下来的分数移动一位
  if int(j) > int(arrayscore[i]):
   k = arrayscore[i]
   arrayscore[i] = str(j)
   j = k
 # 循环分数列表 写入文档
 for i in range(0,len(arrayscore)):
  # 判断列表的第一个分数
  if i == 0:
   write_txt(arrayscore[i]+'mr','w',r'score.txt')
  else:
   # 判断是否是最后一个
   if (i==9):
    # 最近添加内容最后一个分数不加 mr
    write_txt(arrayscore[i],'a',r'score.txt')
   else:
    # 不是最后一个分数,添加的时候加 mr
    write_txt(arrayscore[i]+'mr','a',r'score.txt')










# 定义排行榜函数
def gameRanking():
 # 绘制背景图片
 screen2 = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
 screen2.fill(0)
 screen2.blit(background,(0,0))
 # 使用系统字体
 xtfont = pygame.font.SysFont('jamrul',30)
 # 1.绘制标题
 textstart = xtfont.render('Ranking',True,(255,0,0))
 text_rect = textstart.get_rect()
 text_rect.centerx = screen.get_rect().centerx # x轴位置
 text_rect.centery = 50 # y轴位置
 screen.blit(textstart,text_rect)
 # 2.绘制重新开始按钮
 textstart = xtfont.render('Start',True,(255,0,0))
 text_rect = textstart.get_rect()
 text_rect.centerx = screen.get_rect().centerx # x轴位置
 text_rect.centery = screen.get_rect().centery + 120 # y轴位置
 screen.blit(textstart,text_rect)
 # 3.展示排行榜的数据
 arrayscore = read_txt(r'score.txt')[0].split('mr')
 for i in range(0,len(arrayscore)):
  font = pygame.font.Font(None,48)
  # 编写排名
  k = i+1
  text = font.render(str(k) + " "+arrayscore[i],True,(255,0,0))
  text_rect = text.get_rect()
  text_rect.centerx = screen2.get_rect().centerx
  text_rect.centery = 80 + 30*k
  # 绘制分数
  screen2.blit(text,text_rect)



startGame()

while True:
 for event in pygame.event.get():
  if event.type == pygame.QUIT:
   exit()
  # 监控鼠标的点击
  elif event.type == pygame.MOUSEBUTTONDOWN:
   # 判定重新开始范围
   if screen.get_rect().centerx - 70 <= event.pos[0]\
     and event.pos[0] <= screen.get_rect().centerx + 50\
     and screen.get_rect().centery + 100 <= event.pos[1]\
     and screen.get_rect().centery + 140 >= event.pos[1]:
    startGame()
   # 判定排行榜范围
   if screen.get_rect().centerx - 70 <= event.pos[0]\
     and event.pos[0] <= screen.get_rect().centerx + 50\
     and screen.get_rect().centery + 160 <= event.pos[1]\
     and screen.get_rect().centery + 200 >= event.pos[1]:
    gameRanking()
pygame.display.update()

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

Python 相关文章推荐
Python完全新手教程
Feb 08 Python
python 算法 排序实现快速排序
Jun 05 Python
Python入门篇之对象类型
Oct 17 Python
Python2.6版本中实现字典推导 PEP 274(Dict Comprehensions)
Apr 28 Python
Python Socket使用实例
Dec 18 Python
python 将字符串转换成字典dict的各种方式总结
Mar 23 Python
Django中的文件的上传的几种方式
Jul 23 Python
Python设计模式之迭代器模式原理与用法实例分析
Jan 10 Python
对python中类的继承与方法重写介绍
Jan 20 Python
Python OOP类中的几种函数或方法总结
Feb 22 Python
python通过移动端访问查看电脑界面
Jan 06 Python
用python-webdriver实现自动填表的示例代码
Jan 13 Python
python之pygame模块实现飞机大战完整代码
Nov 29 #Python
Python使用Pygame绘制时钟
Nov 29 #Python
详解pandas赋值失败问题解决
Nov 29 #Python
python 获取剪切板内容的两种方法
Nov 28 #Python
快速创建python 虚拟环境
Nov 28 #Python
Python基于Webhook实现github自动化部署
Nov 28 #Python
Django-simple-captcha验证码包使用方法详解
Nov 28 #Python
You might like
六酷社区论坛HOME页清新格调免费版 下载
2007/03/07 PHP
php cookie 作用范围?不要在当前页面使用你的cookie
2009/03/24 PHP
PHP 创建文件(文件夹)以及目录操作代码
2010/03/04 PHP
mysql From_unixtime及UNIX_TIMESTAMP及DATE_FORMAT日期函数
2010/03/21 PHP
PHP文件读写操作之文件读取方法详解
2011/01/13 PHP
PHP 数组和字符串互相转换实现方法
2013/03/26 PHP
php中sql注入漏洞示例 sql注入漏洞修复
2014/01/24 PHP
javascript import css实例代码
2008/07/18 Javascript
jQuery-Tools-overlay 使用介绍
2012/07/14 Javascript
JavaScript动态创建div属性和样式示例代码
2013/10/09 Javascript
简单易用的倒计时js代码
2014/08/04 Javascript
深入浅析JavaScript字符串操作方法 slice、substr、substring及其IE兼容性
2015/12/16 Javascript
JS中BOM相关知识点总结(必看篇)
2016/11/22 Javascript
vue2.0的虚拟DOM渲染思路分析
2018/08/09 Javascript
详解JavaScript作用域和作用域链
2019/03/19 Javascript
js实现打字小游戏
2019/12/17 Javascript
微信小程序拖拽排序列表的示例代码
2020/07/08 Javascript
[59:08]DOTA2上海特级锦标赛C组小组赛#2 LGD VS Newbee第一局
2016/02/27 DOTA
给Python的Django框架下搭建的BLOG添加RSS功能的教程
2015/04/08 Python
python操作 hbase 数据的方法
2016/12/18 Python
django实现登录时候输入密码错误5次锁定用户十分钟
2017/11/05 Python
python kmeans聚类简单介绍和实现代码
2018/02/23 Python
python程序封装为win32服务的方法
2021/03/07 Python
Python实现多属性排序的方法
2018/12/05 Python
详解python路径拼接os.path.join()函数的用法
2019/10/09 Python
详解python opencv、scikit-image和PIL图像处理库比较
2019/12/26 Python
运行Python编写的程序方法实例
2020/10/21 Python
CSS3 滤镜 webkit-filter详细介绍及使用方法
2012/12/27 HTML / CSS
Trunki英国官网:儿童坐骑式行李箱
2017/05/30 全球购物
英国当代时尚和街头服饰店:18montrose
2018/12/15 全球购物
Clarks其乐鞋荷兰官网:Clarks荷兰
2019/07/05 全球购物
什么是虚拟内存?虚拟内存有什么优势?
2012/02/19 面试题
实习鉴定评语
2014/01/19 职场文书
本科生导师推荐信范文
2014/05/18 职场文书
退休党员个人对照检查材料思想汇报
2014/09/29 职场文书
MySQL创建定时任务
2022/01/22 MySQL