py飞机大战

飞机大战

学习来自:B站“麦叔编程”

--兴趣使人快乐!


源码

# coding:utf-8
'打飞机ybt'
import pygame
import random
import math

from time import sleep
# 初始化,必选项
pygame.init()

#设置窗口大小
win= pygame.display.set_mode((800,600)) #宽高

#设置标题
pygame.display.set_caption('ybt打飞机')

#加载图片
icon= pygame.image.load('ufo.png')

#设置图标
pygame.display.set_icon(icon)

#加载背景图片
bg= pygame.image.load('bg.png')


# #添加分数和设置字体
score=0
#freesansbold.ttf是pygame自带的字体,32是字体大小
font = pygame.font.Font('freesansbold.ttf',32)
def show_score():
    s = f"score: {score}" #f字符串表示可以直接嵌入变量
    # s,是输入的文本;True表示要是24位的颜色,(0,255,0)是三原色坐标
    #font.render字体颜色设置
    score_render = font.render(s,True,(0,255,0))
    #放入背景位置
    win.blit(score_render,(10,10))

#添加游戏结束字体
#游戏结束
over=False
font1 = pygame.font.Font('freesansbold.ttf',64)
def gameOver():
    if over:
        gameover = font1.render("Game Over",True,(0,255,0))
        win.blit(gameover,(200,250))



#添加背景音乐
# pygame.mixer.music.load('bg.wav') #加载音乐
# pygame.mixer.music.play(-1) #单曲循环
#添加击中音效
hits = pygame.mixer.Sound('exp.wav')



#引入飞机图片
fly=pygame.image.load('player.png')
#设置飞机初始坐标
flyx = 400
flyy = 500
#设置飞机迈步
flyStep=0


#定义敌人类
class Enemy(object):
    def __init__(self):
        self.img =pygame.image.load('enemy.png')
        self.x = random.randint(100, 700)
        self.y= random.randint(70, 250)
        self.step = random.randint(1,4)
    #敌人被击中后恢复位置,其实就是随机又放回去了
    def reset(self):
        self.x = random.randint(100, 700)
        self.y= random.randint(70, 250)

enemies = []    #设置敌人类收集列表
for i in range(5):
    enemies.append(Enemy())



#敌人方法
def enemyM():
    global over
    for i in enemies:
        win.blit(i.img,(i.x,i.y))
        i.x += i.step
        if (i.x > 736 or i.x <0):
            i.step*=-1   #*-1改变增量正负号
            i.y+=40
            if i.y >=450:
                over =True
                print ("game over")
                enemies.clear() #列表清空敌人



#计算飞机到敌人的距离;勾股定理#欧几里得距离
def distance(bx, by, ex, ey):
    a = bx - ex
    b = by - ey
    return math.sqrt(a*a + b*b) #sqrt方法开根号,当然也可以**0.5  #不太明天为什么计算斜边(先记住方法即可)


#定义子弹类
class Bullet(object):
    def __init__(self):
        self.img = pygame.image.load('bullet.png')
        self.x = flyx +16  #子弹挪到飞机中间
        self.y = flyy + 10  #子弹挪到飞机上方
        self.step = 30
    #击中
    def hit(self):
        global score
        for i in enemies:
            if distance(self.x,self.y,i.x,i.y) < 30:#判断子弹到敌人的距离小于30
                    #击中后移除敌人
                hits.play()  #播放击中音乐
                bullets.remove(self)
                i.reset()   #重置敌人位置
                score+=1
                break


bullets = [] #子弹类收集列表
#显示子弹方法
def showBullets():
    for b in bullets:
        win.blit(b.img,(b.x,b.y))
        b.hit() #尝试是否击中
        b.y -=b.step
        #如果出界就移除
        if b.y <0:
            bullets.remove(b)


#设置飞机左右临界值和移动增减量
def flyM():
    global flyx     #设置左右宽度移动为全局变量
    flyx+=flyStep
    #设置右边界
    if flyx > 736:  #飞机大小占64
        flyx=736
    #设置左边界
    if flyx < 0:
        flyx = 0


#执行主程序
while True:
    win.blit(bg,(0,0))  #引入背景图,并设置坐标(打开的界面右上角是0,0坐标),
            # 必须放到其他图片前边,要不然背景图会被覆盖
    show_score() #放入分数方法
    for i in pygame.event.get():  # 返回事件,如:点击鼠标,关闭游戏页面等
        if i.type == pygame.QUIT:  # if 事件类型==pygame.QUIT游戏退出
            break
        # pygame.KEYDOWN  通过键盘事件控制
        if i.type == pygame.KEYDOWN:  # 按键盘就移动
            if i.key == pygame.K_RIGHT:  # RIGHT向右的方向键
                flyStep = 3
            elif i.key == pygame.K_LEFT:  # LEFT 向右方向键
                flyStep = -3
            elif i.key == pygame.K_SPACE:   #空格
                print ('子弹发射')
                #子弹类列表实例化
                b = bullets.append(Bullet())

        if i.type == pygame.KEYUP:  # 不按就不动
            flyStep = 0

    #引入飞机图,设置飞机初始宽高
    win.blit(fly,(flyx,flyy))
    flyM()
    enemyM()
    showBullets()
    gameOver()
    pygame.display.update() #界面更新,必须放到最后


总结

坐标系总结

(0,0)原点
|——————————————————————————————————————————————————800
|
|
|	
|
|
|
|
|				
|——————————————————————————————————————————————————(800,600)
600




难点问题
遗留问题咨询的打飞机游戏问题:
1.为什么要使用斜边判断飞机与怪物的距离
	欧式距离判断
2.png大小使用什么工具查看
	ps工具
posted @ 2022-09-20 18:28  ybt&kexiao  阅读(29)  评论(0编辑  收藏  举报