import pygame
import sys
# back 返回,后面
# ground 地面
# 哪一行代码确定战机的位置,27行,用坐标确定战机位置
# 飞机的类
# 飞机名字, 飞机的位置,窗口,图片
class feiji():
def __init__(self, ck):
self.name = "hero"
self.x = 200
self.y = 400
self.chuangkou = ck
self.picture = pygame.image.load("hero1.png")
self.zidan_ku = []
# 把飞机放到屏幕上
def show(self):
self.chuangkou.blit(self.picture, (self.x, self.y))
# 如果有子弹,就放上窗口
print(len(self.zidan_ku))
for dan_ge_zidan in self.zidan_ku:
dan_ge_zidan.show()
# 飞机的子弹移动
dan_ge_zidan.move__fd()
if dan_ge_zidan.yuejie():
self.zidan_ku.remove(dan_ge_zidan)
# move 向左移动
def move_left(self):
self.x -= 20
if self.x < -25:
self.x = 5
# 向右移动
def move_right(self):
self.x += 20
if self.x>=330:
self.x=330
# 发射子弹的函数
def fashe(self):
# 新建子弹对象保存到zidan1变量到列表里去
self.zidan_ku.append(zidan(self.chuangkou,self.x,self.y))
self.zidan_ku.append(zidan1(self.chuangkou,self.x,self.y))
self.zidan_ku.append(zidan2(self.chuangkou, self.x, self.y))
# 子弹的类
# 属性:子弹的位置 ,子弹窗口,子弹图片,伤害,子弹名字,子弹数量,
# 方法:子弹的show展示,move移动
class zidan():
def __init__(self,ck,x,y):
self.x = x+48
self.y = y-10
self.window =ck
self.picture = pygame.image.load("zidan1.gif")
def show(self):
# print("子弹的y坐标是%d"%self.y)
self.window.blit(self.picture,(self.x,self.y))
def move__fd(self):
self.y = self.y-1
def yuejie(self):
if self.y<-100:
return True
else:
return False
class zidan1():
def __init__(self,ck,x,y):
self.x = x+14
self.y = y+25
self.window =ck
self.picture = pygame.image.load("zidan2.png")
def show(self):
# print("子弹的y坐标是%d"%self.y)
self.window.blit(self.picture,(self.x,self.y))
def move__fd(self):
self.y = self.y-10
def yuejie(self):
if self.y<-100:
return True
else:
return False
class zidan2():
def __init__(self,ck,x,y):
self.x = x+80
self.y = y+25
self.window =ck
self.picture = pygame.image.load("zidan3.png")
def show(self):
# print("子弹的y坐标是%d"%self.y)
self.window.blit(self.picture,(self.x,self.y))
def move__fd(self):
self.y = self.y-10
# 判断是否越界的函数
# 越界返回值 True
def yuejie(self):
if self.y<-100:
return True
else:
return False
# 控制飞机
def key_kong(hero):
for shi_jian in pygame.event.get():
# type 类型 QUIT 退出
if shi_jian.type == pygame.QUIT:
pygame.quit() # 退出游戏
sys.exit() # 系统文件的退出
# 判断是否按了键 KEY
elif shi_jian.type == pygame.KEYDOWN:
# 检测电脑是否按了a键,向左移动
if shi_jian.key == pygame.K_a or shi_jian.key == pygame.K_LEFT:
hero.move_left()
if shi_jian.key == pygame.K_d or shi_jian.key == pygame.K_RIGHT:
hero.move_right()
if shi_jian.key == pygame.K_j:
hero.fashe()
# 按键发射子弹,判断然后发射子弹
# 1。初始化
def zhu():
pygame.init()
# 2。设置一个窗口
chuangkou = pygame.display.set_mode((400, 700))
# 3。设置一个标题
pygame.display.set_caption("飞机大战")
# 6. 导入图片 image图像 load 加载
bei_jing = pygame.image.load("background.png")
# 创建一个飞机对象
feiji1 = feiji(chuangkou)
# 5。循环
while True:
# 把背景放上去
chuangkou.blit(bei_jing, (0, 0))
# 把飞机和相关元素放上窗口去
feiji1.show()
# 控制飞机
key_kong(feiji1)
# 4.刷新
pygame.display.update()
# main主要的函数
if __name__ == '__main__':
zhu()
来源:CSDN
作者:少儿编程侯老师
链接:https://blog.csdn.net/houlaos/article/details/104166391