python飞机大战小游戏源码

 copy之前需要安装pygame(装过的当我没说):

pip install pygame

 以下是源码

import pygame
from sys import exit
from random import randint
# 声明常量
String = ".\\"
FPS = 100
SCORE = 0
Bullets = 0
CLOCK = pygame.time.Clock()
W = 600
H = 400

# 初始化
pygame.init()

# 设置窗口
window = pygame.display.set_mode([W, H])
pygame.display.set_caption("AircraftBattleGame")

over = pygame.image.load(f"{String}game_over.jpg")


def main_game():
    # 初始化
    pygame.init()

    global SCORE
    global Bullets
    Bullets = 50 - 1
    SCORE = 0

    class AircraftClass(pygame.sprite.Sprite):
        def __init__(self, w, h):
            pygame.sprite.Sprite.__init__(self)
            self.image = pygame.transform.scale(
                    pygame.image.load(f"{String}飞机.jpg"), (w, h))

            self.rect = self.image.get_rect()
            self.rect[0] = (W - self.rect[2]) / 2
            self.rect[1] = H - self.rect[3]

        def update(self, new_x=0, new_y=0):
            x, y, w, h = self.rect
            self.rect = (new_x, new_y, w, h)

    class FireBombClass(pygame.sprite.Sprite):
        def __init__(self, x, y, w=32, h=64):
            pygame.sprite.Sprite.__init__(self)

            self.y = y

            self.image = pygame.transform.scale(
                    pygame.image.load(f"{String}火弹.jpg"), [w, h])

            self.rect = self.image.get_rect()
            self.rect[0] = x
            self.rect[1] = self.y

        def move(self):
            self.rect[1] -= 5

    class EnemyClass(pygame.sprite.Sprite):
        def __init__(self, enemy_x):
            # 必要操作
            pygame.sprite.Sprite.__init__(self)
            self.enemy_x = enemy_x

            self.image = pygame.transform.flip(pygame.image.load(
                    f"{String}敌机.jpg"), False, True)
            # 改变大小
            self.image = pygame.transform.scale(self.image, (60, 60))

            self.rect = self.image.get_rect()
            self.rect[0] = enemy_x

        def update(self, new_y):
            x, y, w, h = self.image.get_rect()
            self.rect = (self.enemy_x, new_y, w, h)

    def move_determine(x=0, y=0, key="UP"):
        if key == 'UP':
            if y <= 0:
                return False
        if key == 'DOWN':
            if y >= H - Aircraft.rect[2]:
                return False
        if key == 'RIGHT':
            if x >= W - Aircraft.rect[2]:
                return False
        if key == 'LEFT':
            if x <= 0:
                return False
        return True

    # 加载图片
    Bg = pygame.transform.scale(pygame.image.load(f"{String}星空.jpg"), [W, H])

    # 加载音效
    FireBomb_music = pygame.mixer.Sound('.\\激光发射.mp3')
    pint_music = pygame.mixer.Sound(".\\得分.wav")

    # 放置图片
    window.blit(Bg, [0, 0])

    # 刷新
    pygame.display.flip()

    # 实例化对象
    Aircraft = AircraftClass(w=60, h=60)


    # 创建精灵组
    AircraftGroup = pygame.sprite.Group()
    FireBombGroup = pygame.sprite.Group()
    EnemyGroup = pygame.sprite.Group()

    # 添加精灵
    AircraftGroup.add(Aircraft)

    Aircraft_x = Aircraft.rect[0]
    Aircraft_y = Aircraft.rect[1]

    can_move = False
    x, y = 0, 0
    last_ms = 0
    last_time = 0

    font = pygame.font.Font('freesansbold.ttf', 32)

    while True:
        # 绘制背景
        window.fill([255, 255, 255])
        window.blit(Bg, [0, 0])
        # 显示TEXT
        show_score = font.render(f"Score:{str(SCORE)}", True, (255, 255, 255))
        window.blit(show_score, [0, 0])

        show_bullets = font.render(f"Bullets:{str(Bullets)}", True, (255, 255, 255))
        window.blit(show_bullets, [0, 50])

        FireBomb = FireBombClass(Aircraft_x + (Aircraft.rect[3] // 2 - 15), Aircraft_y)

        time = pygame.time.get_ticks()
        if time > last_time + 2600:
            last_time = time
            # 设置子弹上限
            if Bullets < 60:
                Bullets += 1

        # 刷新敌机
        ms = pygame.time.get_ticks()
        if ms > last_ms + randint(300, 600):
            last_ms = ms
            # 实例化对象
            Enemy = EnemyClass(randint(0, W - 60))

            EnemyGroup.add(Enemy)

        # 遍历敌机列表
        for enemy in EnemyGroup.sprites():
            # 碰撞检测
            if pygame.sprite.collide_mask(Aircraft, enemy) is not None:
                return

            for i in FireBombGroup.sprites():
                if pygame.sprite.collide_mask(i, enemy) is not None:
                    pint_music.play()
                    SCORE += 1
                    FireBombGroup.remove(i)
                    EnemyGroup.remove(enemy)
                    break

            sprite_y = enemy.rect[1]

            sprite_y += 2.58

            if sprite_y >= H + 50:
                EnemyGroup.remove(enemy)

            enemy.update(sprite_y)

        # 遍历子弹
        for fireBomb in FireBombGroup.sprites():
            if fireBomb.rect[1] < -30:
                FireBombGroup.remove(fireBomb)
            fireBomb.move()

        # 更新玩家位置
        Aircraft.update(Aircraft_x, Aircraft_y)

        # 绘制精灵组
        EnemyGroup.draw(window)
        FireBombGroup.draw(window)
        AircraftGroup.draw(window)

        if can_move is True:
            Aircraft_y += y
            Aircraft_x += x
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
            # 移动飞机
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.display.quit()
                    exit(0)


                if event.key == pygame.K_DOWN or event.key == pygame.K_s:
                    y = 3.07
                    if move_determine(y=Aircraft_y, key='DOWN'):
                        can_move = True
                        continue

                if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                    can_move = True
                    if move_determine(x=Aircraft_x, key='RIGHT'):
                        x = 3.1
                        continue

                if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                    can_move = True
                    if move_determine(x=Aircraft_x, key='LEFT'):
                        x = -3.1
                        continue

                if event.key == pygame.K_UP or event.key == pygame.K_w:
                    can_move = True
                    if move_determine(y=Aircraft_y, key='UP') is True:
                        y = -3.25
                        continue
                if Bullets > 0:
                    if event.key == pygame.K_SPACE:
                        # 播放音效
                        FireBomb_music.play()

                        # 减去子弹数
                        Bullets -= 1
                        FireBombGroup.add(FireBomb)

            if event.type == pygame.KEYUP:
                x, y = 0, 0
                can_move = False

        pygame.display.update()
        CLOCK.tick(FPS)


def game_over():
    # 初始化
    pygame.init()

    window.blit(over,
                ((W - over.get_size()[0]) / 2,
                 (H - over.get_size()[1]) / 2,
                 )
                )
    pygame.display.flip()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.display.quit()
                exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_F5:
                    main_game()
                    game_over()

        pygame.display.update()


main_game()
game_over()

300行代码不到 

需将蔬菜包与py文件放入同一目录下 

星空网址(背景): https://cdn.yuyicode.com/internalapi/asset/47282ff0f7047c6fab9c94b531abf721.png
敌机网址: https://cdn.yuyicode.com//internalapi/asset/38b7778030b24c588276b99751d81140.png
主机网址: https://cdn.yuyicode.com//internalapi/asset/83e532e130f7418c8b2712d8bef44bc7.png
火弹网址: https://cdn.yuyicode.com//internalapi/asset/1ad45725575b4342959a7a320cad8a99.png 

其余音效自行准备

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值