js制作方块游戏

<!doctype html>
<html lang= "en" >
<head>
     <meta charset= "UTF-8"  />
     <meta http-equiv= "X-UA-Compatible"  content= "IE=edge,chrome=1"  />
     <title> 页面名称 </title>
<style type= "text/css" >
#box {
     width: 800px;
     height: 800px;
     position: relative;
     border: 5px solid  #999;
}
#box div {
     width: 5px;
     height: 5px;
     margin-left: -2px;
     margin-top: -2px;
     position: absolute;
     transition: left 2s linear,top 2s linear;
     animation: an 10s linear forwards;
}
@keyframes an {
       0% { transform:scale(1); background-color:  #0f0; }
     100% { transform:scale(2); background-color:  #f00; }
}
</style>
</head>
<body>
<div id= "box" ></div>
<script type= "text/javascript" >
var  box = document.getElementById( "box" );
var  ds = box.getElementsByTagName( "div" );
setInterval( function (){
     var  div = document.createElement( "div" );
     div.x = Math.floor(Math.random()*780)+10;
     div.y = Math.floor(Math.random()*780)+10;
     div.time =  new  Date().getTime();
     box.appendChild(div);
     for  ( var  arr = []; arr.push([])<16;);
     for  ( var  v,i=-1; v=ds[++i];) {
         v.x += Math.floor(Math.random()*10)-5;
         v.y += Math.floor(Math.random()*10)-5;
         if (v.x<10) v.x=10;
         if (v.y<10) v.y=10;
         if (v.x>790) v.x=790;
         if (v.y>790) v.y=790;
         v.style.left = v.x+ "px" ;
         v.style.top = v.y+ "px" ;
         arr[Math.floor(v.y/200)*4+Math.floor(v.x/200)].push(v);
     }
     for  ( var  v,i=-1; v=arr[++i];) {
         if  (v.length>10) {
             v.sort( function (a,b){
                 return  a.time - b.time;
             });
             box.removeChild(v[0]);
         }
     }
}, 2000);
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_42336593/article/details/80637117
今日推荐