python-飞机大战项目

import math
import sys
import copy
import random as r
import pygame
import os

#加载图片
startImages=[
    pygame.image.load('image/background.png'),
    pygame.image.load('image/bjair.png'),
    pygame.image.load('image/name.png'),
    pygame.image.load('image/buttonstart.png'),
    pygame.image.load('image/bj.png'),
    pygame.image.load('image/img_bg_level_1.jpg'),
    pygame.image.load('image/img_bg_level_4.png'),
    pygame.image.load('image/buttonout.png'),
    pygame.image.load('image/buttonread.png')
    ]
startBottomImages=[
    pygame.image.load('image/game_loading1.png'),
    pygame.image.load('image/game_loading2.png'),
    pygame.image.load('image/game_loading3.png'),
    # pygame.image.load('image/airxiao.png'),
    # pygame.image.load('image/airxiao.png'),
    # pygame.image.load('image/airxiao.png'),
    ]



class StartPanel:
    isInside=False
    outisInside=False
    readisInside=False


    def __init__(self,screen,startImages=startImages,startBottomImages=startBottomImages):
        '''
        :param startImages: 开始背景图
        :param startBottomImages: 开始下方三张动图
        :param screen: 渲染的屏幕
        '''
        self.startImages=startImages
        self.startBottomImages=startBottomImages
        self.screen=screen

        self.index=0

        self.bottomImgIndex=0
        self.bottomImgAddIndex=0



    def Distplay(self):
        self.index+=0.08
        #背景图
        self.screen.blit(self.startImages[4], (0, 0))
        #self.screen.blit(pygame.transform.scale(self.startImages[1],(480,480)),(0,150))

        #文字动图
        self.screen.blit(self.startImages[2],(25,10+40*math.sin(self.index)))
        #按钮
        btn=self.screen.blit(pygame.transform.scale(self.startImages[3],(90,90)),(192,300))
        outbtn = self.screen.blit(pygame.transform.scale(self.startImages[7], (90, 90)), (192, 400))
        readbtn = self.screen.blit(pygame.transform.scale(self.startImages[8], (90, 90)), (192, 500))
        #print(btn)
        #鼠标是否在 按钮上方
        StartPanel.isInside=btn.collidepoint(pygame.mouse.get_pos())
        StartPanel.outisInside = outbtn.collidepoint(pygame.mouse.get_pos())
        StartPanel.readisInside = readbtn.collidepoint(pygame.mouse.get_pos())

        #三张动图
        self.bottomImgAddIndex+=1
        if self.bottomImgAddIndex==100:
            self.bottomImgAddIndex=0
        if self.bottomImgAddIndex%17==0:
            self.bottomImgIndex+=1
            if self.bottomImgIndex==3:
                self.bottomImgIndex=0
        self.screen.blit(self.startBottomImages[self.bottomImgIndex],(170,650))

#音效类
#初始化音效
pygame.mixer.init()
soundList=[pygame.mixer.Sound('sound/button.ogg')]

#背景移动类
class BackGround:
    def __init__(self,speed,screen,img=startImages[6]):
        self.img1=img
        self.img1rect=self.img1.get_rect()
        self.img2=copy.copy(self.img1)
        self.img2rect=self.img2.get_rect()
        self.img2rect.y=-768

        self.speed=speed
        self.screen=screen

    def Move(self):
        self.img1rect=self.img1rect.move(0,self.speed)
        self.img2rect=self.img2rect.move(0,self.speed)
        if self.img1rect.y>=760:
            self.img1rect.y=self.img2rect.y-768
        if self.img2rect.y>=760:
            self.img2rect.y=self.img1rect.y-768

        self.screen.blit(self.img1,self.img1rect)
        self.screen.blit(self.img2,self.img2rect)

#敌机类
enemyList=[]

enemy0Imgs=[
    pygame.image.load('image/enemy0.png'),
    pygame.image.load('image/enemy0_down1.png'),
    pygame.image.load('image/enemy0_down2.png'),
    pygame.image.load('image/enemy0_down3.png'),
    pygame.image.load('image/enemy0_down4.png'),
]
enemy1Imgs=[
    pygame.image.load('image/enemy1.png'),
    pygame.image.load('image/enemy1_hit.png'),
    pygame.image.load('image/enemy1_down1.png'),
    pygame.image.load('image/enemy1_down2.png'),
    pygame.image.load('image/enemy1_down3.png'),
    pygame.image.load('image/enemy1_down4.png'),
]
enemy2Imgs=[
    pygame.image.load('image/enemy2.png'),
    pygame.image.load('image/enemy2.png'),
    pygame.image.load('image/enemy2_down1.png'),
    pygame.image.load('image/enemy2_down2.png'),
    pygame.image.load('image/enemy2_down3.png'),
    pygame.image.load('image/enemy2_down4.png'),
    pygame.image.load('image/enemy2_down5.png'),
    pygame.image.load('image/enemy2_down6.png'),
]
enemy3Imgs=[
    pygame.image.load('image/prop_type_0.png'),
    pygame.image.load('image/wsparticle_06.png'),


]
enemy4Imgs=[
    pygame.image.load('image/bomb.png'),
    pygame.image.load('image/hb1.png'),
    pygame.image.load('image/hb2.png'),
    pygame.image.load('image/hb3.png'),
    pygame.image.load('image/hb4.png')

]
enemy5Imgs=[
    pygame.image.load('image/stageClass2.png'),
    pygame.image.load('image/enemy2_down6.png')

]


class Enemy(pygame.sprite.Sprite):
    # 属性:图片,位置,血量,速度,屏幕,标签;ad
    def __init__(self,img,pos,hp,speed,screen,tag,imgs):
        self.image=img
        self.imgs=imgs
        self.rect=self.image.get_rect()
        self.rect.topleft=pos
        self.hp=hp
        self.speed=speed
        self.screen=screen
        self.tag=tag

        self.indexAdd=0
        self.indexImg=0

        enemyList.append(self)

    #行为:移动,死亡
    def Move(self):
        if self.hp<=0:
            self.Dead()
        else:
            self.rect = self.rect.move(0, self.speed)
            self.screen.blit(self.image, self.rect)
            # 出死亡画面,在最下面销毁敌机,防止列表内存过大溢出
            if self.rect.y >= 750:
                if self in enemyList and self != None:
                    enemyList.remove(self)

    #死亡
    def Dead(self):
        self.indexAdd+=1
        if self.indexAdd==1000:
            self.indexAdd=0
        #播放死亡画面
        if self.tag=='enemy0':
            if self.indexAdd%7==0:
                self.indexImg+=1
                if self.indexImg==4:
                    # 删除列表
                    if self in enemyList:
                        Hero.Score+=1
                        enemyList.remove(self)

        elif self.tag=='enemy1':
            if self.indexAdd%7==0:
                self.indexImg+=1
                if self.indexImg==5:
                    # 删除列表
                    if self in enemyList:
                        Hero.Score += 5
                        enemyList.remove(self)
        elif self.tag=='enemy3':
            if self.indexAdd%7==0:
                self.indexImg+=1
                if self.indexImg==1:
                    # 删除列表d
                    if self in enemyList:
                        Hero.bombScore +=2
                        if Hero.bombScore>6:
                            Hero.bombScore=0
                        enemyList.remove(self)

        elif self.tag == 'enemy4':
            if self.indexAdd % 7== 0:
                self.indexImg += 1
                if self.indexImg == 4:
                    # 删除列表
                    if self in enemyList:
                        Hero.Score += 20
                        enemyList.remove(self)
                        enemyList.clear()
        elif self.tag=='enemy5':
            if self.indexAdd%7==0:
                self.indexImg+=1
                if self.indexImg==1:
                    # 删除列表d
                    if self in enemyList:
                        Hero.superScore +=2
                        if Hero.superScore>6:
                            Hero.superScore=0
                        enemyList.remove(self)
        else:
            if self.indexAdd%7==0:
                self.indexImg+=1
                if self.indexImg==7:
                    # 删除列表
                    if self in enemyList:
                        Hero.Score += 10
                        enemyList.remove(self)

        #渲染
        self.screen.blit(self.imgs[self.indexImg], self.rect)


#敌机工厂类
class EnemyFactor:
    @staticmethod
    def CreateEnemy(screen):
    # 产生几率   小70%  中20%   大10%
        ranNum=r.randint(1,750)
        if ranNum<500:
            Enemy(enemy0Imgs[0],(r.randint(0,429),-39),1,5,screen,'enemy0',enemy0Imgs)
        elif ranNum<550:
            Enemy(enemy1Imgs[0],(r.randint(0,411),-89),3,3,screen,'enemy1',enemy1Imgs)
        elif ranNum<600:
            Enemy(enemy3Imgs[0], (r.randint(0, 422), -58), 1, 3, screen, 'enemy3',enemy3Imgs)
        elif ranNum<650:
            Enemy(enemy4Imgs[0], (r.randint(0, 417), -53), 2, 3, screen, 'enemy4', enemy4Imgs)
        elif ranNum<700:
            Enemy(enemy5Imgs[0], (r.randint(0, 395), -85), 2, 3, screen, 'enemy5', enemy5Imgs)
        else:
            Enemy(enemy2Imgs[0],(r.randint(0,315),-246),8,1,screen,'enemy2',enemy2Imgs)

    @staticmethod
    def AllEnemyMove():
        for i in enemyList:
            if isinstance(i,Enemy):
                i.Move()

#主角类
heroImgs=[pygame.image.load('image/hero1.png'),
          pygame.image.load('image/hero2.png'),
          pygame.image.load('image/hero4.png')
          ]
class Hero(pygame.sprite.Sprite):
    up=False
    down = False
    left = False
    right = False

    Score=0
    bombScore=0
    superScore=0



    # 属性:图片,初始位置,血量,速度,屏幕;
    def __init__(self,imgs,pos,hp,speed,screen):
        if self.superScore>=4:
            self.image=self.imgs[2]
            self.image=self.imgs[2].get_rect()
        else:
            self.imgs=imgs
            self.image = self.imgs[0]
            self.rect = self.imgs[0].get_rect()
        self.rect.topleft=pos
        self.hp=hp
        self.speed=speed
        self.screen=screen
        self.indexAdd=1
        self.imgIndex=0

    # 行为:移动,发射子弹,死亡,无敌,碰撞敌机
    def Move(self):
        if Hero.right:
            self.rect=self.rect.move(self.speed,0)
        if Hero.left:
            self.rect=self.rect.move(-self.speed,0)
        if Hero.down:
            self.rect=self.rect.move(0,self.speed)
        if Hero.up:
            self.rect=self.rect.move(0,-self.speed)

        #动图两张
        self.indexAdd+=1
        if self.indexAdd==1000:
            self.indexAdd=0

        if self.indexAdd%47==0:
            self.imgIndex+=1
            if self.imgIndex==2:
                self.imgIndex=0

        # 鼠标控制
        #self.rect.center = pygame.mouse.get_pos()

        #约束范围
        if self.superScore>=4:
            pass
        else:
            if self.rect.x <= 0:
                self.rect.x = 0
            if self.rect.x >= (self.screen.get_width() - self.imgs[0].get_width()):
                self.rect.x = self.screen.get_width() - self.imgs[0].get_width()
            if self.rect.y <= 0:
                self.rect.y = 0
            if self.rect.y >= (self.screen.get_height() - self.imgs[0].get_height()):
                self.rect.y = self.screen.get_height() - self.imgs[0].get_height()

        #渲染图像
        if self.superScore>=4:
            self.screen.blit(self.imgs[2], self.rect)
        else:
            self.screen.blit(self.imgs[self.imgIndex], self.rect)




        #产生子弹
        if self.indexAdd%9==0:
            if self.superScore>=4:
                Bullet((self.rect.centerx - (bulletImgs[0].get_width() / 2)+150, self.rect.y), 10, self.screen)
                #clock = pygame.time.Clock()
                # time_passed = clock.tick()
                # time_passed = clock.tick(30)
                if self.bombScore > 2:
                    Bullet((self.rect.centerx - (bulletImgs[3].get_width() / 2), self.rect.y + 45), 10, self.screen)
                    if self.bombScore > 4:
                        Bullet((self.rect.centerx - (bulletImgs[3].get_width() / 2) + 300, self.rect.y + 45), 10,self.screen)
            else:
                Bullet((self.rect.centerx - (bulletImgs[0].get_width() / 2), self.rect.y), 10, self.screen)
                # clock = pygame.time.Clock()
                # time_passed = clock.tick()
                # time_passed = clock.tick(30)
                if self.bombScore > 2:
                    Bullet((self.rect.centerx - (bulletImgs[3].get_width() / 2) - 35, self.rect.y + 45), 10,self.screen)
                    if self.bombScore > 4:
                        Bullet((self.rect.centerx - (bulletImgs[3].get_width() / 2) + 45, self.rect.y + 45), 10,self.screen)




            print(self.bombScore)

        #子弹移动
        for i in bulletList:
            if i!=None and isinstance(i,Bullet):
                i.Move()
        self.Collide()
        global isPlay
        if self.hp<=0:
            UpdateHistory(Hero.Score)
            isPlay=False

    #碰撞敌机
    def Collide(self,target=enemyList):
        tempEnemy=pygame.sprite.spritecollideany(self,target,collided=pygame.sprite.collide_mask)
        if tempEnemy in enemyList:
            self.hp-=1
            self.rect.topleft=(180,500)
            tempEnemy.hp-=10



#子弹类
bulletImgs=[
    pygame.image.load('image/bullet.png'),
    pygame.image.load('image/bullet1.png'),
    pygame.image.load('image/bullet2.png'),
    pygame.image.load('image/zidan1.png')
]
bulletList=[]
class Bullet(pygame.sprite.Sprite):
    # 属性:图片,位置,速度,屏幕;
    def __init__(self,pos,speed,screen,img=bulletImgs[0],img3=bulletImgs[3]):
        if Hero.bombScore>4:
            self.image = img3
            self.rect = self.image.get_rect()
        else:
            self.image = img
            self.rect = self.image.get_rect()

        self.rect.topleft=pos

        self.speed=speed
        self.screen=screen
        bulletList.append(self)

    #行为:移动,碰撞敌机
    def Move(self):
        self.rect=self.rect.move(0,-self.speed)
        self.screen.blit(self.image,self.rect)
        if self.rect.y<=-30:
            if self in bulletList:
                bulletList.remove(self)
        self.CollideEnemy()

    #碰撞敌机
    def CollideEnemy(self,target=enemyList):#target检测目标
        #collided=pygame.sprite.collide_mask  >>打开碰撞遮罩
        tempEnemy=pygame.sprite.spritecollideany(self,target,collided=pygame.sprite.collide_mask)
        if tempEnemy in enemyList and self in bulletList:
            bulletList.remove(self)
            tempEnemy.hp-=1

stop_img = [pygame.image.load("image/resume_nor.png"),
            pygame.image.load("image/restart_nor.png"),
            pygame.image.load("image/quit_sel.png"),
            pygame.image.load("image/bg_peek.png")
            ]
class Game_stop:
    isInside1 = False
    isInside2 = False
    isInside3 = False
    def __init__(self,screen ,stop_img =stop_img ):
        self.stop_img = stop_img
        self.screen = screen
    def stop(self):
        self.screen.blit(self.stop_img[3], (150, 270))
        bt1 = self.screen.blit(self.stop_img[0], (348, 350))
        bt2 = self.screen.blit(self.stop_img[1], (319, 400))
        bt3 = self.screen.blit(self.stop_img[2], (320, 450))
        Game_stop.isInside1 = bt1.collidepoint(pygame.mouse.get_pos())  # 判断鼠标是否在图标位置下
        Game_stop.isInside2 = bt2.collidepoint(pygame.mouse.get_pos())
        Game_stop.isInside3 = bt3.collidepoint(pygame.mouse.get_pos())


screen=None
#事件监测的方法
def AllEvent():
    global screen
    global isPlay
    global isRead
    global isStop
    # 迭代所有事件
    for i in pygame.event.get():
        # 判断事件是否为 退出
        if i.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        if i.type == pygame.MOUSEBUTTONDOWN:
            if i.button==1 and StartPanel.outisInside:
                pygame.quit()
                sys.exit()
            if i.button==1 and StartPanel.readisInside:
                print('查看最高分')
                isRead=True
                ReadHistory()
            # print(i)
            if i.button == 1 and StartPanel.isInside:
                print('开始游戏')
                #直读取数据
                ReadHistory()
                soundList[0].play()
                heroObject.hp=10
                Hero.Score=0
                enemyList.clear()
                bulletList.clear()
                isPlay = True
        if i.type == pygame.KEYDOWN:
            if i.key==pygame.K_SPACE:
                isStop=False
            if i.key == pygame.K_ESCAPE:
                isPlay = False
                soundList[0].play()
            if i.key == pygame.K_ESCAPE:
                isRead = False
                soundList[0].play()
            if i.key==pygame.K_w:
                Hero.up=True
            if i.key==pygame.K_s:
                Hero.down = True
            if i.key==pygame.K_a:
                Hero.left = True
            if i.key==pygame.K_d:
                Hero.right = True
        if i.type==pygame.KEYUP:
            if i.key==pygame.K_w:
                Hero.up=False
            if i.key==pygame.K_s:
                Hero.down = False
            if i.key==pygame.K_a:
                Hero.left = False
            if i.key==pygame.K_d:
                Hero.right = False

        if i.type==pygame.USEREVENT+1 and isPlay:
            EnemyFactor.CreateEnemy(screen)


#第一步 初始化pygame
pygame.init()
# 第二步 初始化display
pygame.display.init()

# 第三步 创建窗口
screen = pygame.display.set_mode((480, 750))
#英雄对象
heroObject=Hero(heroImgs,(180,500),10,8,screen)

#字体
fontObj=pygame.font.Font('font/Marker Felt.ttf',25)
#历史的最高分读取和更新
history=0
def ReadHistory(path='score.txt'):
    global history
    if os.path.exists(path):
        with open(path,'r') as f_r:
            history=f_r.read()
            #print('history',type(history))
            #读和写操作的都是字符串
    else:
        with open(path,'w') as f_w:
            f_w.write('0')
def UpdateHistory(score,path='score.txt'):
    if os.path.exists(path):
        with open(path,'r') as f_r:
            if int(f_r.read())

图片素材想要的 评论留下QQ邮箱,我给你发
码云地址

你可能感兴趣的:(python实战项目)