飞机大战编程
飞机大战没有封装的前的代码
import pygame
from pygame.locals import *
import random
import time
class HeroBullet():#定义一个战机子弹的类
def __init__(self,x,y,windows):
self.x=x
self.y=y
self.windows=windows
self.pic=pygame.image.load('D:\\python使用软件\\IT研究院-Python\\New_Stydy\\img\\bullet.png')
def draw(self):#用来画子弹
self.windows.blit(self.pic,(self.x,self.y))
self.move()
def move(self):
self.y-=5
class EnemyBullet():
def __init__(self,x,y,windows):
self.x=x
self.y=y
self.windows=windows
self.pic=pygame.image.load('D:\\python使用软件\\IT研究院-Python\\New_Stydy\\img\\bullet1.png')
def draw(self):
self.windows.blit(self.pic,(self.x,self.y))
self.move()
def move(self):
self.y+=5
windows=pygame.display.set_mode((480,650),0,32)#创建窗口
bg=pygame.image.load('D:\\python使用软件\\IT研究院-Python\\New_Stydy\\img\\background.png')
pygame.display.set_caption('灰机大战')
icon=pygame.image.load('D:\\python使用软件\\IT研究院-Python\\New_Stydy\\img\\icon72x72.png')
pygame.display.set_icon(icon)
heroPlane1=pygame.image.load('D:\\python使用软件\\IT研究院-Python\\New_Stydy\\img\\hero1.png')
heroPlane2=pygame.image.load('D:\\python使用软件\\IT研究院-Python\\New_Stydy\\img\\hero2.png')
enemyPlane=pygame.image.load('D:\\python使用软件\\IT研究院-Python\\New_Stydy\\img\\enemy1.png')
enemyBombList=[ 'D:\\python使用软件\\IT研究院-Python\\New_Stydy\\img\\enemy1_down1.png',
'D:\\python使用软件\\IT研究院-Python\\New_Stydy\\img\\enemy1_down2.png',
'D:\\python使用软件\\IT研究院-Python\\New_Stydy\\img\\enemy1_down3.png',
'D:\\python使用软件\\IT研究院-Python\\New_Stydy\\img\\enemy1_down4.png',]
heroIndexShift=0
direct='左'
pygame.key.set_repeat(20,30)#重复按键指令
heroPlaneX=190
heroPlaneY=526
enemyPlaneX=480//2-69//2
enemyPlaneY=0
BiuList=[]
enemyBiulist=[]
enemy_isBomb=False#敌机爆炸条件
enemy_BombIndex=0#爆炸图片索引
while True:
windows.blit(bg,(0,0))#把图片贴上去!
if heroIdexShift==0:
windows.blit(heroPlane1,(heroPlaneX,heroPlaneY))
heroIdexShift+=1
else:
windows.blit(heroPlane2, (heroPlaneX, heroPlaneY))
heroIdexShift=0
if direct=='左':#敌机移动
enemyPlaneX-=5
if enemyPlaneX<=0:
direct='右'
elif direct=='右':
enemyPlaneX+=5
if enemyPlaneX>=480-69:
direct='左'
if enemy_isBomb==False:#敌机爆炸
windows.blit(enemyPlane,(enemyPlaneX,enemyPlaneY))
else:
if enemy_BombIndex==len(enemyBombList):
time.sleep(0.1)
exit(0)
pic=pygame.image.load(enemyBombList[enemy_BombIndex])
windows.blit(pic,(enemyPlaneX,enemyPlaneY))
enemy_BombIndex=(enemy_BombIndex+1)
time.sleep(0.1)
for biu in BiuList:
biu.draw()
BiuList.remove(biu) if biu.y<0 else '' #让子弹到最上边的时候,不至于消失
for biu in EnemyBiulist:
biu.draw()
EnemyBiulist.remove(biu) if biu.y>650-79 else''
for event in pygame.event.get():
if event.type==pygame.QUIT:
print('关闭了')
exit(0)
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_LEFT
heroPlaneX=heroPlaneX-5 if heroPlaneX>=5 else 0
elif event.key==pygame.K_RIGHT:
heroPlaneX=heroPlaneX+5 if heroPlaneX<=375 else 380
elif event.key==pygame.K_DOWN:
heroPlaneY=heroPlaneY+5 if heroPlaneY<=521 else 526
elif event.key==pygame.K_UP:
heroPlaneY=heroPlaneY-5 if heroPlaneY>=5 else 0
elif event.key==K_SPACE:
oneBiu=HeroBullet(heroPlaneX+50-11,heroPlaneY-22,windows)
BiuList.append(oneBiu)
x=random.randint(0,100)
if x==5 or x==79:
oneBiu=EnemyBullet(enemyPlaneX+69//2-9//2,enemyPlaneY+89,windows)
EnemyBiulist.append(oneBiu)
enemyRect=Rect(enemyPlaneX,enemyPlaneY,69,89)
for biu in BiuList:
biuRect=Rect(biu.x,biu.y,22,22)
if biuRect.colliderect(enemyRect):#当战机子弹和敌机重叠时爆炸
print('爆炸')
enemy_isBomb=True
BiuList.remove(biu)
pygame.display.update()
第一封装:
import pygame,random,time,os
from pygame.locals import *
def getPic(path):
#path只是文件名称,在这里是图片名称。加入到绝对路径上,写此函数易于不同环境下的修改
return os.path.join('D:\\python使用软件\\IT研究院-Python\\New_Stydy\\img',path)
class HeroBullet():
def __init__(self,x,y,windows):
self.x=x
self.y=y
self.windows=windows
self.pic=pygame.image.load(getPic('bullet.png'))
def draw(self):
self.windows.blit(self.pic,(self.x,self.y))
self.move()
def move(self):
self.y-=5
class EnemyBullet():
def __init__(self,x,y,windows):
self.x=x
self.y=y
self.windows=windows
self.pic=pygame.image.load(getPic('bullet1.png'))
def draw(self):
self.windows.blit(self.pic,(self.x,self.y))
self.move()
def move(self):
self.y+=5
class EnemyPlane():
def __init__(self,x,y,windows):
self.x=x
self.y=y
self.windows=windows
self.normalImageList=['enemy1.png']
self.normalImageIndex=0
self.bombImageList=['enemy1_down1.png','enemy1_down2.png','enemy1_down3.png','enemy1_down4.png',]
self.bombImageIndex=0
self.isbomb=False
self.biuList=[]
self.direct='左'
def draw(self):
if self.isbomb==False:
pic=pygame.image.load(getPic(self.normalImageList[self.normalImageIndex]))
self.windows.blit(pic,(self.x,self.y))
self.normalImageIndex=(self.normalImageIndex+1)%len(self.normalImageList)#是让两张照片无线循环
else:
if self.bombImageIndex==len(self.bombImageList):
time.sleep(0.8)
exit(0)
pic = pygame.image.load(getPic(self.bombImageList[self.bombImageIndex]))
self.windows.blit(pic,(self.x, self.y))
self.bombImageIndex=(self.bombImageIndex + 1)
time.sleep(0.6)
self.move()
self.fire()
for biu in self.biuList:
biu.draw()
self.biuList.remove(biu) if self.y>650 else''
def move(self):
if self.direct =='左':
self.x-=5
if self.x<=0:
self.direct='右'
elif self.direct =='右':
self.x+=5
if self.x>=480-69:
self.direct='左'
def fire(self):
x=random.randint(0,100)
if x==5 or x==79:
oneBiu=EnemyBullet(self.x+69//2-9//2, self.y+89, windows)
self.biuList.append(oneBiu)
def pzjc(self,bList):#敌机爆炸检测条件
eRect=Rect(self.x,self.y,69,89)
for biu in bList:
bRect=Rect(biu.x,biu.y,22,22)
if bRect.colliderect(eRect):
self.isbomb=True
class HeroPlane():
def __init__(self,x,y,windows):
self.x=x
self.y=y
self.windows=windows
self.normalImageList=['hero1.png','hero2.png']#为爆炸的图片列表
self.normaIndex=0
self.bombImageList=['hero_blowup_n1.png','hero_blowup_n2.png','hero_blowup_n3.png','hero_blowup_n4.png']
self.bombIamgeIndex=0#显示图片列表索引
self.isBomb=False
self.biuList=[]
def draw(self):
if self.isBomb==False:
pic=pygame.image.load(getPic(self.normalImageList[self.normaIndex]))
self.windows.blit(pic,(self.x,self.y))
self.normaIndex=(self.normaIndex+1)%len(self.normalImageList)#将战机两张照片循环出现
else:
if self.bombImageIndex == len(self.bombImageList):
time.sleep(0.8)
exit(0)
pic=pygame.image.load(getPic(self.bombImageList[self.bombImageIndex]))
self.windows.blit(pic, (self.x, self.y))
self.bombImageIndex = (self.bombImageIndex + 1)
time.sleep(0.6)
for biu in self.biuList:
biu.draw()
self.biuList.remove(biu)if biu.y<0 else''
def dealEvent(self,eventList):
for event in eventList:
if event.type==QUIT:
exit(0)
if event.type==KEYDOWN:
if event.key==K_LEFT:
self.x=self.x-5 if self.x>=5 else 0
elif event.key==K_RIGHT:
self.x=self.x+5 if self.x<=480-5-100 else 380
elif event.key==K_UP:
self.y=self.y-5 if self.y>=5 else 0
elif event.key==K_DOWN :
self.y=self.y+5 if self.y<=650-124-5 else 650-124
elif event.key==K_SPACE:
oneBiu=HeroBullet(self.x+39,self.y-22,windows)
self.biuList.append(oneBiu)
def pzjc(self,bList):#爆炸检测条件
eRect=Rect(self.x,self.y,100,124)
for biu in bList:
bRect=Rect(biu.x,biu.y,9,21)
if bRect.colliderect(eRect):
self.isbomb=True
windows=pygame.display.set_mode((480,650),0,32)
pygame.display.set_caption('灰机大战')#写游戏的名称
icon=pygame.image.load(getPic('icon72x72.png'))
pygame.key.set_repeat(20,30)#设置按键的延迟,增加按键的灵活度用key.set_repeat(delay,interval)就是按住某个键每隔interval毫秒产生一个KEYDOWN事件,delay就是多少毫秒后才开始触发这个事件。
pygame.display.set_icon(icon)#更新游戏图标
bg=pygame.image.load(getPic('background.png'))
heroPlane=HeroPlane(480//2-100//2,650-124,windows)
enemyPlane=EnemyPlane(480//2-69//2,0,windows)
while True:
windows.blit(bg,(0,0))#贴背景图
enemyPlane.pzjc(heroPlane.biuList)
heroPlane.pzjc(enemyPlane.biuList)
heroPlane.draw()#调用函数
enemyPlane.draw()
heroPlane.dealEvent(pygame.event.get())
pygame.display.update()#游戏更新
父类调用子类方法,父类不能被实例化
class Base():
def __init__(self,name):
self.name=name
def say(self):#如果调用子类函数,父类不能被实例化,一定会报错
self.change()
class Bu(Base):
def change(self):
print('刘德华')
a=Bu('张三')
a.say()
b=Base('李四')
b.say()
最终封装
# encoding:utf-8
import random
_date_ = '2019/12/31 10:28'
import pygame
import os
import time
def get_pic(path):
'''获取图片'''
# 拼接图片路径
pic_path = os.path.join('D:\\PythonCode\\PlaneWars\\img', path)
# 返回pygame对象
return pygame.image.load(pic_path)
class Base:
def __init__(self,x,y,screen):
self.x = x
self.y = y
self.screen = screen
class Basebullet(Base):
def __init__(self,x,y,screen):
super().__init__(x,y,screen)
self.pic = ''
def draw(self):
self.screen.blit(self.pic, (self.x, self.y))
self.move()
def move(self):
pass
class HeroBullet(Basebullet):
'''英雄子弹类'''
def __init__(self, x, y, screen):
super().__init__(x,y,screen)
self.pic = get_pic('bullet.png')
def move(self):
'''让子弹移动'''
self.y -= 5
class EnemyBullet(Basebullet):
'''敌机子弹'''
def __init__(self, x, y, screen):
super().__init__(x,y,screen)
self.pic = get_pic('zidan.png')
def move(self):
self.y += 5
class BasePlane(Base):
def __init__(self,x,y,screen):
super().__init__(x,y,screen)
self.isBomb = False # 爆炸条件
self.normal_image_index = 0 # 正常图片索引
self.bomb_image_index = 0
# 定义存放子弹的列表
self.bullet_list = []
class HeroPlane(BasePlane):
'''英雄机类'''
def __init__(self, x, y, screen):
super().__init__(x,y,screen)
self.normal_iamge_list = ['hero1.png', 'hero2.png'] # 正常 图片
self.bomb_image_list = ['hero_blowup_n1.png', 'hero_blowup_n2.png', 'hero_blowup_n3.png', 'hero_blowup_n4.png']
def draw(self):
'''绘制英雄机图片'''
if self.isBomb == False: # 未爆炸情况
pic = get_pic(self.normal_iamge_list[self.normal_image_index])
self.screen.blit(pic, (self.x, self.y)) # 绘制未爆炸 英雄机
self.normal_image_index = (self.normal_image_index + 1) % len(self.normal_iamge_list)
else:
if self.bomb_image_index == len(self.bomb_image_list):
time.sleep(0.3)
exit(0)
# 绘制英雄机爆炸图片
hero_bomb_image = get_pic(self.bomb_image_list[self.bomb_image_index])
self.screen.blit(hero_bomb_image, (self.x, self.y))
self.bomb_image_index += 1
time.sleep(0.3)
def deal_event(self):
'''事件检测'''
event_list = pygame.event.get()
for event in event_list:
if event.type == pygame.QUIT: # 退出事件
exit(0)
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
self.x = self.x - 5 if self.x >= 5 else 0
elif event.key == pygame.K_RIGHT:
self.x = self.x + 5 if self.x <= 375 else 380
elif event.key == pygame.K_DOWN: # 向下
self.y = self.y + 5 if self.y <= 521 else 526
elif event.key == pygame.K_UP: # 向上
self.y = self.y - 5 if self.y >= 5 else 0
elif event.key == pygame.K_SPACE:
one_bullet = HeroBullet(self.x + 50 - 11, self.y - 22, self.screen)
self.bullet_list.append(one_bullet)
# 绘制子弹
for bullet in self.bullet_list:
bullet.draw()
self.bullet_list.remove(bullet) if bullet.y < 0 else ''
def check_collide(self, bullet_list):
'''
碰撞检测
:param bullet_list: 敌机子弹列表
:return:
'''
# 定义英雄的rect
hero_rect = pygame.rect.Rect(self.x, self.y, 100, 124)
print(hero_rect)
for bullet in bullet_list: # 遍历敌机子弹列表
enemy_bullet_rect = pygame.rect.Rect(bullet.x, bullet.y, 14, 143)
if enemy_bullet_rect.colliderect(hero_rect):
print('英雄机爆炸。。。。')
self.isBomb = True # 将英雄机爆炸条件置为真
bullet_list.remove(bullet) # 爆炸时移除敌机子弹
class EnemyPlnane(BasePlane):
'''敌机类'''
def __init__(self, x, y, screen):
super().__init__(x,y,screen)
self.normal_image_list = ['enemy-3.gif', 'enemy2_n2.png']
self.bomb_image_list = ['enemy2_down1.png', 'enemy2_down2.png', 'enemy2_down3.png', 'enemy2_down4.png',
'enemy2_down5.png', 'enemy2_down6.png']
self.direct = '左'
def draw(self):
'''绘制敌机'''
if self.isBomb == False:
# 绘制未爆炸的图片
pic = get_pic(self.normal_image_list[self.normal_image_index])
self.screen.blit(pic, (self.x, self.y))
self.normal_image_index = (self.normal_image_index + 1) % len(self.normal_image_list)
else:
if self.bomb_image_index == len(self.bomb_image_list):
time.sleep(0.3)
exit(0)
# 绘制敌机爆炸图片
enemy_bomb_img = get_pic(self.bomb_image_list[self.bomb_image_index])
self.screen.blit(enemy_bomb_img,(self.x,self.y))
self.bomb_image_index += 1
time.sleep(0.3)
# 控制敌机移动
self.move()
# 调用开火功能
self.fire()
def move(self):
'''控制敌机移动'''
if self.direct =='左':
self.x -= 5
if self.x <=0:
self.direct = '右'
if self.direct == '右':
self.x +=5
if self.x >= 480-165:
self.direct = '左'
def fire(self):
'''敌机开火'''
# 产生随机数
x = random.randint(1,100)
if x ==4 or x==78:
# 实例化一个敌机子弹,
one_bullet = EnemyBullet(self.x+165 // 2 - 14 // 2,self.y+246,self.screen)
self.bullet_list.append(one_bullet)
for bullet in self.bullet_list:
bullet.draw()
# 让子弹在最下面的饿时候消失
self.bullet_list.remove(bullet) if bullet.y>650 - 150 else''
def check_collide(self,bullet_list):
'''
碰撞检测
:param bullet_list: 英雄机子弹列表
:return:
'''
# 定义敌机rect
enemy_rect = pygame.rect.Rect(self.x,self.y,165,246)
for bullet in bullet_list:
hero_bullet_rect = pygame.rect.Rect(bullet.x,bullet.y,22,22)
if hero_bullet_rect.colliderect(enemy_rect):
print('敌机爆炸了。。。。')
self.isBomb = True
# 移除英雄机子弹
bullet_list.remove(bullet)
def main():
# 初始化游戏
pygame.init()
# 设置背景
screen = pygame.display.set_mode((480, 650), 0, 32)
# 设置标题
pygame.display.set_caption('飞机大战')
# 设置图标
pygame.display.set_icon(get_pic('icon72x72.png'))
# 实例化英雄机对象
hero_plane = HeroPlane(190, 526, screen)
# 实例化敌机对象
enemy_plane = EnemyPlnane(480 // 2 - 165 // 2, 0, screen)
# 设置按键灵敏度
pygame.key.set_repeat(20, 30)
while True:
# 绘制背景图片
bg = get_pic('background.png')
screen.blit(bg, (0, 0))
# 敌机碰撞检测
enemy_plane.check_collide(hero_plane.bullet_list)
# 英雄节碰撞检测
hero_plane.check_collide(enemy_plane.bullet_list)
# 绘制战机精灵
hero_plane.draw()
# 绘制敌机精灵
enemy_plane.draw()
hero_plane.deal_event() # 事件检测
pygame.display.update()
if __name__ == '__main__':
main()
赞 (0)