python pygame模块编写飞机大战


Posted in Python onNovember 20, 2018

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

该程序没有使用精灵组,而是用列表存储对象来替代精灵组的动画效果。用矩形对象的重叠来判断相撞事件。该程序可以流畅运行,注释较为详细,希望可以帮助大家。

import pygame
from pygame.locals import *
from sys import exit
import time
import random

# 创建子弹类,把子弹的图片转化为图像对象,设定固定的移动速度
class Bullet():
 def __init__(self,bulletfilename,bulletpos):
  self.bulletimg = pygame.image.load(bulletfilename)
  self.bullet_rect = self.bulletimg.get_rect()
  self.bullet_image = self.bulletimg.subsurface(self.bullet_rect)
  self.bullet_rect.midbottom = bulletpos
  self.speed = 2
 def move(self):
  self.bullet_rect.top -= self.speed

# 创建玩家飞机类,用面向对象的思想来对待
class play_plane_fly():
 def __init__(self,play_image_filename,play_pos):
  self.image = pygame.image.load(play_image_filename)
  self.plane_rect = self.image.get_rect()
  self.play_image = self.image.subsurface(self.plane_rect)
  self.plane_rect.midtop = play_pos
  self.speed = 2
  # 子弹是由玩家飞机发射的,所以创建列表,存储子弹对象,使该列表变为该类的属性
  self.bullets = []
  self.is_hitted = False

 # 生成函数,完成发射子弹动作,同时将每个子弹对象存在列表中
 def shoot(self,bullet_filename):
  bulletobj = Bullet(bullet_filename,self.plane_rect.midtop)
  self.bullets.append(bulletobj)

 # 向上移动,当飞机移动到边框位置时,无法移动
 def moveup(self):
  if self.plane_rect.top <= 0:
   self.plane_rect.top = 0
  else:
   self.plane_rect.top -= self.speed

 # 向下移动,当飞机移动到边框位置时,无法移动
 def movedown(self):
  if self.plane_rect.top >= 950 - self.plane_rect.height:
   self.plane_rect.top = 950 - self.plane_rect.height
  else:
   self.plane_rect.top += self.speed

 # 向右移动,当飞机移动到边框位置时,无法移动
 def moveleft(self):
  if self.plane_rect.left <= -40:
   self.plane_rect.left = -40
  else:
   self.plane_rect.left -= self.speed

 # 向左移动,当飞机移动到边框位置时,无法移动
 def moveright(self):
  if self.plane_rect.left >= 700 - self.plane_rect.width:
   self.plane_rect.left = 700 - self.plane_rect.width
  else:
   self.plane_rect.left += self.speed

# 生成敌机类,设定固定的移动速度
class Enemy():
 def __init__(self,enemyfilename,enemypos):

  self.img = pygame.image.load(enemyfilename)
  self.enemy_rect = self.img.get_rect()
  self.enemy_image = self.img.subsurface(self.enemy_rect)
  self.enemy_rect.midbottom = enemypos
  self.speed = 1

 def move(self):
  self.enemy_rect.bottom += self.speed

clock = pygame.time.Clock()
def main():
 # 初始化文字屏幕
 pygame.font.init()
 # 初始化图像屏幕
 pygame.init()
 # 设定游戏帧
 clock.tick(50)
 # 设定游戏屏幕大小
 screen = pygame.display.set_mode((660,950))
 # 设定游戏名称
 pygame.display.set_caption('飞机大战')
 # 加载背景图片,生成图像对象
 background = pygame.image.load('image/background.png').convert()
 backgroundsurface = pygame.transform.scale(background, (660, 950))
 # 加载游戏结束图片,生成图像对象
 gameover = pygame.image.load('image/gameover.png').convert()
 gameoversurface = pygame.transform.scale(gameover,(660, 950))
 playplanefilename = 'image/myself.png'
 planepos = [330,600]
 player = play_plane_fly(playplanefilename,planepos)
 bulletfilename = 'image/bullet.png'
 # 按频率生成子弹,初始化数字为0
 bullet_frequency = 0
 enemyfilename = 'image/airplane.png'
 # 按频率生成敌机,初始化数字为0
 enemy_frequency = 0
 enemys = []
 myfont = pygame.font.SysFont("arial", 40)
 textImage = myfont.render("Score ", True, (0,0,0))
 # 初始化得分为0
 Score = 0
 # 敌机被子弹击中时的动画,将每张图片的图像对象存在列表中
 enenys_down = []
 enemy0_down = pygame.image.load('image/airplane_ember0.png')
 enemy0_down_rect = enemy0_down.get_rect()
 enemydown0 = enemy0_down.subsurface(enemy0_down_rect)
 enenys_down.append(enemydown0)
 enemy1_down = pygame.image.load('image/airplane_ember1.png')
 enemy1_down_rect = enemy1_down.get_rect()
 enemydown1 = enemy1_down.subsurface(enemy1_down_rect)
 enenys_down.append(enemydown1)
 enemy2_down = pygame.image.load('image/airplane_ember2.png')
 enemy2_down_rect = enemy2_down.get_rect()
 enemydown2 = enemy2_down.subsurface(enemy2_down_rect)
 enenys_down.append(enemydown2)
 enemy3_down = pygame.image.load('image/airplane_ember3.png')
 enemy3_down_rect = enemy3_down.get_rect()
 enemydown3 = enemy3_down.subsurface(enemy3_down_rect)
 enenys_down.append(enemydown3)


 while True:
  # 动态显示得分
  score = str(Score)
  myscore = pygame.font.SysFont("arial", 40)
  scoreImage = myscore.render(score, True, (0, 0, 0))
  # 判断事件,防止卡顿或者意外退出
  for event in pygame.event.get():
   if event.type == pygame.QUIT:
    pygame.quit()
    exit()
  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()

  screen.blit(backgroundsurface, (0, 0))

  if not player.is_hitted:
   # 按频率生成子弹
   if bullet_frequency % 30 == 0:
    player.shoot(bulletfilename)
   bullet_frequency += 1
   if bullet_frequency >= 30:
    bullet_frequency = 0
   # 让子弹动起来
   for i in player.bullets:
    i.move()
    screen.blit(i.bullet_image,i.bullet_rect)
    # 当子弹飞出屏幕,删除子弹对象
    if i.bullet_rect.bottom <= 0:
     player.bullets.remove(i)
   # 按频率生成敌机
   if enemy_frequency % 100 == 0:
    enemypos = [random.randint(30, 630), 0]
    enemyplane = Enemy(enemyfilename, enemypos)
    #将敌机对象添加到列表中
    enemys.append(enemyplane)
   enemy_frequency += 1
   if enemy_frequency >= 100:
    enemy_frequency = 0
   # 让敌机动起来
   for i in enemys:
    i.move()
    screen.blit(i.enemy_image,i.enemy_rect)
    # 当敌机飞出屏幕,删除敌机对象
    if i.enemy_rect.bottom >= 950:
     enemys.remove(i)
    # 遍历子弹对象,判断子弹是否击中敌机
    for j in player.bullets:
     # 如果击中,分数增加,同时移除该子弹和敌机对象
     if pygame.Rect.colliderect(j.bullet_rect,i.enemy_rect):
      Score += 100
      enemys.remove(i)
      player.bullets.remove(j)
      for k in enenys_down:
       screen.blit(k,i.enemy_rect)
    # 遍历敌机对象,判断玩家是否和敌机相撞
    if pygame.Rect.colliderect(player.plane_rect,i.enemy_rect):
     # 修改is_hitted的值,跳出该层循环
     player.is_hitted = True
     break


   screen.blit(player.play_image,player.plane_rect)
   screen.blit(textImage, (0,0))
   screen.blit(scoreImage, (110, 0))
   pygame.display.update()
  # 玩家退出时显示分数和游戏结束
  else:
   screen.blit(gameoversurface,(0,0))
   screen.blit(textImage, (0, 0))
   screen.blit(scoreImage, (110, 0))
   pygame.display.update()
   time.sleep(2)
   break

main()

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

Python 相关文章推荐
Python调用C语言开发的共享库方法实例
Mar 18 Python
给Python的Django框架下搭建的BLOG添加RSS功能的教程
Apr 08 Python
深入浅出学习python装饰器
Sep 29 Python
Python简单实现查找一个字符串中最长不重复子串的方法
Mar 26 Python
opencv python 图像去噪的实现方法
Aug 31 Python
python3 打开外部程序及关闭的示例
Nov 06 Python
pandas数据集的端到端处理
Feb 18 Python
python读取图片的方式,以及将图片以三维数组的形式输出方法
Jul 03 Python
使用Python给头像戴上圣诞帽的图像操作过程解析
Sep 20 Python
python实现按关键字筛选日志文件
Dec 24 Python
Python使用扩展库pywin32实现批量文档打印实例
Apr 09 Python
如何正确理解python装饰器
Jun 15 Python
Python Scapy随心所欲研究TCP协议栈
Nov 20 #Python
python版飞机大战代码分享
Nov 20 #Python
pygame实现雷电游戏雏形开发
Nov 20 #Python
pygame游戏之旅 游戏中添加显示文字
Nov 20 #Python
pygame游戏之旅 添加键盘按键的方法
Nov 20 #Python
pygame游戏之旅 载入小车图片、更新窗口
Nov 20 #Python
一文带你了解Python中的字符串是什么
Nov 20 #Python
You might like
PHP strcmp()和strcasecmp()的区别实例
2016/11/05 PHP
[原创]PHP获取数组表示的路径方法分析【数组转字符串】
2017/09/01 PHP
Javascript中正则表达式的全局匹配模式分析
2011/04/26 Javascript
Javascript实现简单的富文本编辑器附演示
2014/06/16 Javascript
node.js中的fs.fchownSync方法使用说明
2014/12/16 Javascript
Python脚本后台运行的几种方式
2015/03/09 Javascript
JavaScript跨平台的开源框架NativeScript
2015/03/24 Javascript
Juery解决tablesorter中文排序和字符范围的方法
2015/05/06 Javascript
详解Javascript继承的实现
2016/03/25 Javascript
js获取鼠标点击的对象,点击另一个按钮删除该对象的实现代码
2016/05/13 Javascript
微信小程序 scroll-view组件实现列表页实例代码
2016/12/14 Javascript
详解JS中的快速排序与冒泡
2017/01/10 Javascript
jQuery使用siblings获取某元素所有同辈(兄弟姐妹)元素用法示例
2017/01/30 Javascript
超级简易的JS计算器实例讲解(实现加减乘除)
2017/08/08 Javascript
JS中的两种数据类型及实现引用类型的深拷贝的方法
2018/08/12 Javascript
js实现登录拖拽窗口
2020/02/10 Javascript
jQuery HTML css()方法与css类实例详解
2020/05/20 jQuery
[03:58]兄弟们,回来开黑了!DOTA2昔日战友招募宣传视频
2016/07/17 DOTA
[01:23:24]DOTA2-DPC中国联赛 正赛 PSG.LGD vs Elephant BO3 第三场 2月7日
2021/03/11 DOTA
Python实现自动登录百度空间的方法
2017/06/10 Python
Python基于whois模块简单识别网站域名及所有者的方法
2018/04/23 Python
详解numpy矩阵的创建与数据类型
2019/10/18 Python
ubuntu 18.04 安装opencv3.4.5的教程(图解)
2019/11/04 Python
Anaconda+spyder+pycharm的pytorch配置详解(GPU)
2020/10/18 Python
PyQT5速成教程之Qt Designer介绍与入门
2020/11/02 Python
HTML5 input新增type属性color颜色拾取器的实例代码
2018/08/27 HTML / CSS
Linux Interview Questions For software testers
2012/06/02 面试题
法律专业自我鉴定
2013/10/03 职场文书
《影子》教学反思
2014/02/21 职场文书
领导失职检讨书
2014/02/24 职场文书
企业优秀团员事迹材料
2014/08/20 职场文书
学校领导班子四风问题整改意见
2014/10/02 职场文书
教师个人事迹材料
2014/12/17 职场文书
经营场所使用证明
2015/06/19 职场文书
会计专业2019暑假实习报告
2019/06/21 职场文书
详解MySql中InnoDB存储引擎中的各种锁
2022/02/12 MySQL