效果展示:
正文:
一、环境安装
- 本文是写的游戏代码,基于Pygame的源码项目,这里是自己写的飞机大战的1.0版本,比较简陋。
- 准备:Python3、Pycharm、pygame模块以及自带的部分模块。
pip install -i https://pypi.douban.com/simple/ pygame
二、我方飞机
def main():
global is_hit
global nums
screen = pygame.display.set_mode((480, 852), 0, 32)
background = pygame.image.load("./feiji/background.png")
# 创建飞机
hero = HeroPlane(screen)
enermy_plane = EnermyPlane(screen)
while True:
global hero_nums
global enermy_nums
# 显示背景
screen.blit(background, (0, 0))
# 显示我方飞机
hero.display()
# 测试是否被子弹击中
hero.test(enermy_plane.bullets)
if hero.is_hit:
hero_nums += 1
if hero_nums == 10:
hero.image = pygame.image.load("./feiji/hero_blowup_n1.png")
elif hero_nums == 20:
hero.image = pygame.image.load("./feiji/hero_blowup_n2.png")
elif hero_nums == 30:
hero.image = pygame.image.load("./feiji/hero_blowup_n3.png")
elif hero_nums == 40:
hero.image = pygame.image.load("./feiji/hero_blowup_n4.png")
elif hero_nums > 50:
break
三、敌方飞机
# 显示敌飞机
enermy_plane.display()
enermy_plane.test(hero.bullets)
if enermy_plane.is_hit:
enermy_nums += 1
if enermy_nums == 10:
enermy_plane.image = pygame.image.load("./feiji/enemy0_down1.png")
elif enermy_nums == 20:
enermy_plane.image = pygame.image.load("./feiji/enemy0_down2.png")
elif enermy_nums == 30:
enermy_plane.image = pygame.image.load("./feiji/enemy0_down3.png")
elif enermy_nums == 40:
enermy_plane.image = pygame.image.load("./feiji/enemy0_down4.png")
elif enermy_nums > 50:
enermy_plane = EnermyPlane(screen)
enermy_nums = 0
else:
enermy_plane.move()
enermy_plane.fire()
# 控制飞机左右
key_control(hero)
# 刷新屏幕
pygame.display.update()
# 程序休眠0.01秒
time.sleep(0.01)
四、控制键盘移动
def key_control(hero):
for event in pygame.event.get():
if event.type == QUIT:
print("exit")
exit()
elif event.type == KEYDOWN:
if event.key == K_a or event.key == K_LEFT:
hero.move_left()
print("left")
elif event.key == K_d or event.key == K_RIGHT:
hero.move_right()
print("right")
elif event.key == K_SPACE:
hero.fire()
print("space")
五、检测子弹碰撞
class BasePlane(object):
def __init__(self, screen, x, y, image):
self.x = x
self.y = y
self.screen = screen
self.image = pygame.image.load(image)
self.is_hit = False # 此标志用来表示飞机是否被击中了
self.bullets = []
def test(self, bullets):
for bullet in bullets:
if self.x < bullet.x < self.x + self.image.get_width() and \
self.y < bullet.y < self.y + self.image.get_height():
self.is_hit = True
# 检测子弹碰撞
for item in self.bullets:
for bullet in bullets:
if item.x < bullet.x < item.x + item.image.get_width() and \
item.y < bullet.y < item.y + item.image.get_height():
item.is_hit = True
bullet.is_hit = True
成品效果图:
最后:
如果你觉得文章还不错,请大家 点赞、分享、留言 下,因为这将是我持续输出更多优质文章的最强动力!
最后这里免费分享给大家一份Python全台学习资料,包含视频、源码。课件,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。
编程资料、学习路线图、源代码、软件安装包等!【点击这里】领取!
① Python所有方向的学习路线图
,清楚各个方向要学什么东西
② 100多节Python课程视频
,涵盖必备基础、爬虫和数据分析
③ 100多个Python实战案例
,学习不再是只会理论
④ 华为出品独家Python漫画教程
,手机也能学习
⑤ 历年互联网企业Python面试真题
,复习时非常方便