为了能在游戏中正常显示中文,可以在当前代码目录下新建一个fonts文件夹,放入支持中文的字体文件
fontname='s’设置字体
代码仅供参考
import pgzrun
import random
WIDTH=480
HEIGHT=700
TITLE='飞机大战'
sounds.game_music.play(-1)#新建一个sounds文件,复制四个音乐(wav,ogg),括号内可以写重复次数,无数次填-1
background1=Actor('background')#背景
background1.x=480/2
background1.y=852/2
background2=Actor('background')
background2.x=480/2
background2.y=-852/2
bullet = Actor('bullet') # 子弹
bullet.x = 240
bullet.y = -HEIGHT/2 # 初始位置
hero = Actor('hero') # 主战机
hero.x = 240
hero.y = HEIGHT*2/3 # 初始定位
enemy = Actor('enemy') # 敌机
enemy.x = random.randint(0, WIDTH) # 初始位置
enemy.y = 0
#游戏失败的判定
isLoose=False
score = 0
def draw():
background1.draw()#全部绘制出来
background2.draw()
hero.draw()
bullet.draw()
enemy.draw()
screen.draw.text("得分:"+str(score),(200,HEIGHT-500),fontsize=30,fontname='s',color='black')
if isLoose:
screen.draw.text("游戏失败",(200,400),fontsize=40,fontname='s',color='black')
def update():#背景的移动,子弹的移动,敌机的出现,碰撞的消失,得分,失败的判定
global score,isLoose
if isLoose:
return#不进行下面操作
background1.y=background1.y+1#背景移动
if background1.y>852/2+852:
background1.y=-426
background2.y=background2.y+1
if background2.y>852/2+852:
background2.y=-426
if bullet.y>0:
bullet.y=bullet.y-10#子弹的移动
enemy.y+=3 #敌机自动下落
if enemy.y>HEIGHT:#敌机落到底部后从顶部随机出现
enemy.x=random.randint(0,WIDTH)
enemy.y=0
if bullet.colliderect(enemy):#敌机被击中后
sounds.got_enemy.play()
score+=1
enemy.x=random.randint(0,WIDTH)
enemy.y=0#被消灭的敌机的出现
if hero.colliderect(enemy):#失败的判定
sounds.explode.play()#播放音效
isLoose=True#判定游戏
hero.image='hero_blowup'#更换游戏图片
def on_mouse_move(pos,rel,buttons):#飞机的位置
if isLoose:
return#不做,跳出
hero.x=pos[0]
hero.y=pos[1]
def on_mouse_down():#子弹的出现
bullet.y = hero.y-70
bullet.x = hero.x
sounds.gun.play()
pgzrun.go()