按left后,数字不能移动到第一列,数字不能相加
$(document).keydown(function(event){
switch(event.keyCode){
case 37:
if(moveLeft()){
generationOneNumber();
}
break;
case 38:
if(moveUp()){
generationOneNumber();
}
break;
case 39:
if(moveRight()){
generationOneNumber();
}
break;
case 40:
if(moveDown()){
generationOneNumber();
}
break;
default:
break;
}
})
function moveLeft(){
if(!canMoveLeft(board)){
return false;
}
else{
//move left
for(var i=0;i<4;i++){
for(var j=1;j<4;j++){
if(board[i][j]!=0){
for(var k=0;k<j;k++){
if(board[i][k]==0 && noBlockHorizen(i,k,j,board)){
//move
showMoveAnimation(i,j,i,k);
board[i][k]=board[i][j];
board[i][j]=0;
continue;
}
else if(board[i][k]==board[i][j] && noBlockHorizen(i,k,j,board)){
//move
showMoveAnimation(i,j,i,k);
//add
board[i][k]+=board[i][j];
board[i][j]=0;
continue;
}
}
}
}
}
setTimeout("updateBoardView()",200);
return true
}
}
function canMoveLeft(board){
for(var i=0;i<4;i++){
for(var j=1;j<4;j++){
if(board[i][j]!= 0){
if(board[i][j-1]==0 || board[i][j-1]==board[i][j]){
return true;
}
else {
return false;
}
}
}
}
}
function noBlockHorizen(row,rol1,rol2,board){
for(var l=rol1+1;l<rol2;l++){
if(board[row][l]!=0){
return false;
}
else{
return true;
}
}
}