var board = new Array();
var scroe = 0;
$(document).ready(function(){
newgame();
});
function newgame() {
// 初始化棋盘格
init();
//在随机两个格子生成数字
generateOneNumber();
generateOneNumber();
}
function init(){
for(var i = 0 ; i < 4 ; i ++ ){
for(var j = 0 ; j < 4 ; j ++ ){
var gridCell = $("#grid-cell-"+i+"-"+j);
gridCell.css('top', getPosTop( i , j ) );
gridCell.css('left', getPosLeft( i , j ) );
}
}
for(var i = 0 ; i < 4 ; i ++ ){
board[i] = new Array();
for(var j = 0 ; j < 4 ; j ++ ){
board[i][j] = 0;
}
}
updateBoardView();
score = 0;
console.table(board);
}
function updateBoardView(){
$(".number-cell").remove();
for(var i = 0 ; i < 4 ; i ++ ){
for(var j = 0 ; j < 4 ; j ++ ){
$("#grid-container").append('<div class="number-cell" id="number-cell-'+i+'-'+j+'">');
var theNumberCell = $('#number-cell-'+i+'-'+j);
if( board[i][j] == 0 ){
theNumberCell.css('width',0);
theNumberCell.css('height',0);
theNumberCell.css('top', getPosTop(i,j)+50 );
theNumberCell.css('left', getPosLeft(i,j)+50 );
}else{
theNumberCell.css('width',100);
theNumberCell.css('height',100);
theNumberCell.css('top', getPosTop(i,j) );
theNumberCell.css('left', getPosLeft(i,j) );
theNumberCell.css('background-color',getNumberBgColor( board[i][j] ) );
theNumberCell.css('color',getNumberColor( board[i][j] ) );
theNumberCell.text( board[i][j] );
}
}
}
}
function generateOneNumber(){
if( noSpace( board ))
return false;
//随机一个位置
var randx = parseInt( Math.floor( Math.random()*4 ) );
var randy = parseInt( Math.floor( Math.random()*4 ) );
while( true ){
if ( board[randx][randy] == 0 ) break;
var randx = parseInt( Math.floor( Math.random()*4 ) );
var randy = parseInt( Math.floor( Math.random()*4 ) );
}
//随机一个数字
var randNumber = Math.random() < 0.5 ? 2 : 4 ;
//在随机位置显示随机数字
board[randx][randy] = randNumber;
showNumberWithAnimation( randx, randy, randNumber );
return true;
}
$(document).keydown(function(event){
switch( event.keyCode ){
case 37: //左
if( moveLeft() ){
generateOneNumber();
isGameOver();
};
break;
case 38: //上
if( moveTop() ){
generateOneNumber();
isGameOver();
};
break;
case 39: //右
if( moveRight() ){
generateOneNumber();
isGameOver();
};
break;
case 40: //下
if( moveDown() ){
generateOneNumber();
isGameOver();
};
break;
default: //默认
break;
}
console.table(board);
});
function isGameOver(){
}
function moveLeft(){
if( !canMoveLeft( board ) )
return false;
//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[j][k] == 0 && noBlockHorizontal( 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] && noBlockHorizontal(i,k,j,board) ){
//move
showMoveAnimation(i,j,i,k);
//add
board[i][k] += board[i][j];
board[i][j] = 0;
//add score
score += board[i][k];
updateScore( score );
continue;
}
setTimeout("updateBoardView()",200);
return true;
}