用python教大家做一个简单的飞机大战

做飞机大战之前,需要完成以下条件

  • 首先:需要安装pygame模块
  • 其次:一个编辑器,本人用的是sublime

代码块

  • 精灵类---plane_sprites
import pygame
import random
#定时器常量 
CREATE_ENEMY_EVENT = pygame.USEREVENT

SCREEN_RECT = pygame.Rect(0, 0, 1000, 500)

class GameSprite(pygame.sprite.Sprite):

    def __init__(self,image_url,new_speed=1):
        super().__init__()
        self.image = pygame.image.load(image_url)
        self.rect = self.image.get_rect()
        self.speed = new_speed

    def update(self,*args):
        #默认水平方向移动
        self.rect.x -= self.speed

#游戏背景精灵
class Background(GameSprite):
    def __init__(self,is_alt=False):
        super().__init__("/home/lzb/images/yyy.png")

        if is_alt:
            self.rect.left = self.rect.width
    def update(self):
        self.rect.x -= self.speed
        #判断是否移出屏幕 如果移出 将图像设置到屏幕方
        if self.rect.x <=  -self.rect.width:
            self.rect.left = self.rect.width

#敌机精灵
class Enemy(GameSprite):
    def __init__(self):

        super().__init__("/home/lzb/images/enemy1.png")
        #随机速度
        self.speed = random.randint(10, 15)
        #设置敌机的初始位置
        self.rect.left = SCREEN_RECT.width
        max_ = SCREEN_RECT.height -self.rect.height
        self.rect.bottom = random.randint(0, max_)

    def update(self):
        
        panduan = random.randint(0, 1)
        if panduan == 0:
            self.rect.y -= self.speed
            self.rect.x -= self.speed
        else:
            self.rect.y += self.speed
            self.rect.x -= self.speed
        #判断敌机是否飞出屏幕  如果飞出屏幕将敌机从精灵组删除
        if self.rect.y >= SCREEN_RECT.height or self.rect.right <=0 or self.rect.bottom <=0:
            self.kill()



#英雄精灵
class Hero(GameSprite):

    def __init__(self):
        super().__init__("/home/lzb/images/me1.png")

        self.rect.centery = SCREEN_RECT.centery+100
        self.rect.left = SCREEN_RECT.y
        self.move = True
        #子弹精灵组
        self.bullets_group = pygame.sprite.Group()
    def update(self):
        #super().update()
        if not self.move:
            self.rect.x += self.speed
        else:
            self.rect.y += self.speed

        #self.rect.y += self.speed
        #飞机飞出屏幕
        if self.rect.bottom <= 0:
            self.rect.y = self.rect.bottom+SCREEN_RECT.height
        elif self.rect.y >= SCREEN_RECT.height:
            self.rect.y = -self.rect.height

        if self.rect.right <= 0:
            self.rect.x = self.rect.right+SCREEN_RECT.width
        elif self.rect.x >= SCREEN_RECT.width:
            self.rect.x = -self.rect.width
    def fire(self):
        for i in (1,2,3):
            #创建子弹精灵
            bullet1 = Bullet()
            bullet2 = Bullet()
            bullet3 = Bullet()
            #设置子弹精灵的位置
            bullet1.rect.left = (self.rect.x+120)+i*20
            bullet1.rect.centery = self.rect.centery

            bullet2.rect.left = (self.rect.x+70)+i*20
            bullet2.rect.centery = self.rect.centery+32

            bullet3.rect.left = (self.rect.x+70)+i*20
            bullet3.rect.centery = self.rect.centery-32
            #将子弹精灵添加到精灵组
            self.bullets_group.add(bullet1,bullet2,bullet3)

#英雄精灵
class Hero_Two(GameSprite):

    def __init__(self):
        super().__init__("/home/lzb/images/life.png")
        self.rect.centery = SCREEN_RECT.centery-100
        self.rect.left = SCREEN_RECT.y
        self.Move = True
        #子弹精灵组
        self.bullet_group = pygame.sprite.Group()
    def update(self):
        #super().update()
        if not self.Move:
            self.rect.x += self.speed
        else:
            self.rect.y += self.speed

        #self.rect.y += self.speed
        #飞机飞出屏幕
        if self.rect.bottom <= 0:
            self.rect.y = self.rect.bottom+SCREEN_RECT.height
        elif self.rect.y >= SCREEN_RECT.height:
            self.rect.y = -self.rect.height

        if self.rect.right <= 0:
            self.rect.x = self.rect.right+SCREEN_RECT.width
        elif self.rect.x >= SCREEN_RECT.width:
            self.rect.x = -self.rect.width
    def fire(self):
        for i in (1,2,3):
            #创建子弹精灵
            bullet2 = Bullet()
            bullet3 = Bullet()
            #设置子弹精灵的位置

            bullet2.rect.left = (self.rect.x)+i*20
            bullet2.rect.centery = self.rect.centery+20

            bullet3.rect.left = (self.rect.x)+i*20
            bullet3.rect.centery = self.rect.centery-20
            #将子弹精灵添加到精灵组
            self.bullet_group.add(bullet2,bullet3)



#子弹精灵
class Bullet(GameSprite):
    def __init__(self):
        super().__init__("/home/lzb/images/bullet2.png")

    def update(self):
        # panduan = random.randint(0, 1)
        # if panduan == 0:
        #   self.rect.y -= 5
        #   self.rect.x += 5
        # else:
        #   self.rect.y += 5
        #   self.rect.x += 5
        self.rect.x += 30
        if self.rect.left >= SCREEN_RECT.width :

            self.kill()
  • 游戏主类---plan_main
import pygame
from plane_sprites import *
HERO_FIRE_EVENT = pygame.USEREVENT+1

#音乐
pygame.init()
pygame.mixer.music.load("/home/lzb/images/Alan Walker - Sky.mp3")
pygame.mixer.music.play(loops=-1)
class PlaneGame(object):
    
    def __init__(self):
        #创建游戏窗口
        self.screen = pygame.display.set_mode((SCREEN_RECT.size))
        #游戏时钟
        self.clock = pygame.time.Clock()
        #创建精灵和精灵组
        self.__create_sprites()
        pygame.display.set_caption("灰机大战")
        #设置一个定时器事件  每一秒钟创建一架敌机
        pygame.time.set_timer(CREATE_ENEMY_EVENT, 300)
        #子弹发射速度
        pygame.time.set_timer(HERO_FIRE_EVENT, 800)
    def start_game(self):
        while True:
            #1.刷新帧率
            self.clock.tick(200)
            #2.监听事件
            self.__handler_event()
            #3.碰撞检测b
            self.__check_collide()
            #4.更新精灵和精灵组
            self.__update_sprites()
            #5.刷新屏幕
            pygame.display.update()
    #创建精灵和精灵组
    def __create_sprites(self):

        bg1 = Background()
        bg2 = Background(True)
        self.hero = Hero()
        self.hero2 = Hero_Two()
        #英雄精灵组
        self.hero_group = pygame.sprite.Group(self.hero,self.hero2)
        #背景精灵组#调用父类的方法 让敌机在水平方向运动
        self.bg_group = pygame.sprite.Group(bg1,bg2)
        #敌机精灵组
        self.diji_group = pygame.sprite.Group()

    #监听事件
    def __handler_event(self):
        for event in pygame.event.get():
            keys_pressed = pygame.key.get_pressed()
            
            #控制飞机移动
            if keys_pressed[276]:
                self.hero.move = False
                self.hero.speed = -7
            elif keys_pressed[275]:
                self.hero.move = False
                self.hero.speed = 7
            elif keys_pressed[273]:
                self.hero.move = True
                self.hero.speed = -7
            elif keys_pressed[274]:
                self.hero.move = True
                self.hero.speed = 7
            else:
                self.hero.speed = 0


            if keys_pressed[97]:
                self.hero2.Move = False
                self.hero2.speed = -7
            elif keys_pressed[100]:
                self.hero2.Move = False
                self.hero2.speed = 7
            elif keys_pressed[119]:
                self.hero2.Move = True
                self.hero2.speed = -7
            elif keys_pressed[115]:
                self.hero2.Move = True
                self.hero2.speed = 7
            else:
                self.hero2.speed = 0
            #退出游戏
            if event.type == pygame.QUIT:
                PlaneGame.__game_over()
            #将敌机添加到精灵组里
            elif event.type == CREATE_ENEMY_EVENT:
                self.diji_group.add(Enemy())
            #英雄发子弹
            elif event.type == HERO_FIRE_EVENT:
                self.hero.fire()
                self.hero2.fire()
                
    @staticmethod
    def __game_over():
        print("游戏结束")
        pygame.quit()
        exit()

    #碰撞检测
    def __check_collide(self):
        #子弹销毁敌机
        pygame.sprite.groupcollide(self.hero.bullets_group,self.diji_group,True,True)
        pygame.sprite.groupcollide(self.hero2.bullet_group,self.diji_group,True,True)
        #敌机撞毁英雄
        enemies = pygame.sprite.spritecollide(self.hero,self.diji_group,True)
        enemie = pygame.sprite.spritecollide(self.hero2,self.diji_group,True)
        #判断列表时候有内容
        if len(enemies) > 0:
            self.hero.kill()
            self.hero.rect.y = -10000
        if len(enemie) > 0:
            self.hero2.kill()
            self.hero2.rect.y = -10000
        #判断两个敌机都死亡退出游戏
        if self.hero.rect.y == -10000 and self.hero2.rect.y == -10000:
            self.__game_over()
    #更新精灵和精灵组
    def __update_sprites(self):
        # self.hero_group.update()
        # self.hero_group.draw()

        # self.diji_group.update()
        # self.diji_group.draw()

        # self.bg_group.update()
        # self.bg_group.draw()
        for a in [self.bg_group,self.diji_group,self.hero_group,self.hero.bullets_group,self.hero2.bullet_group]:
            a.update()
            a.draw(self.screen)

if __name__ == "__main__":
    #使用游戏类创建游戏对象
    game = PlaneGame()

    #开始游戏
    game.start_game()

下面是我的飞机大战的运行结果

image.png

大致就这样了,欢迎大家把下面的喜欢biu一下!

你可能感兴趣的:(用python教大家做一个简单的飞机大战)