前要:本章节含有两个版本的《飞机大战》,本文主要讲面向对象版本,两个版本的源码连接已给出。
————————————————面向对象版本———————————————
详细注释已经给出,并且已经将类全部封装:
import os,time,random,pygame
from pygame.locals import *
def getPath(path):# 创建一个传入路径的函数,返回路径,然后避免以后传东西的时候路径太长
return os.path.join("C:\\Users\\Administrator\Desktop\IT研究院-Python\\New_Stydy\\img\\", path)
#飞机和子弹共同类
class Father():
def __init__(self, x, y, windows):
self.x = x
self.y = y
self.windows = windows
#子弹父类
class BiuFather(Father):
def draw(self):
self.windows.blit(self.image, (self.x, self.y))
self.move()
#飞机父类
class Plane(Father):
def __init__(self, x, y, windows):
super().__init__(x,y,windows)
self.normalImageListIndex = 0
self.bombImageIndex = 0
self.isBomb = False
self.biuList = []
def draw(self):
if not self.isBomb:
image = pygame.image.load(getPath(self.normalImageList[self.normalImageListIndex]))
self.normalImageListIndex = (self.normalImageListIndex + 1) % len(self.normalImageList) # 切换飞机显示图片
self.windows.blit(image, (self.x, self.y))
else:
# 敌方飞机爆炸
if len(self.bombImageList) == self.bombImageIndex:
time.sleep(0.5)
exit(0)
image = pygame.image.load(getPath(self.bombImageList[self.bombImageIndex]))
self.bombImageIndex += 1
self.windows.blit(image, (self.x, self.y))
time.sleep(0.3)
#我方子弹
class Biu(BiuFather):
def __init__(self, x, y, windows):
super().__init__(x, y, windows)
self.image = pygame.image.load(getPath("bullet.png"))
def move(self):
self.y -= 5
#敌方子弹
class EnemyBiu(BiuFather):
def __init__(self, x, y, windows):
super().__init__(x, y, windows)
self.image = pygame.image.load(getPath("bullet1.png"))
def move(self):
self.y += 5 # 敌机子弹速度
class EnemyPlane(Plane):
def __init__(self, x, y, windows):
self.normalImageList = ['enemy1.png']
self.bombImageList = ['enemy1_down1.png', 'enemy1_down2.png', 'enemy1_down3.png', 'enemy1_down4.png'] # 敌机爆炸图片
super().__init__(x, y, windows)
self.direct = "左"
def draw(self):
super().draw()
if not self.isBomb:
self.move()
self.fire()
for zd in self.biuList:
zd.draw()
def move(self):
if self.direct == '左':
self.x -= 2
if self.x <= 0:
self.direct = " 右"
else:
self.x += 2
if self.x >= 480 - 69:
self.direct = "左"
def fire(self):
x = random.randint(1, 100)
if x == 3:
zd = EnemyBiu(self.x + 69 // 2 - 9 // 2, self.y + 89, self.windows)
self.biuList.append(zd)
def pzjc(self, bList):
eRect = Rect(self.x, self.y, 69, 89)
for zd in bList:
zdRect = Rect(zd.x, zd.y, 22, 22)
if zdRect.colliderect(eRect):
self.isBomb = True
bList.remove(zd)
class HeroPlane(Plane):
def __init__(self, x, y, windows):
self.normalImageList = ['hero1.png', 'hero2.png']
self.bombImageList = ['hero_blowup_n1.png', 'hero_blowup_n2.png', 'hero_blowup_n3.png',
'hero_blowup_n4.png'] # 我方飞机机爆炸图片
super().__init__(x, y, windows)
def draw(self):
super().draw()
for zd in self.biuList:
zd.draw()
self.biuList.remove(zd) if zd.y < 0 else '' # 子弹越界删除子弹
# 我方飞机碰撞检测
def pzjc(self, bList):
eRect = Rect(self.x, self.y, 100, 124)
for zd in bList:
zdRect = Rect(zd.x, zd.y, 9, 21)
if zdRect.colliderect(eRect):
self.isBomb = True
bList.remove(zd)
def dealEvent(self, eventList):
# 事件处理
for event in eventList:
if event.type == QUIT:
exit(0)
elif 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 - 100 - 5 else 480 - 100
elif event.key == K_SPACE:
zd = Biu(self.x + 100 // 2 - 22 // 2, self.y - 22, self.windows)
self.biuList.append(zd)
windows = pygame.display.set_mode((480, 652), 0, 32)
pygame.display.set_caption("飞机大战")
backGround = pygame.image.load(getPath("background.png"))
icon = pygame.image.load(getPath("icon72x72.png"))
pygame.display.set_icon(icon)
pygame.key.set_repeat(50, 10) # 第一个参数是键盘按下30ms后开始反应,第二个参数是按下30ms为抬起再触发一次新的按键事件
heroPlane = HeroPlane(480 // 2 - 100 // 2, 652 - 124, windows) # 贴上我方飞机图片
enemyPlane = EnemyPlane(480 // 2 - 69 // 2, 0, windows) # 贴上敌方飞机图片
while True:
windows.blit(backGround, (0, 0))
heroPlane.draw()
enemyPlane.draw()
enemyPlane.pzjc(heroPlane.biuList)
heroPlane.pzjc(enemyPlane.biuList)
heroPlane.dealEvent(pygame.event.get())
pygame.display.update()
————————————————面向过程版本——————————————
import pygame
from pygame.locals import *
import random, time
class Biu(): # 我方子弹类
def __init__(self, x, y, wind):
self.x = x
self.y = y
self.wind = wind
self.pic = pygame.image.load(r'C:\Users\Administrator\Desktop\img\篮球.png')
def draw(self):
self.wind.blit(self.pic, (self.x, self.y))
self.move()
def move(self):
self.y -= 3
class DJBiu(): # 敌方子弹类
def __init__(self, x, y, wind):
self.x = x
self.y = y
self.wind = wind
self.pic = pygame.image.load(r"C:\Users\Administrator\Desktop\img\bullet1.png")
def draw(self):
self.wind.blit(self.pic, (self.x, self.y))
self.move()
def move(self):
self.y += 0.5
wind = pygame.display.set_mode((480, 500), 0, 32) # (480,652)是屏幕分辨率,后边的数字是专业数字
background = pygame.image.load(r'C:\Users\Administrator\Desktop\img\背景图.jpg') # 定义一张背景图
icon = pygame.image.load(r'C:\Users\Administrator\Desktop\img\1.png') # 定义一张游戏图标
# ----------------------------------------定义我方飞机图片--------------------------------
heroindex = 0
heroPlane1 = pygame.image.load(r'C:\Users\Administrator\Desktop\img\hero1.png') # 定义我方飞机1
heroPlane2 = pygame.image.load(r'C:\Users\Administrator\Desktop\img\hero2.png') # 定义我方飞机2
heroboomlist = [r'C:\Users\Administrator\Desktop\img\hero_blowup_n1.png',
r'C:\Users\Administrator\Desktop\img\hero_blowup_n2.png',
r'C:\Users\Administrator\Desktop\img\hero_blowup_n3.png',
r'C:\Users\Administrator\Desktop\img\hero_blowup_n4.png']
heroboomindex = 0
heroPlaneisBoom = False
hero_x = (480 - 100) // 2 # 我方飞机横坐标
hero_y = 500 - 124 # 我方飞机纵坐标
# -------------------------------------------定义敌方飞机--------------------------------
dfPlane1 = pygame.image.load(r'C:\Users\Administrator\Desktop\img\enemy1.png') # 定义敌方飞机1
djboomlist = [r'C:\Users\Administrator\Desktop\img\enemy1_down1.png',
r'C:\Users\Administrator\Desktop\img\enemy1_down2.png',
r'C:\Users\Administrator\Desktop\img\enemy1_down3.png',
r'C:\Users\Administrator\Desktop\img\enemy1_down4.png']
heroBiuList = [] # 子弹列表
djBiuList = [] # 敌方子弹列表
dfPlane1_x = (480 - 69) // 2
# 敌机初始横坐标
df_fx = '左' # 设置敌人的飞机方向
# --------------------------------------定义图标和游戏名字----------------------------
pygame.display.set_caption('篮球大战') # 设置左上角游戏名字
pygame.display.set_icon(icon) # 将游戏图标加载至左上角
pygame.key.set_repeat(30, 30) # 第一个参数,自己按下键盘的反应时间,第二个参数如果30毫秒没抬起,按照连续按下为止
zd = None
# ============================游戏运行时内部============================================
while True:
wind.blit(background, (0, 0)) # 将背景图从(0,0)开始贴背景图
# ---------贴我方飞机图,定义的heroindex为了让飞机实现喷气(两张图切换)--------
if heroPlaneisBoom == False:
if heroindex == 0:
wind.blit(heroPlane1, (hero_x, hero_y)) # 贴飞机
heroindex = 1
else:
wind.blit(heroPlane2, (hero_x, hero_y)) # 贴飞机
heroindex = 0
else:
if heroboomindex == len(heroboomlist):
time.sleep(0.7)
exit(0)
pic = pygame.image.load(heroboomlist[heroboomindex])
wind.blit(pic, (hero_x, hero_y))
heroboomindex += 1
time.sleep(0.5)
wind.blit(dfPlane1, (dfPlane1_x, 0))
# ------------我方子弹发射与敌机爆炸----------------
df_Rect = Rect(dfPlane1_x, 0, 69, 89)
for zd in heroBiuList:
zd.draw()
zdRect = Rect(zd.x, zd.y, 22, 22)
if df_Rect.colliderect(zdRect): # 子弹与敌机相交爆炸
print('BOOM!')
heroBiuList.remove(zd)
else:
heroBiuList.remove(zd) if zd.y < 0 else '' # 如果子弹一下按的多了,会重头开始,所以加这句话会解决
# --------敌方子弹发射撞我方飞机爆炸------------------
hero_Rect = Rect(hero_x, hero_y, 100, 124)
for zd in djBiuList:
zd.draw()
zdRect = Rect(zd.x, zd.y, 9, 21)
if hero_Rect.colliderect(zdRect):
# print('爆炸')
heroPlaneisBoom = True
djBiuList.remove(zd)
else:
djBiuList.remove(zd) if zd.y < 0 else ''
# -----------------------------------我方发射子弹和控制移动---------------------------------------
for event in pygame.event.get(): # 循环获取时间,尤其是键盘或者鼠标
if event.type == QUIT: # 如果事件是退出,则触发退出
print('退出游戏!')
exit()
elif event.type == KEYDOWN:
if event.key == K_LEFT:
hero_x = hero_x - 12 if hero_x > 0 else 0
elif event.key == K_RIGHT:
hero_x = hero_x + 12 if hero_x < 480 - 100 - 12 else 480 - 100
elif event.key == K_SPACE:
zd = Biu(hero_x + 100 // 2 - 46 // 2, hero_y - 46, wind)
heroBiuList.append(zd)
# ---------------------------------------敌方飞机自由移动,撞墙会回头--------------------------
if df_fx == '左':
dfPlane1_x -= 1
if dfPlane1_x <= 0:
df_fx = '右'
else:
dfPlane1_x += 1
if dfPlane1_x >= 480 - 69:
df_fx = '左'
# ---------# 敌方随机发射子弹---------------------
h = random.randint(0, 300)
if h == 20:
# 敌方随机发射子弹
zd = DJBiu(dfPlane1_x + 69 // 2 - 9 // 2, 89, wind)
djBiuList.append(zd)
pygame.display.update() # 更新