Python版飞机大战
前面学了java用java写了飞机大战这次学完python基础后写了个python版的飞机大战,有兴趣的可以看下。
父类是飞行物类是所有对象的父类,setting里面是需要加载的图片,你可以换称自己的喜欢的图片,敌机可以分为敌机和奖励,enemy为普通敌人的父类,award为奖励敌机的父类。
各个类的基本属性
主类的大概逻辑
具体的代码:
settings配置
import pygame
class Settings(object):
"""设置常用的属性"""
def __init__(self):
self.bgImage = pygame.image.load('img/background.png') # 背景图
self.bgImageWidth = self.bgImage.get_rect()[2] # 背景图宽
self.bgImageHeight = self.bgImage.get_rect()[3] # 背景图高
self.start=pygame.image.load("img/start.png")
self.pause=pygame.image.load("img/pause.png")
self.gameover=pygame.image.load("img/gameover.png")
self.heroImages = ["img/hero.gif",
"img/hero1.png", "img/hero2.png"] # 英雄机图片
self.airImage = pygame.image.load("img/enemy0.png") # airplane的图片
self.beeImage = pygame.image.load("img/bee.png") # bee的图片
self.heroBullet=pygame.image.load("img/bullet.png")# 英雄机的子弹
飞行物类
import abc
class FlyingObject(object):
"""飞行物类,基类"""
def __init__(self, screen, x, y, image):
self.screen = screen
self.x = x
self.y = y
self.width = image.get_rect()[2]
self.height = image.get_rect()[3]
self.image = image
@abc.abstractmethod
def outOfBounds(self):
"""检查是否越界"""
pass
@abc.abstractmethod
def step(self):
"""飞行物移动一步"""
pass
def shootBy(self, bullet):
"""检查当前飞行物是否被子弹bullet(x,y)击中"""
x1 = self.x
x2 = self.x + self.width
y1 = self.y
y2 = self.y + self.height
x = bullet.x
y = bullet.y
return x > x1 and x < x2 and y > y1 and y < y2
def blitme(self):
"""打印飞行物"""
self.screen.blit(self.image, (self.x, self.y))
英雄机
from flyingObject import FlyingObject
from bullet import Bullet
import pygame
class Hero(FlyingObject):
"""英雄机"""
index = 2 # 标志位
def __init__(self, screen, images):
# self.screen = screen
self.images = images # 英雄级图片数组,为Surface实例
image = pygame.image.load(images[0])
x = screen.get_rect().centerx
y = screen.get_rect().bottom
super(Hero,self).__init__(screen,x,y,image)
self.life = 3 # 生命值为3
self.doubleFire = 0 # 初始火力值为0
def isDoubleFire(self):
"""获取双倍火力"""
return self.doubleFire
def setDoubleFire(self):
"""设置双倍火力"""
self.doubleFire = 40
def addDoubleFire(self):
"""增加火力值"""
self.doubleFire += 100
def clearDoubleFire(self):
"""清空火力值"""
self.doubleFire=0
def addLife(self):
"""增命"""
self.life += 1
def sublife(self):
"""减命"""
self.life-=1
def getLife(self):
"""获取生命值"""
return self.life
def reLife(self):
self.life=3
self.clearDoubleFire()
def outOfBounds(self):
return False
def step(self):
"""动态显示飞机"""
if(len(self.images) > 0):
Hero.index += 1
Hero.index %= len(self.images)
self.image = pygame.image.load(self.images[int(Hero.index)]) # 切换图片
def move(self, x, y):
self.x = x - self.width / 2
self.y = y - self.height / 2
def shoot(self,image):
"""英雄机射击"""
xStep=int(self.width/4-5)
yStep=20
if self.doubleFire>=100:
heroBullet=[Bullet(self.screen,image,self.x+1*xStep,self.y-yStep),Bullet(self.screen,image,self.x+2*xStep,self.y-yStep),Bullet(self.screen,image,self.x+3*xStep,self.y-yStep)]
self.doubleFire-=3
return heroBullet
elif self.doubleFire<100 and self.doubleFire > 0:
heroBullet=[Bullet(self.screen,image,self.x+1*xStep,self.y-yStep),Bullet(self.screen,image,self.x+3*xStep,self.y-yStep)]
self.doubleFire-=2
return heroBullet
else:
heroBullet=[Bullet(self.screen,image,self.x+2*xStep,self.y-yStep)]
return heroBullet
def hit(self,other):
"""英雄机和其他飞机"""
x1=other.x-self.width/2
x2=other.x+self.width/2+other.width
y1=other.y-self.height/2
y2=other.y+self.height/2+other.height
x=self.x+self.width/2
y=self.y+self.height
return x>x1 and x<x2 and y>y1 and y<y2
enemys
import abc
class Enemy(object):
"""敌人,敌人有分数"""
@abc.abstractmethod
def getScore(self):
"""获得分数"""
pass
award
import abc
class Award(object):
"""奖励"""
DOUBLE_FIRE = 0
LIFE = 1
@abc.abstractmethod
def getType(self):
"""获得奖励类型"""
pass
if __name__ == '__main__':
print(Award.DOUBLE_FIRE)
airplane
import random
from flyingObject import FlyingObject
from enemy import Enemy
class Airplane(FlyingObject, Enemy):
"""普通敌机"""
def __init__(self, screen, image):
x = random.randint(0, screen.get_rect()[2] - 50)
y = -40
super(Airplane, self).__init__(screen, x, y, image)
def getScore(self):
"""获得的分数"""
return 5
def outOfBounds(self):
"""是否越界"""
return self.y < 715
def step(self):
"""移动"""
self.y += 3 # 移动步数
Bee
import random
from flyingObject import FlyingObject
from award import Award
class Bee(FlyingObject, Award):
def __init__(self, screen, image):
x = random.randint(0, screen.get_rect()[2] - 60)
y = -50
super(Bee, self).__init__(screen, x, y, image)
self.awardType = random.randint(0, 1)
self.index = True
def outOfBounds(self):
"""是否越界"""
return self.y < 715
def step(self):
"""移动"""
if self.x + self.width > 480:
self.index = False
if self.index == True:
self.x += 3
else:
self.x -= 3
self.y += 3 # 移动步数
def getType(self):
return self.awardType
主类
import pygame
import sys
import random
from setting import Settings
from hero import Hero
from airplane import Airplane
from bee import Bee
from enemy import Enemy
from award import Award
START=0
RUNNING=1
PAUSE=2
GAMEOVER=3
state=START
sets = Settings()
screen = pygame.display.set_mode(
(sets.bgImageWidth, sets.bgImageHeight), 0, 32) #创建窗口
hero=Hero(screen,sets.heroImages)
flyings=[]
bullets=[]
score=0
def hero_blitme():
"""画英雄机"""
global hero
hero.blitme()
def bullets_blitme():
"""画子弹"""
for b in bullets:
b.blitme()
def flyings_blitme():
"""画飞行物"""
global sets
for fly in flyings:
fly.blitme()
def score_blitme():
"""画分数和生命值"""
pygame.font.init()
fontObj=pygame.font.Font("SIMYOU.TTF", 20) #创建font对象
textSurfaceObj=fontObj.render(u'生命值:%d\n分数:%d\n火力值:%d'%(hero.getLife(),score,hero.isDoubleFire()),False,(135,100,184))
textRectObj=textSurfaceObj.get_rect()
textRectObj.center=(300,40)
screen.blit(textSurfaceObj,textRectObj)
def state_blitme():
"""画状态"""
global sets
global state
if state==START:
screen.blit(sets.start, (0,0))
elif state==PAUSE:
screen.blit(sets.pause,(0,0))
elif state== GAMEOVER:
screen.blit(sets.gameover,(0,0))
def blitmes():
"""画图"""
hero_blitme()
flyings_blitme()
bullets_blitme()
score_blitme()
state_blitme()
def nextOne():
"""生成敌人"""
type=random.randint(0,20)
if type<4:
return Bee(screen,sets.beeImage)
elif type==5:
return Bee(screen,sets.beeImage) #本来准备在写几个敌机的,后面没找到好看的图片就删了
else:
return Airplane(screen,sets.airImage)
flyEnteredIndex=0
def enterAction():
"""生成敌人"""
global flyEnteredIndex
flyEnteredIndex+=1
if flyEnteredIndex%40==0:
flyingobj=nextOne()
flyings.append(flyingobj)
shootIndex=0
def shootAction():
"""子弹入场,将子弹加到bullets"""
global shootIndex
shootIndex +=1
if shootIndex % 10 ==0:
heroBullet=hero.shoot(sets.heroBullet)
for bb in heroBullet:
bullets.append(bb)
def stepAction():
"""飞行物走一步"""
hero.step()
for flyobj in flyings:
flyobj.step()
global bullets
for b in bullets:
b.step()
def outOfBoundAction():
"""删除越界的敌人和飞行物"""
global flyings
flyingLives=[]
index=0
for f in flyings:
if f.outOfBounds()==True:
flyingLives.insert(index,f)
index+=1
flyings=flyingLives
index=0
global bullets
bulletsLive=[]
for b in bullets:
if b.outOfBounds()==True:
bulletsLive.insert(index,b)
index+=1
bullets=bulletsLive
j=0
def bangAction():
"""子弹与敌人碰撞"""
for b in bullets:
bang(b)
def bang(b):
"""子弹与敌人碰撞检测"""
index=-1
for x in range(0,len(flyings)):
f=flyings[x]
if f.shootBy(b):
index=x
break
if index!=-1:
one=flyings[index]
if isinstance(one,Enemy):
global score
score+=one.getScore() # 获得分数
flyings.remove(one) # 删除
if isinstance(one,Award):
type=one.getType()
if type==Award.DOUBLE_FIRE:
hero.addDoubleFire()
else:
hero.addLife()
flyings.remove(one)
bullets.remove(b)
def checkGameOverAction():
if isGameOver():
global state
state=GAMEOVER
hero.reLife()
def isGameOver():
for f in flyings:
if hero.hit(f):
hero.sublife()
hero.clearDoubleFire()
flyings.remove(f)
return hero.getLife()<=0
def action():
x, y = pygame.mouse.get_pos()
blitmes() #打印飞行物
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
flag=pygame.mouse.get_pressed()[0] #左键单击事件
rflag=pygame.mouse.get_pressed()[2] #右键单击事件
global state
if flag==True and (state==START or state==PAUSE):
state=RUNNING
if flag==True and state==GAMEOVER:
state=START
if rflag==True:
state=PAUSE
if state==RUNNING:
hero.move(x,y)
enterAction()
shootAction()
stepAction()
outOfBoundAction()
bangAction()
checkGameOverAction()
def main():
pygame.display.set_caption("飞机大战")
while True:
screen.blit(sets.bgImage, (0, 0)) # 加载屏幕
action()
pygame.display.update() # 重新绘制屏幕
# time.sleep(0.1) # 过0.01秒执行,减轻对cpu的压力
if __name__ == '__main__':
main()
``` 写这个主要是练习一下python,把基础打实些。pygame的文本书写是没有换行,得在新建一个对象去写,为了简单我把文本都书写在了一行。
**background.png**

**hero.gif**



**bee.png**

**enemy.png**

**gameover.png**

**start.png**

Python版飞机大战的更多相关文章
- python版飞机大战代码简易版
# -*- coding:utf-8 -*- import pygame import sys from pygame.locals import * from pygame.font import ...
- 微信5.0 Android版飞机大战破解无敌模式手记
微信5.0 Android版飞机大战破解无敌模式手记 转载: http://www.blogjava.net/zh-weir/archive/2013/08/14/402821.html 微信5.0 ...
- 一、利用Python编写飞机大战游戏-面向对象设计思想
相信大家看到过网上很多关于飞机大战的项目,但是对其中的模块方法,以及使用和游戏工作原理都不了解,看的也是一脸懵逼,根本看不下去.下面我做个详细讲解,在做此游戏需要用到pygame模块,所以这一章先进行 ...
- java版飞机大战 实战项目详细步骤.md
[toc] 分析 飞机大战 首先对这个游戏分析,在屏幕上的物体都是飞行物,我们可以把建一个类,让其他飞行物继承这个类.游戏中应有英雄机(也就是自己控制的飞机).敌人.而敌人应该分为打死给分的飞机(就是 ...
- python项目飞机大战
实现步骤 1.创建窗口 2.创建一个玩家飞机,按方向键可以左右移动 3.给玩家飞机添加按空格键发射子弹功能 4.创建一个敌机 5.敌机自动左右移动 6.敌机自动发射子弹 1.创建窗口 import p ...
- 基于Python的飞机大战游戏
前几天决定学Python,上网找了教程看了两天,和C比起来面向对象的特性真的都很便捷,有了类开发各种敌机,子弹什么的都很方便. 在此要感谢开发pygame模块的开发人员,真的很好用(逃 效果图↓ 主函 ...
- java版飞机大战代码
@ 目录 前言 Plane PlaneStatus类 Power类 Gift Diji play类 over类 MainFrame主类 MyZiDan DijiZiDan Before 前言 很久之前 ...
- 用DIV+Css+Jquery 实现的旧版微信飞机大战。
用jquery 实现的旧版微信飞机大战. 以前一直都是做后台和业务逻辑,前端很少去做, 现在个小游戏. 方向键控制方向,Ctrl 键 放炸弹(当然你的有炸弹,哈哈)! 主要都是用div+Css实现的, ...
- Python小游戏之 - 飞机大战美女 !
用Python写的"飞机大战美女"小游戏 源代码如下: # coding=utf-8 import os import random import pygame # 用一个常量来存 ...
随机推荐
- Beta 反(tu)思(cao) && 获小黄衫感言
写在前面 终于要结束了...我的心情就像走在沙漠中的人看到了一片绿洲一样,身体很疲惫,心情是自由自在~ 这是一篇总结反思的博客 (为了附加分),顺便把早该写的获小黄衫感言一起发了. Beta 反思 做 ...
- 【ZJOI 2018】 历史(lct)
历史 题目描述 九条可怜是一个热爱阅读的女孩子. 这个世界有 $n$ 个城市,这 $n$ 个城市被恰好 $n-1$ 条双向道路联通,即任意两个城市都可以互相到达.同时城市 $1$ 坐落在世界的中心,占 ...
- BZOJ1443 [JSOI2009]游戏Game 【博弈论 + 二分图匹配】
题目链接 BZOJ1443 题解 既然是网格图,便可以二分染色 二分染色后发现,游戏路径是黑白交错的 让人想到匹配时的增广路 后手要赢[指移动的后手],必须在一个与起点同色的地方终止 容易想到完全匹配 ...
- 关于[x/y]一些小想法
[x/y],即x除以y下取整 (不会LATEX) 1.对于给定的x,对于所有的1<=y<=x, [x/y]一共有√x种取值. 证明: 对于y<=√x,y有根号种,所以值最多根号种.对 ...
- springcloud之config 配置管理中心之配置属性加密解密
1.为什么要加密解密? 为了维护项目的安全性. 2.配置加密解密的前提是什么? 要进行JCE下载,然后替换掉jdk的security文件: 下载链接:http://www.oracle.com/tec ...
- 【python】python安装lxml报错【2】
cl : Command line warning D9025 : overriding '/W3' with '/w' lxml.etree.c c:\docume~\admini~.chi\loc ...
- linux命令总结之查找命令find、locate、whereis、which、type
我们经常需要在系统中查找一个文件,那么在Linux系统中我们如何准确高效的确定一个文件在系统中的具体位置呢?一下我总结了在linux系统中用于查找文件的几个命令. 1.find命令 find是最常用也 ...
- P2572 [SCOI2010]序列操作
对自己 & \(RNG\) : 骄兵必败 \(lpl\)加油! P2572 [SCOI2010]序列操作 题目描述 lxhgww最近收到了一个01序列,序列里面包含了n个数,这些数要么是0,要 ...
- Hadoop基础原理
Hadoop基础原理 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 业内有这么一句话说:云计算可能改变了整个传统IT产业的基础架构,而大数据处理,尤其像Hadoop组件这样的技术出 ...
- 转【Zabbix性能调优:配置优化】
转载:https://sre.ink/zabbix-turn-conf/ #通过日志可以分析当前服务状态.LogFile=/tmp/zabbix_server.log #日志文件路径.LogFileS ...