前提条件:
需要安装pygame,pgzero,numpy(windows:1.19.3)
功能:
1.玩家飞机子弹连发
2.初始化三架敌机,随机出现
3.特效:背景音乐,子弹发射音乐,子弹击中敌机的声音,玩家飞机爆炸的声音
4.统计玩家击中敌机的数量,每击中一架敌机分数加1,显示分数
5.玩家飞机爆炸后游戏结束
附:
代码中涉及到的素材来自异步社区:《Python游戏趣味编程》一书中提供的素材:https://www.epubit.com/bookDetails?id=UB72096d97d6149
以下是代码:
import pgzrun
import random
TITLE = '飞机大战'
WIDTH = 480
HEIGHT = 700
# 背景图片1
background1 = Actor('background')
background1.x = WIDTH / 2
background1.y = 852 / 2
# 背景图片2
background2 = Actor('background')
background2.x = WIDTH / 2
background2.y = -852 / 2
# 玩家
hero = Actor('hero')
hero.x = WIDTH / 2
hero.y = HEIGHT * 2 / 3
# 存储敌机的信息
enemies = []
# 初始化三架敌机,依次出现
for i in range(3):
# 敌机
enemy = Actor('enemy')
enemy.x = random.randint(80, 320)
enemy.y = -i * 100
enemies.append(enemy)
# 子弹
bullet = Actor('bullet')
bullet.x = WIDTH / 2
bullet.y = -HEIGHT
# 存储发射的子弹
bullets = [bullet]
# 移动速度
speed_enemy = 3
speed_bullet = 10
# 分数
score = 0
# 游戏是否失败
isLoose = False
# 加载背景音乐
sounds.game_music.play(-1)
def draw():
# 绘制背景
background1.draw()
background2.draw()
# 绘制玩家
hero.draw()
# 绘制子弹
for bt in bullets:
bt.draw()
# 绘制敌机
for emy in enemies:
emy.draw()
# 显示分数
screen.draw.text('当前得分: ' + str(score), (160, HEIGHT - 50), fontsize=30, fontname='s', color='green')
# 失败后输出信息
if isLoose:
screen.draw.text('游戏失败', (150, HEIGHT / 2), fontsize=50, fontname='s', color='red')
def update():
global score, isLoose
if not isLoose:
# 游戏失败的判定
for emy in enemies:
if hero.colliderect(emy):
isLoose = True
# 更换敌机的图片
hero.image = 'hero_blowup'
# 播放玩家飞机爆炸的声音
sounds.explode.play()
# 判断是否击中敌机
for bt in bullets:
for emy in enemies:
if bt.colliderect(emy):
# 击中敌机后,敌机位置重置,并将分数加1,隐藏子弹
emy.y = 0
emy.x = random.randint(80, 320)
score += 1
bt.y = -HEIGHT
# 加载子弹击中敌机的音乐
sounds.got_enemy.play()
# 背景图片
if background1.y > 852 / 2 + 852:
background1.y = -852 / 2
if background2.y > 852 / 2 + 852:
background2.y = -852 / 2
# 背景移动
background1.y += 1
background2.y += 1
# 敌机移动
for emy in enemies:
emy.y += speed_enemy
# 子弹移动
for bt in bullets:
if bt.y > -HEIGHT:
bt.y -= speed_bullet
# 当敌机移出视野后,重置敌机的位置
for emy in enemies:
if emy.y > HEIGHT:
emy.y = 0
emy.x = random.randint(80, 320)
# 玩家飞机跟随鼠标移动
def on_mouse_move(pos, rel, buttons):
if not isLoose:
hero.x = pos[0] # 玩家飞机的x坐标为鼠标的x坐标
hero.y = pos[1] # 玩家飞机的y坐标为鼠标的y坐标
# 鼠标按下发射子弹
def on_mouse_down():
if not isLoose:
# 播放发射子弹的背景音乐
sounds.gun.play()
# 生成新的子弹,并将子弹放到飞机的正上方
new_bullet = Actor('bullet')
new_bullet.x = hero.x
new_bullet.y = hero.y - 40
bullets.append(new_bullet)
# 执行游戏
pgzrun.go()