俄罗斯方块类
以下代码包括了俄罗斯方块生成以及上下左右旋转的操作。
完整代码在github上: [俄罗斯方块小游戏源码](https://github.com/suchuanpao/tetris.git)
function Tetris (pos, type, dir) {
this .turn = function () {
var flag = 1 ;
switch (this .types_name[this .type]) {
case "SQUARE" :
return true ;
case "LINE" :
flag = this .tetris[1 ].y-this .centor.y?1 :-1 ;
break ;
case "SWAGERLY" :
case "RSWAGERLY" :
flag = this .tetris[2 ].y-this .centor.y?1 :-1 ;
break ;
case "LBLOCK" :
case "RLBLOCK" :
case "TBLOCK" :
flag = 1 ;
break ;
}
for (var i = 1 ; i < this .tetris.length; i++) {
var diff = {"x" :this .tetris[i].x-this .centor.x, "y" :this .tetris[i].y-this .centor.y};
this .tetris[i].x = this .centor.x + flag*diff.y;
this .tetris[i].y = this .centor.y - flag*diff.x;
}
return true ;
}
this .turnback = function () {
if (this .types_name[this .type] == "SQUARE" )
return true ;
for (var i = 0 ; i < 3 ; i++)
this .turn();
}
this .leftSlice = function () {
this .pos.x--;
}
this .rightSlice = function () {
this .pos.x++;
}
this .drop = function () {
this .pos.y++;
}
this .rise = function () {
this .pos.y--;
}
this .body = function () {
var body = [];
for (var i = 0 ; i < this .tetris.length; i++) {
if (this .tetris[i].y+this .pos.y >= 0 )
body.push({"x" :this .tetris[i].x+this .pos.x, "y" :this .tetris[i].y+this .pos.y});
}
return body;
}
this .__init__ = function () {
var arr = this .types_body[this .type];
this .tetris = [];
this .centor = {"x" :arr[0 ]%4 -this .origin%4 , "y" :parseInt (arr[0 ]/4 )-parseInt (this .origin/4 )};
for (var i = 0 ; i < 4 ; i++) {
this .tetris[i] = {"x" :arr[i]%4 -this .origin%4 , "y" :parseInt (arr[i]/4 )-parseInt (this .origin/4 )};
}
}
this .types_name = ["LBLOCK" , "RLBLOCK" , "TBLOCK" , "SWAGERLY" , "RSWAGERLY" , "LINE" , "SQUARE" ];
this .types_body = [
[5 , 1 , 2 , 9 ],
[6 , 1 , 2 ,10 ],
[5 , 1 , 4 , 6 ],
[5 , 2 , 6 , 9 ],
[5 , 1 , 6 ,10 ],
[5 , 4 , 6 , 7 ],
[5 , 0 , 1 , 4 ],
]
this .origin = 5 ;
this .type = type%7 ;
this .pos = pos;
this .__init__();
for (i = 0 ; i < dir%4 ; i++)
this .turn();
return this ;
}