```javascript
//坦克类
function Tank(){
this.position={
x:0,
y:0
};
this.direction='up';
this.speed=1;
this.lifeValue = 100;
//在画布上绘制坦克
this.draw = function(){
var oTank = document.createElement('div');
oTank.style.position='absolute';
oTank.style.left = this.position.x +'px';
oTank.style.top = this.position.y +'px';
oTank.style.width='20px';
oTank.style.height='30px';
oTank.style.background='#000';
document.body.appendChild(oTank);
}
//坦克的运动
this.move = function(){
switch(this.direction){
case 'up':
this.position.y-=this.speed;
break;
case 'down':
this.position.y+=this.speed;
break;
case 'left':
this.position.x-=this.speed;
break;
case 'right':
this.position.x+=this.speed;
break;
default:break;
}
},
//坦克方向改变
this.changeDirection = function(direction){
this.direction = direction;
}
this.shot = function(){
//发射子弹
},
this.destory = function(){
//销毁坦克
}
this.takeDamage = function(){
//受伤
this.lifeValue -= 10;
if(this.lifeValue<=0){
this.destory();
}
}
}
//主函数
function main(){
//创建两个坦克
var tank1 = new Tank(),
tank2 = new Tank();
//两辆坦克开始移动
tank1.draw();
tank1.move();
tank2.draw();
tank2.move();
//先进行玩家一的操作
move();
function move(){
document.onkeydown = function(e){
switch(e.keyCode){
case 38:
tank1.changeDirection('up');
break;
case 40:
tank1.changeDirection('down');
break;
case 37:
tank1.changeDirection('left');
break;
case 39:
tank1.changeDirection('right');
break;
case 32:
tank1.shot();
break;
}
}
}
//然后进行玩家二的操作,由电脑AI控制
setInterval(function(){
//生成一个随机的方向
var randomDirection = Math.floor(Math.random()*4);
switch(randomDirection){
case 0:
tank2.changeDirection('up');
break;
case 1:
tank2.changeDirection('down');
break;
case 2:
tank2.changeDirection('left');
break;
case 3:
tank2.changeDirection('right');
break;
default:break;
}
tank2.shot();
},500);
//碰撞检测
function collisionDetection(){
//判断坦克之间的位置,位置重合,则有碰撞
if(tank1.position.x === tank2.position.x && tank1.position.y === tank2.position.y){
tank1.takeDamage();
tank2.takeDamage();
}
}
//子弹碰撞检测
function bulletCollisionDetection(){
//todo:
}
}
main();
```
关注小世学长不迷路,带你见识更多的小程序(小游戏)!!!