代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{
width: 500px;
margin:20px auto;
}
div.content{
height: 300px;
border:1px solid red;
position: relative;
}
span{
color: red;
font-size: 20px;
}
img{
position: absolute;
}
img:last-child{
margin-top: 60px;
}

</style>
<script type="text/javascript">
window.onload=function(){
var btns=document.getElementsByTagName('button');
var imgs=document.images;
var span=document.getElementsByTagName("span")[0];

//手动移动
btns[0].onclick=function(){
imgs[0].style.left=imgs[0].offsetLeft+10+"px";
}

//发射
btns[1].onclick=function(){
var num=Number(span.innerHTML);


var id=setInterval(function(){
span.innerHTML= --num;
if(num==0){
clearInterval(id);

imgs[0].style.left=imgs[0].offsetLeft+100+"px";
}
},1000);
//赛跑
btns[2].onclick=function(){
var id=setInterval(function(){
var random1=Math.round(Math.random()*10);
var random2=Math.round(Math.random()*10);
imgs[0].style.left=imgs[0].offsetLeft+random1+"px";
imgs[1].style.left=imgs[1].offsetLeft+random2+"px";

if(imgs[0].offsetLeft>400 || imgs[1].offsetLeft>400){
clearInterval(id);
if(imgs[0].offsetLeft>400){
alert("tanke1胜出");
}else{
alert("tanke2胜出");
}
}
},100);
}

//自动移动
function run(){
var tanke1=imgs[0];
var id0=setInterval(function(){
tanke1.style.left=tanke1.offsetLeft+10+"px";
if(tanke1.offsetLeft>390){
clearInterval(id0);
tanke1.src='tanke_down.jpg';
var id1=setInterval(function(){
tanke1.style.top=tanke1.offsetTop+10+"px";
if(tanke1.offsetTop>200){
clearInterval(id1);
tanke1.src='tanke_left.jpg';

var id2=setInterval(function(){
tanke1.style.left=tanke1.offsetLeft-10+"px";
if(tanke1.offsetLeft<10){
clearInterval(id2);
tanke1.src='tanke_up.jpg'
var id3=setInterval(function(){
tanke1.style.top=tanke1.offsetTop-10+"px";
if(tanke1.offsetTop<10){
clearInterval(id3);
tanke1.src='tanke_right.jpg';

run();
}
},100)
}
},100)
}
},100);
}
},100);


}
btns[3].onclick=run;
}
</script>
</head>
<body>
<div>
<button>手动移动</button>
<button>发射</button>
<button>赛跑</button>
<button>自动移动</button>
<span>5</span>
</div>
<div>
<img src="tanke_right.jpg" alt=""> <br>

<img src="tanke_right.jpg" alt="">
</div>
</body>
</html>

最后实现的效果图如下图所示:

用所学JS的知识做一个简单的坦克小游戏_游戏开发

能:这个网络游戏实现了对小坦克的手动移动、自动移动、赛跑以及发射的功能,其中发射还加入了倒计时的属性。

点击手动移动第一个小坦克会向右移动一小段距离,具体移动的距离根据所设置的值来确定。

点击发射会进入5秒倒计时,倒计时结束后第一个小坦克会向右瞬间移动一段距离,具体移动多少距离也需要看自己的设置。

点击赛跑两个小坦克会向右同时出发,通过间歇调用的设置,两个坦克会在某个时间随机移动随机的距离,直到某一方将要贴近边框线则停下且胜出,同时弹框显示。

点击自动移动第一个小坦克会向右出发,直至将要碰到右边框线时向下转向,接着将要碰到下边框线时向左转向,然后在将要碰到左边框线时向上转向,最后在将要碰到上边框线时向右转向,依次循环(移动的具体位置也需自己设置)。