飞机大战 JavaScript

演示地址飞机大战http://kiss-rebounds.gitee.io/aircraft-war-games/

 

 滚动鼠标可切换子弹,击败敌人有一定概率掉落道具,灵活运用各种子弹可顺利通过。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <link rel="shortcut icon" href="resource/self.png">
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" class="mobileCSS">
    <style>
        body {
            width: 100vw;
            height: 100vh;
            overflow: hidden;
            display: grid;
            place-content: center;
        }

        .container {
            width: 920px;
            height: auto;
            margin-top: 40px;
            border: 2px solid rgb(0, 136, 255);
            border-radius: 10px;
            position: relative;
            z-index: 999;
            transition: all .2s;
        }

        .container:hover {
            background-color: rgb(0, 136, 255);
        }

        .container:hover button {
            border: 2px solid white !important;
            color: white;
        }

        .container button {
            width: 100px;
            height: 100px;
            line-height: 100px;
            text-align: center;
            text-decoration: none;
            background-color: transparent;
            color: rgb(0, 136, 255);
            border: 2px solid rgb(0, 136, 255);
            display: inline-block;
            margin: 15px;
            font-size: 22px;
            font-weight: 800;
            box-sizing: border-box;
            transition: all .2s;
            border-radius: 20px;
            cursor: pointer;
        }

        .container button.finish {
            background-color: rgb(0, 202, 101);
            color: white;
            border-color: rgb(0, 202, 101);
        }

        .container button:hover {
            transform: translateY(-10px);
        }

        @keyframes containerA {
            0% {
                transform: translateY(-20px);
                opacity: 0;
            }
        }

        .title {
            width: 100vw;
            position: fixed;
            z-index: 999;
            text-align: center;
            top: 20px;
            left: 0;
            color: rgb(0, 136, 255);
            font-size: 50px;
            font-weight: 800;
            transform: skew(-10deg);
            text-shadow: 0 0 5px #ffffff;
        }

        .enemy {
            opacity: 0.8;
        }

        .rule {
            width: 920px;
            height: 360px;
            margin-top: 10px;
            border: 2px solid rgb(0, 136, 255);
            color: rgb(0, 76, 255);
            background-color: transparent;
            border-radius: 10px;
            position: relative;
            z-index: 999;
            text-align: center;
            font-size: 17px;
            transition: all .2s;
            display: grid;
            place-content: center;
        }

        .rule:hover {
            color: white;
            background-color: rgb(0, 136, 255);
        }

        .rule:hover .trainingCamp {
            color: rgb(255, 255, 255);
        }

        .rule p {
            margin-bottom: 5px;
            border: 1px solid transparent;
            padding: 2px;
        }

        .rule p:hover {
            border: 1px solid white;
        }

        .bulletBox {
            border: 2px solid transparent;
            border-left: 2px solid rgb(0, 136, 255);
            padding: 15px;
            margin-top: 20px;
            position: fixed;
            z-index: 99;
            top: 120px;
            left: 30px;
            color: rgb(0, 76, 255);
            transition: all .2s;
            border-radius: 10px;
        }

        .bulletBox:hover {
            border: 2px solid rgb(0, 136, 255);
        }

        .bulletBox::before {
            content: '子弹:';
            position: relative;
            font-size: 18px;
            top: -8px;
        }

        .bulletBox div {
            margin-top: 20px;
            cursor: help;
        }

        .propsBox {
            border: 2px solid transparent;
            border-left: 2px solid rgb(0, 136, 255);
            padding: 15px;
            margin-top: 20px;
            position: fixed;
            z-index: 99;
            top: 120px;
            left: 150px;
            color: rgb(0, 76, 255);
            transition: all .2s;
            border-radius: 10px;
        }

        .propsBox:hover {
            border: 2px solid rgb(0, 136, 255);
        }

        .propsBox::before {
            content: '道具:';
            position: relative;
            font-size: 18px;
            top: -8px;
        }

        .propsBox div {
            width: 60px;
            height: 60px;
            background-image: url(resource/props.png);
            background-repeat: no-repeat;
            cursor: help;
        }

        .trainingCamp {
            color: rgb(17, 156, 255);
        }
    </style>
</head>

<body>
    <!-- 介绍 -->
    <div class="introduceBox">
        <div class="title">飞 机 大 战</div>
        <div class="container"></div>
        <div class="rule">
            <p>点击进入 <a href="trainingCamp.html" target="_blank" class="trainingCamp">训练营</a> 试玩(无BOSS)</p>
            <p>移动鼠标控制飞机的移动,滚动鼠标滚轮切换子弹</p>
            <p>击败当前关卡内的所有BOSS,即可获得胜利</p>
            <p>每种子弹各有特性,正确使用可以快速通关</p>
            <p>鼠标指向左边展示的子弹或道具,会显示其信息</p>
            <p>击败敌军有一定概率掉落道具(BOSS必定掉落)</p>
            <p>右下角的进度会告诉你最后一个BOSS出现的时间</p>
            <p>每逃走一个敌人扣除5点血量,BOSS逃走则会直接失败</p>
            <p>自己与敌人相撞,双方会扣除5点血量,且自己暂时无敌</p>
            <p>通关后关卡按钮会变色,指向它会展示该关卡最高得分</p>
        </div>
        <div class="bulletBox"></div>
        <div class="propsBox"></div>
    </div>
    <!-- 背景音乐 -->
    <audio muted src="resource/gameBG.ogg" class="BG_Audio"></audio>
    <!-- 战斗 -->
    <div class="fightingBox">
        <img src="resource/self.png" class="self">
        <div class="showCurrentInfo">
            <div class="showScore">0</div>
            血量 <progress value="30" min="0" max="30" class="blood" style="--color:rgb(255, 30, 30)"></progress><br>
            攻击力 <progress value="10" min="0" max="30" class="attackPower"
                style="--color:rgb(255, 85, 0)"></progress><br>
        </div>
        <div class="levelInfo">
            <div class="mark"></div>
            <progress min="0" style="--color:white"></progress>
        </div>
    </div>
    <script src="js/main.js"></script>
</body>

</html>
* {
    padding: 0px;
    margin: 0px;
    box-sizing: content-box;
}

body {
    width: 100vw;
    height: 100vh;
    overflow: hidden;
    background-size: cover;
    background-position: 50% 0%;
    user-select: none;
}

.self {
    width: 80px;
    height: auto;
    position: absolute;
    z-index: 9;
    top: 85vh;
    left: 50vw;
}

.self.Invincible {
    filter: brightness(150%);
}

.selfBullet {
    position: absolute;
    z-index: 1;
}

.enemy {
    position: absolute;
    opacity: 0.95;
}

.enemySoldier {
    position: absolute;
    z-index: 2;
    top: -30px;
    animation: enemySoldier 16s linear forwards;
}

@keyframes enemySoldier {
    100% {
        top: 100vh;
    }
}

.showCurrentInfo {
    width: 180px;
    height: 150px;
    /* background-color: rgba(0, 106, 255, 0.5); */
    position: fixed;
    z-index: 99;
    top: 0px;
    left: 0px;
    clip-path: polygon(0 0, 100% 0, 87% 100%, 0% 100%);
    padding-right: 20px;
    opacity: 0.9;
    padding-left: 10px;
}

progress {
    width: 60%;
    height: 11px;
    background: none;
    transform: skew(-15deg);
    margin-top: 15px;
    opacity: 0.9;
    border: 2px solid rgb(64, 64, 64);
    padding: 2px;
}

progress::-webkit-progress-bar {
    background-color: white;
    /* background-color: transparent; */
}

progress::-webkit-progress-value {
    background-color: var(--color);
    /* background-color: rgb(0, 182, 254); */
}

.explosion {
    width: 66px;
    height: 66px;
    background-image: url(../resource/explosion.png);
    background-position-x: 0px;
    background-repeat: no-repeat;
    animation: explosion .3s steps(7) forwards;
    position: absolute;
    z-index: 9;
    opacity: 0.9;
}

@keyframes explosion {
    80% {
        opacity: 0.9;
    }

    100% {
        background-position-x: -462px;
        opacity: 0.3;
    }
}

.enemyBoss {
    width: 360px;
    height: 250px;
    background-image: url(../resource/boss.png);
    background-repeat: no-repeat;
    transform: scale(0.7);
    position: absolute;
    top: -150px;
    z-index: 9;
    animation: enemyBoss 120s linear forwards;
}

@keyframes enemyBoss {
    100% {
        top: 90vh;
    }
}

.enemyBossBullet {
    width: 15px;
    height: 34px;
    background-image: url(../resource/bossBullet.png);
    background-repeat: no-repeat;
    position: absolute;
    z-index: 8;
    transition: all 1s linear;
}

.showScore {
    width: 95%;
    font-weight: 800;
    margin-top: 10px;
    border-bottom: 1px solid black;
    padding-bottom: 10px;
}

.showScore::before {
    content: '得分:';
}

.props {
    width: 60px;
    height: 60px;
    background-image: url(../resource/props.png);
    background-repeat: no-repeat;
    position: absolute;
    z-index: 99;
    opacity: 0.9;
}

.promptStatus {
    position: fixed;
    z-index: 5;
    top: 0;
    left: 0;
    height: 100vh;
    width: 100vw;
}

.hint {
    width: 100vw;
    height: auto;
    padding: 20px 0;
    position: fixed;
    z-index: 99;
    top: 120px;
    left: 0;
    text-align: center;
    font-size: 40px;
    font-weight: 900;
    font-family: cursive;
    background-color: rgba(0, 0, 0, 0.2);
}

.levelInfo {
    width: 150px;
    height: 40px;
    position: fixed;
    bottom: 5px;
    right: 5px;
}

.levelInfo::before {
    content: 'BOSS进度';
    position: absolute;
    font-weight: 800;
    top: 15px;
    left: -75px;
}

.levelInfo progress {
    width: 90%;
    position: absolute;
    top: 5px;
    left: 5px;
    border: 2px solid rgb(75, 75, 75);
    padding: 0;
}

.levelInfo progress::-webkit-progress-bar {
    background-color: rgb(0, 106, 255);
}
const self = document.querySelector('.self');
const body = document.body;
const windowWidth = window.innerWidth;
const showCurrentInfo = document.querySelector('.showCurrentInfo');
const showCurrentInfoAttackPower = document.querySelector('.showCurrentInfo .attackPower');
const showCurrentInfoBlood = document.querySelector('.showCurrentInfo .blood');
const showScore = document.querySelector('.showScore');
const levelInfo = document.querySelector('.levelInfo');
const levelInfoProgress = document.querySelector('.levelInfo progress');
let Invincible = false;
let additionalAttackPower = 0;
let doubleScore = false;
let strafingTimer;
let levelInfoProgressTimer;
let currentLevel = 0;

//输入一个最小值和最大值,则会返回两者之间的随机整数(包括两者)
const randomFunction = (min, max) => {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

const hintCreate = (color, text, duration) => {
    let hint = document.createElement('div');
    hint.classList.add('hint');
    hint.style.color = color;
    body.appendChild(hint);
    hint.innerHTML = text;
    // 到达指定时间后移除此元素
    setTimeout(() => hint.remove(), duration);
}

// 自己血量改变
const selfBloodChange = (val, duration) => {
    // 如果val大于0,则血量直接加val
    if (val > 0) {
        showCurrentInfoBlood.value >= 30 ? showCurrentInfoBlood.value = 30 : showCurrentInfoBlood.value += parseInt(val);
        // 血量条暂时变绿
        showCurrentInfoBlood.style.setProperty('--color', 'rgb(0, 255, 21)');
        // 恢复血量条初始颜色
        setTimeout(() => showCurrentInfoBlood.style.setProperty('--color', 'rgb(255, 30, 30)'), 500);
    } else {
        // 如果是无敌时间则返回,不能减少血量
        if (Invincible) return;
        // 减少血量
        showCurrentInfoBlood.value += parseInt(val);
        // 如果val为0,则不提示血量状态减少
        val && promptStatus('rgba(255, 0, 0, 0.3)', duration);
        if (showCurrentInfoBlood.value <= 0) {
            gameOver('很遗憾你失败了', false);
        }
        // 开启无敌
        Invincible = true;
        self.classList.add('Invincible');
        // 到达对应时间解除无敌
        setTimeout(() => {
            Invincible = false;
            self.classList.remove('Invincible');
        }, duration);
    }
}

// 提示状态
const promptStatus = (BG, duration) => {
    let promptStatus = document.createElement('div');
    promptStatus.classList.add('promptStatus');
    promptStatus.style.background = `radial-gradient(ellipse, rgba(255, 255, 255, 0), rgba(255, 255, 255, 0), ${BG})`;
    body.appendChild(promptStatus);
    // 到达指定时间后移除此元素
    setTimeout(() => promptStatus.remove(), duration);
}

// 自己的子弹信息列表
const selfBulletList = [
    {
        introduce: '普通子弹',
        width: 35,
        height: 35,
        polygon: '50% 0, 100% 40%, 100% 100%, 50% 60%, 0 100%, 0 40%',
        feature: [],
        attackPower: 22,
        color: 'rgb(0, 255, 128)'
    },
    {
        introduce: '大号子弹',
        width: 80,
        height: 30,
        polygon: '50% 0, 100% 40%, 100% 100%, 50% 60%, 0 100%, 0 40%',
        feature: [],
        attackPower: 19,
        color: 'rgb(0, 255, 128)'
    },
    {
        introduce: '穿透能力(击中敌人子弹不会消失)',
        width: 40,
        height: 35,
        polygon: '0 100%, 50% 0, 100% 100%, 50% 70%',
        feature: ['penetrate'],
        attackPower: 6,
        color: 'rgb(0, 149, 255)'
    },
    {
        introduce: '攻击力最高',
        width: 20,
        height: 35,
        polygon: '50% 0, 100% 40%, 100% 100%, 50% 60%, 0 100%, 0 40%',
        feature: [],
        attackPower: 26,
        color: 'rgb(251, 56, 56)'
    },
    {
        introduce: '幸运(增加道具掉落概率)',
        width: 35,
        height: 35,
        polygon: '50% 0, 67% 33%, 100% 50%, 67% 67%, 50% 100%, 33% 67%, 0 50%, 33% 33%',
        feature: ['lucky'],
        attackPower: 19,
        color: 'rgb(255, 174, 0)'
    },
]

// 当前子弹的类型
let currentBulletNum = 0;
let currentBullet = selfBulletList[currentBulletNum];

// 滚动鼠标改变子弹类型
document.addEventListener('wheel', e => {
    // 负数是向下滚动
    if (e.wheelDeltaY < 0) {
        currentBulletNum >= selfBulletList.length - 1 ? currentBulletNum = 0 : currentBulletNum++;
    } else {
        currentBulletNum <= 0 ? currentBulletNum = selfBulletList.length - 1 : currentBulletNum--;
    }
    // 改变当前子弹类型
    currentBullet = selfBulletList[currentBulletNum];
    // 更新攻击力显示
    showCurrentInfoAttackPower.value = currentBullet.attackPower + additionalAttackPower;
});

// 创建自己的子弹
const selfBulletCreate = (changeLeft) => {
    let bullet = document.createElement('div');
    bullet.classList.add('selfBullet');
    bullet.style.width = `${currentBullet.width}px`;
    bullet.style.height = `${currentBullet.height}px`;
    bullet.style.clipPath = `polygon(${currentBullet.polygon})`;
    bullet.style.backgroundColor = currentBullet.color;
    // 子弹的攻击力
    bullet.setAttribute('attackPower', currentBullet.attackPower + additionalAttackPower);
    // 添加该子弹的特性,如穿透等
    currentBullet.feature.forEach(item => bullet.setAttribute(item, item));
    body.appendChild(bullet);
    // 子弹的初始位置
    bullet.style.left = `${self.offsetLeft + self.clientWidth / 2 - bullet.clientWidth / 2}px`;
    // 如果有这个参数,则重置子弹的左边距
    if (changeLeft) bullet.style.left = `${changeLeft}px`;
    bullet.style.top = `${self.offsetTop + self.clientHeight / 2 - bullet.clientHeight}px`;
    // 使子弹运动(改变它的top)
    bullet.style.transition = 'all 1s linear';
    bullet.style.top =
        `${self.offsetTop + self.clientHeight / 2 - bullet.clientHeight - window.outerHeight}px`;
    // 过渡完成后移除子弹
    // bullet.addEventListener('transitionend', e => e.target.remove());
    setTimeout(() => bullet.remove(), 1100);
}

// 敌方小兵信息列表
const enemySoldierList = [{
    src: 'resource/enemySoldier1.png',
    blood: 10,
    score: 10
},
{
    src: 'resource/enemySoldier2.png',
    blood: 20,
    score: 20
},
{
    src: 'resource/enemySoldier3.png',
    blood: 30,
    score: 30
},
{
    src: 'resource/enemySoldier4.png',
    blood: 40,
    score: 40
},
{
    src: 'resource/enemySoldier5.png',
    blood: 50,
    score: 50
}
]
// 创建敌人(小兵)
const enemySoldierCreate = () => {
    let enemySoldier = document.createElement('img');
    let random = randomFunction(0, 4);
    enemySoldier.classList.add('enemy');
    enemySoldier.classList.add('enemySoldier');
    enemySoldier.setAttribute('src', enemySoldierList[random].src);
    enemySoldier.setAttribute('blood', enemySoldierList[random].blood);
    enemySoldier.setAttribute('score', enemySoldierList[random].score);
    body.appendChild(enemySoldier);
    // 随机左边距
    enemySoldier.style.left = `${randomFunction(0, windowWidth - 100)}px`;
    // css动画结束时,移除敌人(动画结束代表敌人逃走)
    enemySoldier.addEventListener('animationend', e => {
        e.target.remove();
        // 血量减少5,无敌时间0秒
        selfBloodChange(-5, 0);
        promptStatus('rgba(255, 0, 0, 0.3)', 500);
    });
}

// boss信息列表
const enemyBossList = [{
    bossId: 0,
    BGX: 0,
    blood: 4000,
    bullet: {
        BGX: 0,
        attackPower: 7,
    },
    score: 1000
}, {
    bossId: 1,
    BGX: -360,
    blood: 4500,
    bullet: {
        BGX: -15,
        attackPower: 6,
    },
    score: 1000
}, {
    bossId: 2,
    BGX: -720,
    blood: 5000,
    bullet: {
        BGX: -30,
        attackPower: 5,
    },
    score: 1000
}, {
    bossId: 3,
    BGX: -1080,
    blood: 5500,
    bullet: {
        BGX: -45,
        attackPower: 4,
    },
    score: 1000
}, {
    bossId: 4,
    BGX: -1440,
    blood: 6000,
    bullet: {
        BGX: -60,
        attackPower: 3,
    },
    score: 1000
}]

// 创建boss
const enemyBossCreate = () => {
    let enemyBoss = document.createElement('div');
    let random = randomFunction(0, 4);
    enemyBoss.classList.add('enemy');
    enemyBoss.classList.add('enemyBoss');
    enemyBoss.style.backgroundPositionX = `${enemyBossList[random].BGX}px`;
    enemyBoss.setAttribute('blood', enemyBossList[random].blood);
    enemyBoss.setAttribute('bossId', enemyBossList[random].bossId);
    enemyBoss.setAttribute('score', enemyBossList[random].score);
    body.appendChild(enemyBoss);
    enemyBoss.style.left = `${randomFunction(0, windowWidth - enemyBoss.offsetWidth)}px`;
    // css动画结束时,移除敌人(动画结束代表boss逃走)
    enemyBoss.addEventListener('animationend', e => {
        e.target.remove();
        // 血量清空,无敌时间0秒
        selfBloodChange(-999, 0);
    });
}

// 创建boss的子弹
const enemyBossBulletCreate = (num, top, left) => {
    let enemyBossBullet = document.createElement('div');
    enemyBossBullet.classList.add('enemyBullet');
    enemyBossBullet.classList.add('enemyBossBullet');
    enemyBossBullet.style.left = `${left}px`;
    enemyBossBullet.style.top = `${top}px`;
    // 使子弹运动(改变它的top)
    enemyBossBullet.style.transition = `all ${Math.random() + 2.2}s linear`;
    setTimeout(() => enemyBossBullet.style.top = `${top + window.outerHeight + 100}px`, 10);
    enemyBossBullet.style.backgroundPositionX = `${enemyBossList[num].bullet.BGX}px`;
    // boss子弹的攻击力
    enemyBossBullet.setAttribute('attackPower', enemyBossList[num].bullet.attackPower);
    body.appendChild(enemyBossBullet);
    setTimeout(() => enemyBossBullet.remove(), 4000);
}

// 判断两个元素是否碰撞
function ifCollision(element1, element2) {
    var rect1 = element1.getBoundingClientRect();
    var rect2 = element2.getBoundingClientRect();
    return !(rect1.right < rect2.left || rect1.left > rect2.right || rect1.bottom < rect2.top || rect1.top > rect2.bottom);
}

document.addEventListener('mousemove', e => {
    if (!self) return;
    // 使自己的飞机跟随鼠标
    self.style.top = `${e.clientY - self.offsetHeight / 2}px`;
    self.style.left = `${e.clientX - self.offsetWidth / 2}px`;
});

// 创建爆炸效果
const explosionCreate = (top, left) => {
    let explosion = document.createElement('div');
    explosion.classList.add('explosion');
    explosion.style.top = `${top}px`;
    explosion.style.left = `${left}px`;
    body.appendChild(explosion);
    // css动画结束时,移除
    explosion.addEventListener('animationend', e => e.target.remove());
}

// 道具列表
const propsList = [
    {
        introduce: '增加攻击力道具',
        propsId: 0,
        BGX: 0,
        propsFunction() {
            // 增加攻击力
            additionalAttackPower = 8;
            // 更新攻击力显示
            showCurrentInfoAttackPower.value = currentBullet.attackPower + additionalAttackPower;
            // 恢复原始攻击力
            setTimeout(() => {
                additionalAttackPower = 0;
                // 更新攻击力显示
                showCurrentInfoAttackPower.value = currentBullet.attackPower + additionalAttackPower;
            }, 6000);
        }
    },
    {
        introduce: '无敌时间道具',
        propsId: 1,
        BGX: -60,
        propsFunction() {
            // 借用selfBloodChange函数,不减少血量,无敌时间为6秒
            selfBloodChange(0, 6000);
            promptStatus('rgba(255, 157, 0, 0.3)', 6000);
        }
    },
    {
        introduce: '血量增加道具',
        propsId: 2,
        BGX: -120,
        propsFunction() {
            // 增加血量
            selfBloodChange(10, 0);
            promptStatus('rgba(0, 255, 55, 0.3)', 500);
        }
    },
    {
        introduce: '双倍得分道具',
        propsId: 3,
        BGX: -180,
        propsFunction() {
            // 开启双倍得分
            doubleScore = true;
            // 关闭双倍得分
            setTimeout(() => doubleScore = false, 6000);
        }
    },
    {
        introduce: '增加子弹道具',
        propsId: 4,
        BGX: -240,
        propsFunction() {
            // 如果有定时器,则先清除上一个
            strafingTimer && clearInterval(strafingTimer);
            // 在侧翼发射子弹
            strafingTimer = setInterval(() => {
                selfBulletCreate(self.offsetLeft - currentBullet.width / 2);
                selfBulletCreate(self.offsetLeft + self.offsetWidth - currentBullet.width / 2);
            }, 200);
            // 停止发射
            setTimeout(() => {
                clearInterval(strafingTimer);
            }, 6000);
        }
    }
]

// 创建道具
const propsCreate = (top, left) => {
    let props = document.createElement('div');
    let random = randomFunction(0, 4);
    props.classList.add('props');
    props.style.top = `${top}px`;
    props.style.left = `${left}px`;
    props.style.backgroundPositionX = `${propsList[random].BGX}px`;
    props.setAttribute('propsId', propsList[random].propsId);
    body.appendChild(props);
    // 添加鼠标进入事件,触发相应的道具函数
    props.addEventListener('mouseenter', e => {
        propsList[e.target.getAttribute('propsId')].propsFunction();
        e.target.remove();
    });
    // 如果十秒内没有拾起道具,则道具消失
    setTimeout(() => props.remove(), 10000);
}

// 游戏关卡设置
const level = [{
    // 小兵来袭时间和持续时间
    enemySoldier: [
        // 第1波小兵来袭时间、持续时间
        [8000, 2000]
    ],
    // boss来袭时间
    enemyBoss: [5000]
},
{
    enemySoldier: [
        // 第1波小兵来袭时间、持续时间
        [10000, 2000],
        // 第2波小兵来袭时间、持续时间
        [30000, 2000]
    ],
    enemyBoss: [5000, 40000]
},
{
    enemySoldier: [
        [2000, 3000],
        [10000, 3000],
        [2000, 2000],
        [30000, 4000],
        [40000, 3000],
        [50000, 3000]
    ],
    enemyBoss: [5000, 60000]
},
{
    enemySoldier: [
        [2000, 3000],
        [10000, 3000],
        [2000, 3000],
        [30000, 2000],
        [40000, 3000],
        [70000, 3000],
        [90000, 3000]
    ],
    enemyBoss: [5000, 60000, 100000]
},
{
    enemySoldier: [
        [2000, 3000],
        [10000, 3000],
        [2000, 2000],
        [30000, 3000],
        [40000, 3000],
        [50000, 3000],
        [70000, 2000],
        [90000, 3000],
        [120000, 3000],
        [140000, 3000]
    ],
    enemyBoss: [5000, 60000, 100000, 150000]
},
{
    enemySoldier: [
        [2000, 3000],
        [10000, 3000],
        [2000, 2000],
        [30000, 3000],
        [40000, 3000],
        [50000, 2000],
        [60000, 3000],
        [80000, 3000],
        [90000, 3000],
        [130000, 2000],
        [150000, 3000],
        [170000, 3000]
    ],
    enemyBoss: [5000, 60000, 100000, 150000, 200000]
},
{
    enemySoldier: [
        [2000, 2000],
        [10000, 4000],
        [20000, 3000],
        [30000, 3000],
        [40000, 2000],
        [50000, 4000],
        [70000, 4000],
        [80000, 2000],
        [90000, 4000],
        [120000, 4000],
        [130000, 2000],
        [140000, 2000],
        [160000, 4000],
        [170000, 2000],
        [190000, 4000],
        [210000, 2000],
        [230000, 3000]
    ],
    enemyBoss: [5000, 60000, 100000, 150000, 200000, 240000]
}
]

// 开始游戏
function gameStart(num) {
    // 初始化
    currentLevel = num;
    // 初始化攻击力
    showCurrentInfoAttackPower.value = currentBullet.attackPower;
    showCurrentInfoAttackPower.setAttribute('max', 40);
    // 创建敌人小兵
    setInterval(enemySoldierCreate, 1000);
    // 所有的碰撞检测
    setInterval(() => {
        // 检测自己的子弹与敌人是否碰撞
        let allEnemy = document.querySelectorAll('.enemy');
        let allSelfBullet = document.querySelectorAll('.selfBullet');
        // 循环嵌套
        allEnemy.forEach(enemy => {
            allSelfBullet.forEach(selfBullet => {
                if (ifCollision(enemy, selfBullet)) {
                    // 爆炸效果
                    explosionCreate(selfBullet.offsetTop, selfBullet.offsetLeft);
                    // 如果没有penetrate(穿透)这个属性,则移除子弹
                    selfBullet.getAttribute('penetrate') || selfBullet.remove();
                    // 减少敌人血量
                    enemy.setAttribute('blood', parseInt(enemy.getAttribute('blood')) - parseInt(selfBullet.getAttribute('attackPower')));
                    // 如果敌人的血量低于或等于0,则移除敌人
                    if (enemy.getAttribute('blood') <= 0) {
                        // 如果是boss,则必定掉落一个道具
                        enemy.classList.contains('enemyBoss') && propsCreate(enemy.offsetTop + enemy.offsetHeight / 2, enemy.offsetLeft + enemy.offsetWidth / 2);
                        // 根据是否开启双倍得分,来判断此次加分
                        showScore.innerHTML = parseInt(showScore.innerHTML) + (doubleScore ? parseInt(enemy.getAttribute('score')) * 2 : parseInt(enemy.getAttribute('score')));
                        // 一定概率掉落道具,如果子弹有lucky(幸运)这个属性,则增加道具掉落概率
                        if (Math.random() < (selfBullet.getAttribute('lucky') ? 0.25 : 0.1)) propsCreate(enemy.offsetTop, enemy.offsetLeft);
                        enemy.remove();
                    }
                }
            });
        });
        // 检测自已与敌人是否碰撞
        allEnemy.forEach(enemy => {
            if (ifCollision(enemy, self)) {
                // 双方身上的爆炸效果
                explosionCreate(enemy.offsetTop + enemy.offsetHeight / 2, enemy.offsetLeft + enemy.offsetWidth / 3);
                explosionCreate(self.offsetTop, self.offsetLeft);
                // 血量减少5,无敌时间1500毫秒
                selfBloodChange(-5, 1500);
                // 减少敌人血量
                enemy.setAttribute('blood', parseInt(enemy.getAttribute('blood')) - 5);
                enemy.getAttribute('blood') <= 0 && enemy.remove();
            }
        });
        // 检测自己与敌人的子弹是否碰撞
        let allEnemyBullet = document.querySelectorAll('.enemyBullet');
        allEnemyBullet.forEach(bullet => {
            if (ifCollision(bullet, self)) {
                explosionCreate(bullet.offsetTop, bullet.offsetLeft);
                // 血量减少,无敌时间1000毫秒
                selfBloodChange(-(bullet.getAttribute('attackPower')), 1000);
                // 移除敌人的子弹
                bullet.remove();
            }
        });
        // 判断敌人的子弹与自己的子弹是否碰撞
        allSelfBullet.forEach(selfBullet => {
            allEnemyBullet.forEach(enemyBullet => {
                if (ifCollision(selfBullet, enemyBullet)) {
                    explosionCreate(selfBullet.offsetTop, selfBullet.offsetLeft);
                    // 清除双方子弹
                    selfBullet.remove();
                    enemyBullet.remove();
                }
            });
        });
    }, 100);
    // 创建自己的子弹
    setInterval(selfBulletCreate, 90);
    // 创建boss的子弹
    setInterval(() => {
        let allBoss = document.querySelectorAll('.enemyBoss');
        // 如果没有boss,则返回
        if (allBoss.length <= 0) return;
        allBoss.forEach(boss => {
            let bossAttr = boss.getBoundingClientRect();
            // boss发射的三颗子弹
            enemyBossBulletCreate(boss.getAttribute('bossId'), bossAttr.top + bossAttr.height / 2, bossAttr.left);
            enemyBossBulletCreate(boss.getAttribute('bossId'), bossAttr.bottom - 20, bossAttr.left + bossAttr.width / 2 - 7.5);
            enemyBossBulletCreate(boss.getAttribute('bossId'), bossAttr.top + bossAttr.height / 2, bossAttr.right - 15);
        });
    }, 900);
    let raidTimer;
    // 创建敌人小兵
    for (let i = 0; i < level[num].enemySoldier.length; i++) {
        setTimeout(() => {
            hintCreate('rgb(255, 46, 46)', '一大波敌人来袭', 2000);
            // 开启创建小兵的定时器
            raidTimer = setInterval(enemySoldierCreate, 300);
            // 清除创建小兵的定时器
            setTimeout(() => clearInterval(raidTimer), level[num].enemySoldier[i][1]);
        }, level[num].enemySoldier[i][0]);
    }
    // 创建boss
    for (let i = 0; i < level[num].enemyBoss.length; i++) {
        // 创建boss
        setTimeout(() => {
            hintCreate('rgb(255, 46, 46)', 'BOSS来袭', 2000);
            enemyBossCreate();
        }, level[num].enemyBoss[i]);
    }
    // 最后一个boss出现的时间
    let lastBoss = level[num].enemyBoss[level[num].enemyBoss.length - 1];
    // 设置关卡进度条
    levelInfoProgress.value = lastBoss;
    levelInfoProgress.setAttribute('max', lastBoss);
    // 持续增加关卡进度(减少进度值)
    levelInfoProgressTimer = setInterval(() => {
        levelInfoProgress.value -= 500;
        // 停止定时器
        if (levelInfoProgress.value <= 0) {
            clearInterval(levelInfoProgressTimer);
            // 判断是否胜利
            setInterval(() => {
                // 获取所有boss
                let allBoss = document.querySelectorAll('.enemyBoss');
                // 如果没有boss,则胜利
                if (allBoss.length <= 0) gameOver('恭喜你胜利了', true);
            }, 500);
        }
    }, 500);
}

// 游戏关卡胜利记录
const victoryRecord = localStorage.getItem('airplane_wars_victory_record') ? JSON.parse(localStorage.getItem('airplane_wars_victory_record')) : [];
for (let i = 0; i < level.length; i++) {
    // 如果victoryRecord元素不够,则添加
    victoryRecord.length >= level.length || victoryRecord.push(false);
}

// 游戏最高得分记录
const scoreRecord = localStorage.getItem('airplane_wars_score_record') ? JSON.parse(localStorage.getItem('airplane_wars_score_record')) : [];
for (let i = 0; i < level.length; i++) {
    // 如果scoreRecord元素不够,则添加
    scoreRecord.length >= level.length || scoreRecord.push(0);
}

// 游戏结束
function gameOver(text, ifVictory) {
    setTimeout(() => {
        alert(`${text},最终分数:${showScore.innerHTML}`);
        location.reload();
    }, 100);
    // 如果胜利了
    if (ifVictory) {
        // 则把当前关卡的索引变为true
        victoryRecord[currentLevel] = true;
        // 更新localStorage数据
        localStorage.setItem('airplane_wars_victory_record', JSON.stringify(victoryRecord));
        // 如果本次得分更高,则替换数据
        if (showScore.innerHTML > scoreRecord[currentLevel]) {
            scoreRecord[currentLevel] = showScore.innerHTML;
            localStorage.setItem('airplane_wars_score_record', JSON.stringify(scoreRecord));
        }
    }
}

// 飞机大战-4.0
// 渲染index.html画面
const container = document.querySelector('.container');
const rule = document.querySelector('.rule');
const ruleP = document.querySelectorAll('.rule p');
const bulletBox = document.querySelector('.bulletBox');
const propsBox = document.querySelector('.propsBox');
const BG_Audio = document.querySelector('.BG_Audio');
const introduceBox = document.querySelector('.introduceBox');
const fightingBox = document.querySelector('.fightingBox');

// 遍历关卡个数,创建a标签
for (let i = 0; i < level.length; i++) {
    let btn = document.createElement('button');
    btn.innerHTML = `第${i + 1}关`;
    btn.style.animation = `containerA ${Math.random() + 1}s`;
    btn.setAttribute('href', `${i}.html`);
    btn.setAttribute('target', '_blank');
    container.appendChild(btn);
}

// 为文字添加动画
ruleP.forEach(item => item.style.animation = `containerA ${Math.random() + 1}s`);

// 子弹介绍
selfBulletList.forEach(item => {
    let bullet = document.createElement('div');
    bullet.classList.add('bullet');
    bullet.style.width = `${item.width}px`;
    bullet.style.height = `${item.height}px`;
    bullet.style.clipPath = `polygon(${item.polygon})`;
    bullet.style.backgroundColor = item.color;
    bullet.setAttribute('title', `${item.introduce},攻击力:${item.attackPower},宽度${item.width}`);
    bulletBox.appendChild(bullet);
});

// 道具介绍
propsList.forEach(item => {
    let props = document.createElement('div');
    props.style.backgroundPositionX = `${item.BGX}px`;
    props.setAttribute('title', item.introduce);
    propsBox.appendChild(props);
});

// 获取已完成关卡胜利的记录
const victoryArr = localStorage.getItem('airplane_wars_victory_record') ? JSON.parse(localStorage.getItem('airplane_wars_victory_record')) : [];
const containerBtn = document.querySelectorAll('.container button');
// 如果为true,则为当前a标签添加finish类
victoryArr.forEach((item, index) => item && containerBtn[index].classList.add('finish'));

// 关卡最高分记录
const scoreArr = localStorage.getItem('airplane_wars_score_record') ? JSON.parse(localStorage.getItem('airplane_wars_score_record')) : [];
// 为每个a标签添加title,显示本关卡的最高得分
scoreArr.forEach((item, index) => item && containerBtn[index].setAttribute('title', `最高得分:${item}`));

// 隐藏展示战斗的页面
fightingBox.style.display = 'none';

// 为每个按钮添加事件
containerBtn.forEach((item, index) => {
    item.addEventListener('click', () => {
        // 点击播放背景音乐
        BG_Audio.muted = false;
        BG_Audio.autoplay = true;
        BG_Audio.loop = true;
        BG_Audio.play();
        // 隐藏介绍的页面
        introduceBox.style.display = 'none';
        // 显示战斗的画面
        fightingBox.style.display = 'block';
        // 开始游戏
        gameStart(index);
    });
});

// 移动端操作
const mobileCSS = document.querySelector('link.mobileCSS');
const myResize = () => {
    let userAgentInfo = navigator.userAgent;
    const Agents = ["Android", "iPhone", "symbianOS", "Windows Phone", "iPad", "iPod"]
    for (let i = 0; i < Agents.length; i++) {
        if (userAgentInfo.indexOf(Agents[i]) > 0) {
            // 是移动端
            // 添加移动端的CSS,让物体大小适应屏幕
            mobileCSS.setAttribute('href', 'css/mobile.css');
            break;
        }
        // 电脑端
    }
}
myResize();

// 手指操作飞机
document.addEventListener('touchmove', e => {
    if (!self) return;
    // 使自己的飞机跟随鼠标
    self.style.top = `${e.targetTouches[0].clientY - self.offsetHeight / 2}px`;
    self.style.left = `${e.targetTouches[0].clientX - self.offsetWidth / 2}px`;
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值