>  기사  >  웹 프론트엔드  >  Xiaoqiang의 HTML5 모바일 개발 과정(9) – 탱크 배틀 게임 3

Xiaoqiang의 HTML5 모바일 개발 과정(9) – 탱크 배틀 게임 3

黄舟
黄舟원래의
2017-01-22 11:18:131241검색

이전 기사에서는 적의 탱크와 우리의 탱크를 생성했습니다. 다음으로 우리 탱크가 총알을 발사하도록 해야 합니다.

이전에는 탱크를 캡슐화하기 위해 객체 지향적 사고를 사용했고, 우리 탱크와 적의 탱크를 구현하기 위해 객체 가장을 사용했습니다. 이 방법에 따라 총알도 캡슐화해야 할까요? 좋습니다. 그러면 이 Bullet "클래스"가 무엇을 캡슐화해야 하는지 생각해 보겠습니다. 위치가 있어야 하고, 총알이 날아가는 방향이 있어야 하고, 날아가는 속도가 있어야 하고, 스스로 날아가는 동작이 있어야 한다. 좋습니다. 캡슐화된 Bulle "t 클래스"는 다음과 같습니다.

//子弹类  
function Bullet(x,y,direct,speed){  
    this.x=x;  
    this.y=y;  
    this.speed=speed;  
    this.direct=direct;  
    this.timer=null;  
    this.run=function(){  
        switch(this.direct){  
            case 0:  
                this.y-=this.speed;  
                break;  
            case 1:  
                this.x+=this.speed;  
                break;  
            case 2:  
                this.y+=this.speed;  
                break;  
            case 3:  
                this.x-=this.speed;  
                break;    
        }  
          
    }  
}

다음으로 탱크를 사용하여 총알을 생성하고 Hero 클래스로 보냅니다. ShotEnemy 메소드를 추가합니다.

//定义一个Hero类  
function Hero(x,y,direct,color){  
    //下面两句话的作用是通过对象冒充达到继承的效果  
    this.tank=Tank;  
    this.tank(x,y,direct,color);  
    //射击敌人函数  
    this.shotEnemy=function(){  
        switch(this.direct){  
            case 0:  
                heroBullet=new Bullet(this.x+10,this.y,this.direct,1);  
                break;  
            case 1:  
                heroBullet=new Bullet(this.x+30-4,this.y+10+4,this.direct,1);  
                break;  
            case 2:  
                heroBullet=new Bullet(this.x+10,this.y+30,this.direct,1);  
                break;  
            case 3:  
                heroBullet=new Bullet(this.x-4,this.y+10+4,this.direct,1);  
                break;  
        }  
        //把这个子弹放入数组中——》push函数  
        //调用我们子弹的run  
        //var timer=window.setInterval("heroBullet.run()",50);  
        //heroBullet.timer=timer;  
        heroBullets.push(heroBullet);  
        var timer=window.setInterval("heroBullets["+(heroBullets.length-1)+"].run()",50);  
        heroBullets[heroBullets.length-1].timer=timer;  
          
    }  
}

키 듣기 기능에서 총알 발사를 들으려면 키 "J"를 추가하세요.

case 74: //J  :发子弹  
    hero.shotEnemy();  
    break;

자, 총알 발사를 해보세요! 왜 총알은 한 발만 발사될 수 있는데 점점 빨라지는 걸까요? 위에서 작성한 코드를 보면 총알이 발사되면 멈출 수 없으며 두 번째 총알이 발사되면 여전히 한 방향으로 달리고 있습니다. bullet will 인터페이스를 새로 고칠 때 글머리 기호가 다시 그려지지 않기 때문에 사라집니다. 좋아, 이제 이유를 알았으니 총알이 범위를 벗어났는지 확인한 다음 총알에 isLive 상태를 지정해 보겠습니다. 이 상태는 총알이 존재하는지 여부를 표시하며 존재하지 않으면 총알이 다시 그려지지 않습니다. 글머리 기호가 다시 그려집니다) 수정된 코드는 다음과 같습니다.

//子弹类  
unction Bullet(x,y,direct,speed){  
this.x=x;  
this.y=y;  
this.speed=speed;  
this.direct=direct;  
this.timer=null;  
this.isLive=true;  
this.run=function(){  
    //判断子弹是否已经到边界了  
    if(this.x<=0||this.x>=400||this.y<=0||this.y>=300){  
        //子弹要停止  
        window.clearInterval(this.timer);  
        //子弹死亡  
        this.isLive=false;  
    }else{  
        //可以去修改坐标  
        switch(this.direct){  
            case 0:  
                this.y-=this.speed;  
                break;  
            case 1:  
                this.x+=this.speed;  
                break;  
            case 2:  
                    break;    
        }  
    }  
}

글머리 기호가 캔버스 범위를 초과하는 경우 isLive 속성을 false


로 설정합니다. 그런 다음 이전 새로 고침 인터페이스 함수

//定时刷新我们的作战区(定时重绘)  
//自己的坦克,敌人坦克,子弹,炸弹,障碍物  
function flashTankMap(){  
    //把画布清理  
    cxt.clearRect(0,0,400,300);  
    //我的坦克  
    drawTank(hero);  
    //我的子弹  
    drawHeroBullet();  
    //敌人的坦克  
    for(var i=0;i<3;i++){  
        drawTank(enemyTanks[i]);  
    }  
}
//画出自己的子弹  
function drawHeroBullet(){  
    for(var i=0;i<heroBullets.length;i++){  
        var heroBullet=heroBullets[i];  
        if(heroBullet!=null&&heroBullet.isLive){  
            cxt.fillStyle="#FEF26E";  
            cxt.fillRect(heroBullet.x,heroBullet.y,2,2);  
        }  
    }  
}

에 새로 고침 글머리 기호 함수를 추가합니다. 위의 drawHeroBullet에서 글머리 기호의 isLive 속성이 결정되는 것을 볼 수 있습니다.


실행 결과를 살펴보자

Xiaoqiang의 HTML5 모바일 개발 과정(9) – 탱크 배틀 게임 3

전체 소스코드는 다음과 같다.

tankGame06.js

//为了编程方便,我们定义两个颜色数组  
var heroColor=new Array("#BA9658","#FEF26E");  
var enemyColor=new Array("#00A2B5","#00FEFE");  
  
    //子弹类  
function Bullet(x,y,direct,speed){  
    this.x=x;  
    this.y=y;  
    this.speed=speed;  
    this.direct=direct;  
    this.timer=null;  
    this.isLive=true;  
    this.run=function(){  
        //判断子弹是否已经到边界了  
        if(this.x<=0||this.x>=400||this.y<=0||this.y>=300){  
            //子弹要停止  
            window.clearInterval(this.timer);  
            //子弹死亡  
            this.isLive=false;  
        }else{  
            //可以去修改坐标  
            switch(this.direct){  
                case 0:  
                    this.y-=this.speed;  
                    break;  
                case 1:  
                    this.x+=this.speed;  
                    break;  
                case 2:  
                    this.y+=this.speed;  
                    break;  
                case 3:  
                    this.x-=this.speed;  
                    break;    
            }  
        }  
    }  
}  
  
//定义一个Tank类(基类)  
function Tank(x,y,direct,color){  
    this.x=x;  
    this.y=y;  
    this.speed=1;  
    this.direct=direct;  
    this.color=color;  
    //上移  
    this.moveUp=function(){  
        this.y-=this.speed;  
        this.direct=0;  
    }  
    //右移  
    this.moveRight=function(){  
        this.x+=this.speed;  
        this.direct=1;  
    }  
    //下移  
    this.moveDown=function(){  
        this.y+=this.speed;  
        this.direct=2;  
    }  
    //左移  
    this.moveLeft=function(){  
        this.x-=this.speed;  
        this.direct=3;  
    }  
}  
  
//定义一个Hero类  
function Hero(x,y,direct,color){  
    //下面两句话的作用是通过对象冒充达到继承的效果  
    this.tank=Tank;  
    this.tank(x,y,direct,color);  
    //设计敌人函数  
    this.shotEnemy=function(){  
        switch(this.direct){  
            case 0:  
                heroBullet=new Bullet(this.x+10,this.y,this.direct,1);  
                break;  
            case 1:  
                heroBullet=new Bullet(this.x+30-4,this.y+10+4,this.direct,1);  
                break;  
            case 2:  
                heroBullet=new Bullet(this.x+10,this.y+30,this.direct,1);  
                break;  
            case 3:  
                heroBullet=new Bullet(this.x-4,this.y+10+4,this.direct,1);  
                break;  
        }  
        //把这个子弹放入数组中——》push函数  
        //调用我们子弹的run  
        //var timer=window.setInterval("heroBullet.run()",50);  
        //heroBullet.timer=timer;  
        heroBullets.push(heroBullet);  
        var timer=window.setInterval("heroBullets["+(heroBullets.length-1)+"].run()",50);  
        heroBullets[heroBullets.length-1].timer=timer;  
          
    }  
}  
  
//定义一个EnemyTank类  
function EnemyTank(x,y,direct,color){  
    this.tank=Tank;  
    this.tank(x,y,direct,color);  
}  
  
    //绘制坦克  
function drawTank(tank){  
    //考虑方向  
    switch(tank.direct){  
        case 0:     //向上  
        case 2:     //向下  
            //设置颜色  
            cxt.fillStyle=tank.color[0];  
            //左边的矩形  
            cxt.fillRect(tank.x,tank.y,5,30);  
            //右边的矩形  
            cxt.fillRect(tank.x+17,tank.y,5,30);  
            //画中间的矩形  
            cxt.fillRect(tank.x+6,tank.y+5,10,20);  
            //画出坦克的盖子  
            cxt.fillStyle=tank.color[1];  
            cxt.arc(tank.x+11,tank.y+15,5,0,Math.PI*2,true);  
            cxt.fill();  
            //画出炮筒  
            cxt.strokeStyle=tank.color[1];  
            cxt.lineWidth=1.5;  
            cxt.beginPath();  
            cxt.moveTo(tank.x+11,tank.y+15);  
            if(tank.direct==0){         //只是炮筒的方向不同  
                cxt.lineTo(tank.x+11,tank.y);  
            }else{  
                cxt.lineTo(tank.x+11,tank.y+30);  
            }  
            cxt.closePath();  
            cxt.stroke();  
            break;  
        case 1:  
        case 3:  
            //设置颜色  
            cxt.fillStyle="#BA9658";  
            //上边的矩形  
            cxt.fillRect(tank.x-4,tank.y+4,30,5);  
            //下边的矩形  
            cxt.fillRect(tank.x-4,tank.y+17+4,30,5);  
            //画中间的矩形  
            cxt.fillRect(tank.x+5-4,tank.y+6+4,20,10);  
            //画出坦克的盖子  
            cxt.fillStyle="#FEF26E";  
            cxt.arc(tank.x+15-4,tank.y+11+4,5,0,Math.PI*2,true);  
            cxt.fill();  
            //画出炮筒  
            cxt.strokeStyle="#FEF26E";  
            cxt.lineWidth=1.5;  
            cxt.beginPath();  
            cxt.moveTo(tank.x+15-4,tank.y+11+4);  
            if(tank.direct==1){         //只是炮筒的方向不同  
                cxt.lineTo(tank.x+30-4,tank.y+11+4);  
            }else{  
                cxt.lineTo(tank.x-4,tank.y+11+4);  
            }  
            cxt.closePath();  
            cxt.stroke();  
            break;    
    }  
      
}

Tank Battle.html

<!DOCTYPE html>  
<html>  
<head>  
<meta charset="utf-8"/>  
</head>  
<body onkeydown="getCommand();">  
<h1>html5-坦克大战</h1>  
<!--坦克大战的战场-->  
<canvas id="tankMap" width="400px" height="300px" style="background-color:black"></canvas>  
<!--将tankGame04.js引入-->  
<script type="text/javascript" src="tankGame06.js"></script>  
<script type="text/javascript">  
    //得到画布  
    var canvas1=document.getElementById("tankMap");  
    //得到绘图上下文  
    var cxt=canvas1.getContext("2d");  
      
    //我的tank  
    //规定0向上、1向右、2向下、3向左  
    var hero=new Hero(40,40,0,heroColor);  
    //定义子弹数组  
    var heroBullets=new Array();  
    //敌人的tank  
    var enemyTanks=new Array();  
    for(var i=0;i<3;i++){  
        var enemyTank = new EnemyTank((i+1)*50,0,2,enemyColor);  
        enemyTanks[i]=enemyTank;      
    }  
      
    //画出自己的子弹  
    function drawHeroBullet(){  
        for(var i=0;i<heroBullets.length;i++){  
            var heroBullet=heroBullets[i];  
            if(heroBullet!=null&&heroBullet.isLive){  
                cxt.fillStyle="#FEF26E";  
                cxt.fillRect(heroBullet.x,heroBullet.y,2,2);  
            }  
        }  
    }  
      
    //定时刷新我们的作战区(定时重绘)  
    //自己的坦克,敌人坦克,子弹,炸弹,障碍物  
    function flashTankMap(){  
        //把画布清理  
        cxt.clearRect(0,0,400,300);  
        //我的坦克  
        drawTank(hero);  
        //我的子弹  
        drawHeroBullet();  
        //敌人的坦克  
        for(var i=0;i<3;i++){  
            drawTank(enemyTanks[i]);  
        }  
    }  
    flashTankMap();  
    //接收用户按键的函数  
    function getCommand(){  
        var code = event.keyCode;  //键盘上字幕的ASCII码  
        switch(code){  
            case 87:  //W   :上  
                hero.moveUp();  
                break;  
            case 68: //D    :右  
                hero.moveRight();  
                break;  
            case 83:  //S   :下  
                hero.moveDown();  
                break;  
            case 65: //A    :左  
                hero.moveLeft();  
                break;  
            case 74: //J  :发子弹  
                hero.shotEnemy();  
                break;  
        }  
        flashTankMap();  
    }  
    //每隔100毫秒去刷新一次作战区  
    window.setInterval("flashTankMap()",100);  
</script>  
</body>  
</html>

위는 Xiaoqiang의 HTML5 모바일 개발 로드(9) - 탱크 배틀 게임 3의 내용입니다. 더 많은 관련 콘텐츠를 보려면 결제하세요. PHP 중국어 홈페이지(www.php.cn)를 주목해주세요!



성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.