python3实现飞机大战

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

以下是亲测Python飞机大战全部代码,在保证有pygame环境支持并且有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()

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

(0)

相关推荐

  • python实现飞机大战游戏

    飞机大战(Python)代码分为两个python文件,工具类和主类,需要安装pygame模块,能完美运行(网上好多不完整的,调试得心累.实现出来,成就感还是满满的),如图所示: 完整代码如下: 1.工具类plane_sprites.py import random import pygame # 屏幕大小的常量 SCREEN_RECT = pygame.Rect(0, 0, 480, 700) # 刷新的帧率 FRAME_PER_SEC = 60 # 创建敌机的定时器常量 CREATE_ENEM

  • python飞机大战pygame碰撞检测实现方法分析

    本文实例讲述了python飞机大战pygame碰撞检测实现方法.分享给大家供大家参考,具体如下: 目标 了解碰撞检测方法 碰撞实现 01. 了解碰撞检测方法 pygame 提供了 两个非常方便 的方法可以实现碰撞检测: pygame.sprite.groupcollide() 两个精灵组 中 所有的精灵 的碰撞检测 groupcollide(group1, group2, dokill1, dokill2, collided = None) -> Sprite_dict 如果将 dokill 设

  • python实现飞机大战

    本文实例为大家分享了python实现飞机大战的具体代码,供大家参考,具体内容如下 实现的效果如下: 主程序代码如下: import pygame from plane_sprites import * class PlaneGame(object): """飞机大战主游戏""" def __init__(self): print("游戏初始化") # 1,绘制屏幕窗口 self.screen = pygame.display.

  • 用Python写飞机大战游戏之pygame入门(4):获取鼠标的位置及运动

    目标是拷贝微信的飞机大战,当然拷贝完以后大家就具备自己添加不同内容的能力了. 首先是要拿到一些图片素材,熟悉使用图像处理软件和绘画的人可以自己制作,并没有这项技能的同学只能和我一样从网上下载相应的素材了. 网上可以找到相应的这样的图片,注意,所有的元件图片要是png类型的图片,那样可以有透明的背景,否则会有白色的边框露出来. 找到素材以后我们就要开始搭建我们的飞机大战了. 微信上的飞机大战是由手指控制的,在电脑上,我们就先用鼠标代替了. 按照之前我们在天空上移动云的那个程序,我们可以知道该怎么做

  • python版飞机大战代码分享

    利用pygame实现了简易版飞机大战.源代码如下: # -*- coding:utf-8 -*- import pygame import sys from pygame.locals import * from pygame.font import * import time import random class Hero(object): #玩家 英雄类 def __init__(self, screen_temp): self.x = 210 self.y = 700 self.life

  • python pygame模块编写飞机大战

    本文实例为大家分享了python pygame模块编写飞机大战的具体代码,供大家参考,具体内容如下 该程序没有使用精灵组,而是用列表存储对象来替代精灵组的动画效果.用矩形对象的重叠来判断相撞事件.该程序可以流畅运行,注释较为详细,希望可以帮助大家. import pygame from pygame.locals import * from sys import exit import time import random # 创建子弹类,把子弹的图片转化为图像对象,设定固定的移动速度 clas

  • python实现飞机大战小游戏

    本文实例为大家分享了python实现飞机大战的具体代码,供大家参考,具体内容如下 初学Python,写了一个简单的Python小游戏. 师出bilibili某前辈 pycharm自带了第三方库pygame,安装一下就好了,很方便. 虽然很多大佬已经给出了步骤,我这里还是啰嗦一下,也为了自己巩固一下. 上图: 这里再给出代码的逻辑架构 plane_main.py import pygame from plane_sprites import * class PlaneGame(object): "

  • python实现飞机大战游戏(pygame版)

    简介 使用python实现pygame版的飞机大战游戏: 环境:Windows系统+python3.8.0 游戏规则: 1.点击"PLAY"或者按键"P"开始游戏: 2.敌机根据设置频率从顶部随机位置生成,生成后向下移动: 3.飞船在底部中间生成,玩家使用上下左右键控制飞船移动,敲击空格键发射子弹: 4.子弹打到敌机,该敌机产生爆炸效果并累计分数到右上角: 5.消灭10只飞机后,等级升高,敌机生成频率变快,下落速度也变快: 6.当三条命都消失了,游戏结束. 游戏运行

  • python实现飞机大战微信小游戏

    0.前言 我学一种语言,可以说学任何东西都喜欢自己动手实践,总感觉自己动手一遍,就可以理解的更透彻,学python也一样,自己动手写代码,但更喜欢做点小东西出来,一边玩一边学.下面我就展示一下我最近做的一个小游戏. 1.素材准备 首先我们先来预览一下游戏的最终运行界面 根据游戏界面,我们可以清楚的知道必须要先准备游戏背景图片,飞机图片,子弹图片等等.这些素材我已经放到网上, 点我下载 ,里面包括了我的代码和图片素材. 2.代码部分 库依赖: pygame 本游戏主要有两个py文件,主文件plan

  • 500行代码使用python写个微信小游戏飞机大战游戏

    这几天在重温微信小游戏的飞机大战,玩着玩着就在思考人生了,这飞机大战怎么就可以做的那么好,操作简单,简单上手. 帮助蹲厕族.YP族.饭圈女孩在无聊之余可以有一样东西让他们振作起来!让他们的左手 / 右手有节奏有韵律的朝着同一个方向来回移动起来! 这是史诗级的发明,是浓墨重彩的一笔,是-- 在一阵抽搐后,我结束了游戏,瞬时觉得一切都索然无味,正在我进入贤者模式时,突然想到,如果我可以让更多人已不同的方式体会到这种美轮美奂的感觉岂不美哉? 所以我打开电脑,创建了一个 plan_game.py-- 先

随机推荐