標籤:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>坦克大戰</title>
</head>
<body onkeydown="hero.move(event)">
<div id="filed" style="background:#000;width:500px;height:400px;position:absolute;"></div>
<div id="mytank" style="background:url(w.png) no-repeat;width:40px;height:40px;position:absolute;"></div>
<input type="button" value="上">
<input type="button" value="右" >
<input type="button" value="下" >
<input type="button" value="左">
<script type="text/javascript">
// function change(obj){
// if(obj.value=="上"){
// tank.style.backgroundPositionY="0px";
// }else if(obj.value=="右"){
// tank.style.backgroundPositionY="-40px";
// }
// else if(obj.value=="下"){
// tank.style.backgroundPositionY="-80px";
// }
// else if(obj.value=="左"){
// tank.style.backgroundPositionY="-120px";
// }
// }
//用物件導向的方法開發,web版本的坦克大戰,可以通過asdw鍵來控制坦克的走向
function MyTank(x,y,direct){
this.x=x;//坦克的橫座標
this.y=y;//坦克的縱座標
this.speed=3;//速度
//初始化
mytank.style.left=this.x+"px";
mytank.style.top=this.y+"px";
mytank.style.backgroundPositionY="0px";
//event表示按鍵事件
this.move=function move(event){
//a表示左 3
//s表示下 2
//d表示右 1
//w表示上 0
switch (event.keyCode){
case 65:
//a表示左
this.x-=this.speed;
this.direct=3;
mytank.style.backgroundPositionY="-120px";
break;
case 83:
//S表示向下 2
this.y+=this.speed;
this.direct=2;
mytank.style.backgroundPositionY="-80px";
break;
case 68:
//d表示右 1
this.x+=this.speed;
this.direct=1;
mytank.style.backgroundPositionY="-40px";
break;
case 87:
//w表示上 0
this.y-=this.speed;
this.direct=0;
mytank.style.backgroundPositionY="0px";
break;
}
//統一改變位置
mytank.style.left=this.x+"px";
mytank.style.top=this.y+"px";
}
}
//建立坦克
var hero=new MyTank(200,360,0)
</script>
</body>
</html>
例子:web版坦克大戰1.0