HTML5实现经典坦克大战坦克乱走还能发出一个子弹

2020-04-24 19:01:20易采站长站整理

flashTankMap();
//重新绘制所有的敌人的坦克.你可以在这里写代码(思想,我们干脆些一个函数,专门用于定时刷新我们的画布[作战区])
}
//每隔100毫秒去刷新一次作战区
window.setInterval(“flashTankMap()”,100);
</script>
</body>
</html></pre>

tank.js


<pre></pre>
<pre name=”code” class=”html”><pre name=”code” class=”javascript”>//为了编程方便,我们定义两个颜色数组
var heroColor=new Array(“#BA9658″,”#FEF26E”);
var enmeyColor=new Array(“#00A2B5″,”#00FEFE”);
//其它的敌人坦克,这里的扩展性,还是不错的.
//子弹类
function Bullet(x,y,direct,speed){
this.x=x;
this.y=y;
this.direct=direct;
this.speed=speed;
this.timer=null;
this.isLive=true;
this.run=function run(){
//在该表这个子弹的坐标时,我们先判断子弹是否已经到边界
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;
}
}
document.getElementById(“aa”).innerText=”子弹x=”+this.x+” 子弹y=”+this.y;
}
}
//这是一个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类
//x 表示坦克的 横坐标, y 表示纵坐标, direct 方向
function Hero(x,y,direct,color){
//下面两句话的作用是通过对象冒充,达到继承的效果
this.tank=Tank;
this.tank(x,y,direct,color);
//增加一个函数,射击敌人坦克.
this.shotEnemy=function(){
//创建子弹, 子弹的位置应该和hero有关系,并且和hero的方向有关.!!!
//this.x 就是当前hero的横坐标,这里我们简单的处理(细化)
switch(this.direct){
case 0:
heroBullet=new Bullet(this.x+9,this.y,this.direct,1);
break;
case 1:
heroBullet=new Bullet(this.x+30,this.y+9,this.direct,1);