俄羅斯方塊遊戲
一,遊戲結構
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
html,body{
height: 100%;
overflow: hidden;
}
*{
margin:0px;
padding: 0px;
}
.wrap{
width: 300px;
height: 500px;
background: black;
margin: 100px auto;
position: relative;
}
.square{
width: 20px;
height: 20px;
background: #fff;
position: absolute;
border: 3px solid red;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="wrap">
</div>
</body>
</html>
<script src="js/俄羅斯方塊01.js"></script>
二,遊戲腳本
function ForinGame(){
this.wrap=document.querySelector(".wrap");
this.count=1;
this.rightSwitch=false;
this.shaps=[
[0,0,1,0,2,0,3,0],
[0,0,1,0,1,1,2,1],
[0,0,1,0,2,0,1,1,],
[0,0,1,0,0,1,1,1]
]
this.initShape=function(){
var Index=Math.floor(Math.random()*4);
for(var i=0;i<this.shaps[Index].length/2;i++){
var oS=document.createElement("span");
oS.id="new";
oS.classList.add("square");
oS.style.left=this.shaps[Index][2*i]*20+"px";
oS.style.top=this.shaps[Index][2*i+1]*20+"px";
this.wrap.appendChild(oS);
}
this.dropMove()
}
this.dropMove=function(){
var isEnd=false;
var timer=setInterval(function(){
var all=document.querySelectorAll('#new');
var old=document.querySelectorAll("#old");
if(old.length>=1){
for(var i=0;i<old.length;i++){
for(var j=0;j<all.length;j++){
if(all[j].offsetLeft==old[i].offsetLeft && all[j].offsetTop==old[i].offsetTop-20){
clearInterval(timer);
this.emidtId();
this.initShape();
return;
}
}
}
}
all.forEach(function(item){
item.style.top=item.offsetTop+20+"px";
if(item.offsetTop>=this.wrap.clientHeight-20){
this.emidtId();
clearInterval(timer);
isEnd=true;
}
}.bind(this));
if(isEnd){
isEnd=false;
this.initShape();
}
}.bind(this),500)
}
this.emidtId=function(){
var all=document.querySelectorAll('#new');
all.forEach(function(item){
item.id="old"
})
}
this.toggleShap=function(){
var all=document.querySelectorAll('#new');
var Index=Math.floor(Math.random()*4);
var currentShap=this.shaps[Index];
var initTop=all[0].offsetTop;
var initLeft=all[0].offsetLeft;
for(var i=0;i<all.length;i++){
all[i].style.left=currentShap[2*i]*20+initLeft+"px";
all[i].style.top=currentShap[2*i+1]*20+initTop+"px";
}
}
this.toRight=function(){
var all=document.querySelectorAll('#new');
console.log(all.length)
if(!this.rightSwitch){
this.rightSwitch=false;
all.forEach(function(item){
item.style.left=item.offsetLeft+20+"px";
if(item.offsetLeft>=this.wrap.clientWidth-20){
this.rightSwitch=true;
}
}.bind(this));
}
}
this.toRightLimit=function(){
var all=document.querySelectorAll('#new');
all.forEach(function(item){
})
}
}
var game=new ForinGame();
game.initShape();
document.onkeyup=function(ev){
var ev=ev||event;
switch (ev.keyCode){
case 37:
break;
case 39:
game.toRight();
break;
case 40:
break;
case 13:
game.toggleShap();
break;
}
}
三,遊戲備註
- 此遊戲僅用於學習,培養遊戲開發能力
- 關於圖形變換的思想參考上圖