//ui输出
curScoreEle.innerHTML=""+curScore;
maxScoreEle.innerHTML=""+maxScore;
curSpeedEle.innerHTML=curSpeed.toFixed(1);//保留两位小数
clearInterval(timer);
timer=setInterval(function(){
next();
}, 500/curSpeed);
}
}
}
//判断是否触顶
for(let i=0;i<currentFall.length;i++){
if(currentFall[i].y==0){
gameEnd();
return;
}
}
localStorage.setItem("tetris_status", JSON.stringify(tetris_status));
//新的block
createBlock();
localStorage.setItem("currentFall", JSON.stringify(currentFall));
}
drawBlocks();
}
//右移
function moveRight(){
for(let i=0;i<currentFall.length;i++){
if(currentFall[i].x+1>=TETRIS_ROWS || tetris_status[currentFall[i].y][currentFall[i].x+1]!=NO_BLOCK)
return;
}
for(let i=0;i<currentFall.length;i++)
currentFall[i].x++;
localStorage.setItem("currentFall", JSON.stringify(currentFall));
return;
}
//左移
function moveLeft(){
for(let i=0;i<currentFall.length;i++){
if(currentFall[i].x-1<0 || tetris_status[currentFall[i].y][currentFall[i].x-1]!=NO_BLOCK)
return;
}
for(let i=0;i<currentFall.length;i++)
currentFall[i].x--;
localStorage.setItem("currentFall", JSON.stringify(currentFall));
return;
}
//judge can move down and if arrive at end return 1, if touch other blocks return 2, else, return 0
function moveDown(){
for(let i=0;i<currentFall.length;i++){
if(currentFall[i].y>=TETRIS_ROWS-1 || tetris_status[currentFall[i].y+1][currentFall[i].x]!=NO_BLOCK)
return true;
}
for(let i=0;i<currentFall.length;i++)
currentFall[i].y+=1;
return false;
}
上下左右移动
function gameKeyEvent(evt){
switch(evt.keyCode){
//向下
case 40://↓
case 83://S
next();
drawBlocks();
break;
//向左
case 37://←
case 65://A
moveLeft();
drawBlocks();
break;
//向右
case 39://→
case 68://D
moveRight();
drawBlocks();
break;
//旋转
case 38://↑
case 87://W
rotate();
drawBlocks();
break;
}
}keydown事件监听
keydown事件监听
其他的详细情况可以看源代码,我就不整理了。
接下来我们看游戏结束时的特效。因为我也不是很懂,所以在这里整理的会比较详细。当做学习。
//game end
function gameEnd(){
clearInterval(timer);
//键盘输入监听结束
window.onkeydown=function(){
//按任意键重新开始游戏
window.onkeydown=gameKeyEvent;
//初始化游戏数据
initData();
createBlock();
localStorage.setItem("currentFall", JSON.stringify(currentFall));









