横版-飞机大战html游戏全代码js、jquery操作

博主的话

我在今年(19年)2月的时候为了练习jq写了一个h5小游戏,其中有诸多不如意的地方不足为外人道。上次写的是花了1周,这次写的横版飞机大战加起来花了7、8个小时左右。
较于上次,这次代码更加优美简洁、几乎无BUG、游戏界面更加好看友好。
我会把html文件、css文件提供下载地址,文件夹路径也展示给大家。但是图片就不给大家了,毕竟博主辛辛苦苦做出来的游戏。 但是!!!但是!!!我其实是很愿意给那些为了自己锻炼而需要参考我的代码的同志们。所以,大家有需要的话,加博主QQ:2864144286,全天在线,博主绝不吝啬。
这里给出我上次飞机大战的博客:

飞机大战html游戏全代码js、jquery操作


运行图片

在这里插入图片描述


目录路径

在这里插入图片描述

这里引用的图片资源比较多,所以大家想要程序跑起来的话,还需要jquery-3.3.1.js文件和img文件夹里面的图片。真有需求的可以加博主QQ。


飞机大战.html

<html>
<head>
    <title>飞机大战</title>
    <link rel="stylesheet" type="text/css" href="css/style-test.css"/>
    <script src="jquery-3.3.1.js" type="text/javascript"></script>
</head>
<body >
    <div id="container">
        <div id="tab">
            <audio src="css/music/firstDesk.mp3" id="firstDesk" class="audio" autoplay="autoplay" loop="loop"></audio>
            <audio src="css/music/boom.mp3" id="boom" class="audio"></audio>
            <div id="tab_time" class="tabStyle"><p><span></span></p></div>

            <div id="tab_sound" class="tabStyle"><p><span></span></p></div>
            <img src="css/img-test/sound1.png" id="sound1" class="soundStyle">
            <img src="css/img-test/sound2.png" id="sound2" class="soundStyle">

            <div id="tab_score" class="tabStyle"><p><span style="color: red;">得分</span></p>
                <div id="score_num_con">
                    <div class="info_score_num"><img src="css/img-test/0.png"></div>
                    <div class="info_score_num"><img src="css/img-test/0.png"></div>
                    <div class="info_score_num"><img src="css/img-test/0.png"></div>
                    <div class="info_score_num"><img src="css/img-test/0.png"></div>
                </div>
            </div>
            <div id="tab_oil" class="tabStyle"><p><span>油量</span></p>
                <div id="oil_border">
                    <div id="main_oil"></div>
                </div>
            </div>
            <div id="tab_life" class="tabStyle"><p><span></span></p></div>
            <img src="css/img-test/life1.png" id="life1" class="lifeStyle">
            <img src="css/img-test/life1.png" id="life2" class="lifeStyle">
        </div>
        <div id="mainBox">
            <img id="myPlane" src="css/img-test/plane.png"/>
            <div id="information">
                <p><span></span></p>
                <div></div><div></div><div></div><div></div><div></div><div></div>
            </div>
        </div>
    </div>
</body>

<script  type="text/javascript">
/**************************定义变量接口*****************************************/
    var bgMoveFlag=0;//背景移动flag

    var bgMoveSpeed=4;//背景移动速度
    var planeY=(parseInt($("#container").height())-65)/2;//飞机Y坐标
    var planeX=0;//飞机X坐标
    var planeMoveSpeed=3;//飞机移速
    var key_pressed=[false,false,false,false];//[0-3]分别代表左、上、右、下键
    var score=0;//分数
    var myPlane=$("#myPlane");//飞机对象
    var oilPerSecond=1.5;//每秒油耗
    var nowOil=100;//总油量
    var life=3;//生命
    var bulletRanking=3;//子弹等级 [1-3]三种级别的子弹
    var bulletType=2;//子弹样式 [1-3]
    
    cardInfor(5);
    
    

/*********************便捷函数*******************************/
function getRandom(min,max){//获取在区间[min.max]内的int数
        var s;
        s=parseInt(Math.random()*max+1);
        while(s<min)
        {
        s=parseInt(Math.random()*max+1);
        }
        return s;
    }
    function isInIt(b1,b2,e1,e2,e3,e4){
        var k=-3;//设置k值,使得子弹陷入敌机才会消失
        if(b1<e3-k&&b1>e1+k&&b2>e2+k&&b2<e4-k)
        {return 1;}
        else {return 0;}
      }
    function isFourInIt(b1,b2,b3,b4,e1,e2,e3,e4){//判断是否重叠,即相撞
        if(isInIt(b1,b2,e1,e2,e3,e4)||isInIt(b1,b4,e1,e2,e3,e4)||isInIt(b3,b2,e1,e2,e3,e4)||isInIt(b3,b4,e1,e2,e3,e4))
        {return 1;}
        else return 0;
    }
    function sleep(ms){//时间延迟函数
          return new Promise(resolve =>setTimeout(resolve,ms))
      }
      async function test() {
        console.log('Hello')
        await sleep(1000)
        console.log('world!')
        }

    function shansuo(i){//飞机闪烁多少秒
        var i1=0;
        myPlane.fadeTo(200,0.1);
        myPlane.fadeTo(200,1);
        i1+=1;
        if(i1<=i*2)
        setTimeout("shansuo()",500);
      }
/**************************系统设置*****************************************/
    /***封装游戏容器居中*****/
    function onResizeContainer(){
        var screenHeight=parseInt($(window).height()); //浏览器时下窗口可视区域高度
        var screenWidth=parseInt($(window).width()); //浏览器时下窗口可视区域高度
        var containerHeigth=parseInt($("#container").height());//container容器高度
        var containerWidth=parseInt($("#container").width());//container容器宽度
    
        $("#container").css({
        'marginLeft':(screenWidth-containerWidth)/2+'px',
        'marginTop':(screenHeight-containerHeigth)/2+'px',
        })
    }
    onResizeContainer();
    /***封装游戏背景类*****/
    function bgMove(){
        bgMoveFlag-=bgMoveSpeed;
        $("#container").css('background','url("css/img-test/background.jpg")'+bgMoveFlag+'px 0px');
        if(bgMoveFlag<=-1200) bgMoveFlag=0;//防止bgMoveFlag过大
        setTimeout(' bgMove()',50);
    }
    bgMove();
    /***初始化我方飞机*****/
    function initialPlane(){
        myPlane.css({
            'marginLeft':planeX+'px',
            'marginTop':planeY+'px'
        }); 
    }
    initialPlane();
    /******设置多键操作*********/
    document.addEventListener("keyup",function(e){
        key_pressed[e.keyCode-37]=false;  
    });
    document.addEventListener("keydown",function(e){
        key_pressed[e.keyCode-37]=true;
    });
    function keyBoradCtrl(){
        if(key_pressed[0]&&planeX>=0){
            planeX-=planeMoveSpeed;
            myPlane.css('marginLeft',planeX+'px');
        }
        if(key_pressed[1]&&planeY>=0){
            planeY-=planeMoveSpeed;
            myPlane.css('marginTop',planeY+'px');
            myPlane.attr('src','css/img-test/planeUp.png');
        }
        if(key_pressed[2]&&planeX<=1160){
            planeX+=planeMoveSpeed;
            myPlane.css('marginLeft',planeX+'px');
        }
        if(key_pressed[3]&&planeY<=550){
            planeY+=planeMoveSpeed;
            myPlane.css('marginTop',planeY+'px');
            myPlane.attr('src','css/img-test/planeDown.png');
        }
        if(!key_pressed[1]&&!key_pressed[3]){
            myPlane.attr('src','css/img-test/plane.png');
        }
        setTimeout('keyBoradCtrl()',20);
    }
    keyBoradCtrl();
    function cardInfor(key){//提供提示信息
        var cardinforword=['子弹升级','油箱加满','飞机加速','子弹更换','生命减一','游戏开始','游戏结束'];
        $("span")[5].innerHTML=cardinforword[key];
        $("#information").fadeTo(200,0.1);
        $("#information").fadeTo(200,1);
        $("#information").fadeTo(200,0.1);
        $("#information").fadeTo(200,1);
        $("#information").fadeTo(200,0.1);
        $("#information").fadeTo(200,1);
        $("#information").fadeTo(200,0);
       
    }
    
/**************************tab栏设置:时间、分数、生命、油量、声音控制*****************************/
    //时间
    var minute=0,second=0;
    function timedCount()
    {
        if(second==60) {second=0;minute++;}
        second++;
        $("span")[0].innerHTML="时间 "+(minute>9?minute:"0"+minute)+":"+(second>9?second:"0"+second);
        setTimeout("timedCount()",1000); 
    }
    timedCount();
    //声音设置
    $("span")[1].innerHTML="声音";
    var audio_key=1;                                //播放bgm的flag
    var audio = document.getElementById('firstDesk');
    $(".soundStyle").click(function(){
            $("#sound1").toggle();
            $("#sound2").toggle();
            if(audio_key) 
                {audio.pause();audio_key=0;}
            else 
                {audio.play();audio_key=1;}
    });
    //分数
    var score_pic=new Array('css/img-test/0.png','css/img-test/1.png','css/img-test/2.png','css/img-test/3.png','css/img-test/4.png','css/img-test/5.png',
                            'css/img-test/6.png','css/img-test/7.png','css/img-test/8.png','css/img-test/9.png',);
    function displayScore(){//分数-艺术字形式-显示
        var s=score;
        var score0=s%10;
        var score1=parseInt(s/10)%10;
        var score2=parseInt(s/100)%10;
        var score3=parseInt(s/1000);
        $(".info_score_num img").eq(3).attr('src',score_pic[score0]);
        $(".info_score_num img").eq(2).attr('src',score_pic[score1]);
        $(".info_score_num img").eq(1).attr('src',score_pic[score2]);
        $(".info_score_num img").eq(0).attr('src',score_pic[score3]);
        setTimeout('displayScore()',50);
    }
    displayScore();
    //燃油
    function displayOil(){//对油箱进行显示
        nowOil-=(oilPerSecond/20);
        //变色
        if(nowOil<=100&&nowOil>55)
            $("#main_oil").css('background','green');
        else if(nowOil>=30&&nowOil<=55)
            $("#main_oil").css('background','rgb(209, 90, 20)');
        else if(nowOil>0&&nowOil<=30)
            $("#main_oil").css('background','red');
        
        if(nowOil<=0){//如果没油了,生命数减一,油箱加满
            life--;
            nowOil=100;
            cardInfor(4);
        }
        //油形条变短
        $("#main_oil").css('width',nowOil+'px');
        setTimeout('displayOil()',50);
    }
    displayOil();
    //生命
    $("span")[4].innerHTML="生命 ";
    function displayLife(){//对生命进行显示
        if(life==2){
            $("#life1").attr('src','css/img-test/life2.png');
        }
        else if(life==1){
            $("#life2").attr('src','css/img-test/life2.png');
        }

        if(life==0)//游戏结束时的接口******************************************************************************here
            {cardInfor(6);
            var rs=confirm("重新开始");
                if(rs==true) location.reload();
                else location.reload();
            }
        setTimeout('displayLife()',50);
    }
    displayLife();
/**********************封装子弹**********************************/
    //最近学了一段时间java,对类的运用更得心应手,较上次写的飞机大战里面的子弹类而言,这次的封装更好:子弹的坐标、运动、样式等等
    //但是,碰撞检测更应该写在抽象类里面,通过继承的方式获取,这是我还欠缺、不会的地方

    function Bullet(planeX,planeY){
        //当前坐标bulletx、bullety 子弹大小bulletw、bulleth 子弹三个等级bulletName
        var that=this;

        this.bulletw=20;
        this.bulleth=bulletRanking*4;
        if(bulletRanking==1) this.bulletName='css/img-test/bullet'+bulletType+'.png';
        else if(bulletRanking==2) this.bulletName='css/img-test/bullet'+bulletType+'x.png';
        else if(bulletRanking==3) this.bulletName='css/img-test/bullet'+bulletType+'xx.png';
        this.bulletx =planeX+40;
        this.bullety =planeY+25-(this.bulleth)/2;//设置子弹居飞机的中
        var nowx=this.bulletx;
        
        var img=$(new Image());//添加子弹
        img.attr({
            'src':this.bulletName,
            'class':'bullet'
        });
        img.css({
            'margin-left':this.bulletx+'px',
            'margin-top':this.bullety+'px',
            'height':this.bulleth+'px'
        });
        $("#mainBox").append(img);
        
        this.moveBullet=function(){//子弹移动
            nowx+=6;
            img.css('margin-left',nowx+'px');
            this.bulletx=nowx;
            if(nowx>=1200){//当子弹在页面消失时,移除该对象,防止内存积累
                img.css('display','none');
                img.remove();
            }
            setTimeout(that.moveBullet,20);
        }
        this.moveBullet();
    }


    function myBullet(){//调用myBullet类 生成子弹
        var bu=new Bullet(planeX,planeY);
        setTimeout("myBullet()",300);
    }
    myBullet();
/********敌机:机型、路线、子弹、机组*******************************************/
function ePlane(){
        var that=this;
        var nowx=1180;
        var nowy=getRandom(0,550);
        var ePlaneRouteKey=getRandom(1,3);//飞机路线

        this.ePlanex =nowx;//敌机坐标x
        this.ePlaney =nowy;//敌机坐标y
        this.ePlanew=40;//敌机宽
        this.ePlaneh=50;//敌机高
        this.ePlaneName='css/img-test/ePlane'+getRandom(1,4)+'.png';//敌机样式
        

        var img=$(new Image());//添加敌机
        img.attr({
            'src':this.ePlaneName,
            'class':'ePlane'
        });
        img.css({
            'margin-left':this.ePlanex+'px',
            'margin-top':this.ePlaney+'px'
        });
        $("#mainBox").append(img);

        this.moveEPlane1=function(){//飞机移动路线1--直向左走
            nowx-=4;
            img.css('margin-left',nowx+'px');
            this.ePlanex=nowx;
            if(nowx<=-40){//当飞机在页面消失时,移除该对象,防止内存积累
                img.css('display','none');
                img.remove();
            }
            setTimeout(that.moveEPlane1,20);
        }
        this.moveEPlane2=function(){//飞机移动路线2--斜向左走
            nowx-=4;nowy+=vvv;
            img.css({
                'margin-left':nowx+'px',
                'margin-top':nowy+'px',
                'transform':"rotate("+deg+"deg)"
                });
            this.ePlanex=nowx;this.ePlaney=nowy;
            if(nowx<=-40){
                img.css('display','none');
                img.remove();
            }
            setTimeout(that.moveEPlane2,20);
        }
        this.moveEPlane3=function(){//飞机移动路线3--之字型
            nowx-=4;
            if(l_r_flag==1){
                nowy-=6;
                if(nowy<=0) l_r_flag=2;
            }
            else if(l_r_flag==2){
                nowy+=4;
                if(nowy>=540) l_r_flag=1;
            }
            
            img.css({
                'margin-left':nowx+'px',
                'margin-top':nowy+'px',
                'transform':"rotate("+deg+"deg)"
                });
            this.ePlanex=nowx;this.ePlaney=nowy;
            if(nowx<=-40){
                img.css('display','none');
                img.remove();
            }
            setTimeout(that.moveEPlane3,20);
        }

        //根据随机flag挑选一路线执行
        if(ePlaneRouteKey==1) this.moveEPlane1();
        else if(ePlaneRouteKey==2){
            var endy=getRandom(0,550);
            var tan_deg=(nowy-endy)/1200;
            var vvv=-tan_deg*3;
            var deg=Math.atan(tan_deg)*180/Math.PI;
            console.log(deg);
            this.moveEPlane2();
        }
        else if(ePlaneRouteKey==3){
            var l_r_flag=getRandom(1,2);
            this.moveEPlane3();
        }
        
}

function theePlane(){//调用ePlane类 生成子弹
        var ep=new ePlane();
        setTimeout("theePlane()",1000);
    }
    theePlane();
/********************************碰撞检测:击毁敌机、被击毁************************************/
function isFight(){
        var bullet=$("#mainBox .bullet");
        var ePlane=$("#mainBox .ePlane");
        var icon=$(".icon");
       
        for(var i=0;i<bullet.length;i++){//判断子弹与敌机是否发生碰撞
            //子弹的四周范围
            var b_1=parseInt(bullet.eq(i).css("margin-left"));
            var b_2=parseInt(bullet.eq(i).css("margin-top"));
            var b_3=b_1+20;
            var b_4=b_2+bulletRanking*4;

            //敌机的四周范围
            for(var j=0;j<ePlane.length;j++){
                var e_1=parseInt(ePlane.eq(j).css("margin-left"));
                var e_2=parseInt(ePlane.eq(j).css("margin-top"));
                var e_3=e_1+40;
                var e_4=e_2+50;

                if(isFourInIt(b_1,b_2,b_3,b_4,e_1,e_2,e_3,e_4)){
                    ePlane.eq(j).css('display','none');
                    ePlane.eq(j).remove();
                    bullet.eq(i).css('display','none');
                    bullet.eq(j).remove();
                    score+=10;
                    var audio_boom = document.getElementById('boom');
                    audio_boom.play();

                }
            }
        }

        var p_1=planeX;//判断飞机与敌机是否发生碰撞
        var p_2=planeY;
        var p_3=b_1+40;
        var p_4=b_2+50;
        for(var j=0;j<ePlane.length;j++){
            var e_1=parseInt(ePlane.eq(j).css("margin-left"));
            var e_2=parseInt(ePlane.eq(j).css("margin-top"));
            var e_3=e_1+40;
            var e_4=e_2+50;

            if(isFourInIt(p_1,p_2,p_3,p_4,e_1,e_2,e_3,e_4)){//如果与敌机相撞,生命减一、子弹级别初始化、飞机闪烁2秒
                life--;
                bulletRanking=1;
                ePlane.eq(j).css('display','none');
                ePlane.eq(j).remove();
                shansuo(2);
                cardInfor(4);
            }
        }

        for(var j=0;j<icon.length;j++){//飞机与icon图标碰撞检测
                var i_1=parseInt(icon.css("margin-left"));
                var i_2=parseInt(icon.css("margin-top"));
                var i_3=i_1+40;
                var i_4=i_2+40;

                if(isFourInIt(i_1,i_2,i_3,i_4,p_1,p_2,p_3,p_4)){
                    if(icon.attr('src')=='css/img-test/icon-2.png')//子弹升级
                    {
                        if(bulletRanking==1)
                        bulletRanking++;  
                        else if(bulletRanking==2)
                        bulletRanking++;
                        icon.css('display','none');
                        icon.remove();
                        cardInfor(0);
                    }
                    else if(icon.attr('src')=='css/img-test/icon-1.png')//飞机加速
                    {
                        if(planeMoveSpeed>=3&&planev<=5)
                        {
                            planeMoveSpeed++;
                        }
                        icon.css('display','none');
                        icon.remove();
                        cardInfor(2);
                    }
                    else if(icon.attr('src')=='css/img-test/icon-3.png')//更换子弹
                    {
                        var btflag=getRandom(1,3);
                        while(bulletType==btflag){
                            btflag=getRandom(1,3);
                        }
                        bulletType=btflag;
                        icon.css('display','none');
                        icon.remove();
                        cardInfor(3);
                    }
                    else if(icon.attr('src')=='css/img-test/icon-4.png')//油箱加满
                    {
                        nowOil=100;
                        icon.css('display','none');
                        icon.remove();
                        cardInfor(1);
                    }
                }
            }
        setTimeout("isFight()",20);
}
isFight();
/******************************图标:升级子弹、油箱加满、飞机加速、子弹种类*****************************/
function Icon(index){
        var that=this;

        var nowx=1200;
        this.index=index;//1-飞机加速 2-子弹升级 3-更换子弹 4-油箱加满
        this.iconx=nowx;
        this.icony=getRandom(1,560);//y随机
        var img=$(new Image());

        img.attr({
                'src':'css/img-test/icon-'+this.index+'.png',
                'class':'icon'
            });
        img.css({
                'margin-left':this.iconx+'px',
                'margin-top':this.icony+'px'
            });
        $("#mainBox").append(img);

        this.moveIcon=function(){//飞机移动路线1--直向左走
            nowx-=4;
            img.css('margin-left',nowx+'px');
            this.iconx=nowx;
            if(nowx<=-40){//当飞机在页面消失时,移除该对象,防止内存积累
                img.css('display','none');
                img.remove();
            }
            setTimeout(that.moveIcon,20);
        }
        this.moveIcon();
}
async function theIcon_1_2_3(){//生成图标1-3
await sleep(10000);
        var ico1=new Icon(getRandom(1,3));
        setTimeout("theIcon_1_2_3()",10000);
    }
function theIcon_4(){//生成油箱
        var ico2=new Icon(4);
        setTimeout("theIcon_4()",40000);
    }
    theIcon_1_2_3();
    theIcon_4();
  

</script>
</html>

进行下一个游戏的开发!

指尖大冒险、跳一跳升级版html5游戏全代码
“是男人就下一百层”h5游戏全网最详细教学、全代码,js操作

查看我的上一篇飞机大战!

飞机大战html游戏全代码js、jquery操作

注意事项

【1】 原创博客,转载本篇请与我联系,尊重版权。QQ:2864144286
【2】 关于阅读本篇博客的所有问题、代码源码、图片素材、编程技巧、编程经历都可联系我,与我交流讨论。
【3】 本人部分时间承接各种毕业设计、网站编写、微信小程序编写、数据库作业编写。需要请加QQ:2864144286,详聊。

发布了57 篇原创文章 · 获赞 43 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43592352/article/details/103052604