2048小游戏(JavaScript版) (4) 初始化数字格

1. 初始化数字格

棋盘格初始化完成后,我们还需要用一个格子来显示数字。

而用来显示数字的格子应该在棋盘格的基础上的,所以初始化数字格的updateBoardView()应该在初始化棋盘格的init()方法的最后来执行。

function init() {
    //i表示4乘以4的格子的行
    for(var i=0;i<4;i++){//初始化格子数组
        //定义了一个二维数组
        board[i] = new Array();
        //i表示4乘以4的格子的列
        for(var j=0;j<4;j++){
            //初始化小格子的值为0
            board[i][j] = 0;
            //通过双重遍历获取每个格子元素
            var gridCell= document.getElementById("grid-cell-" + i + "-" + j)
//            console.log(gridCell)
            //通过getPosTop()方法设置每个格子距离顶端的距离
            gridCell.style.top = getPosTop(i, j);
            //通过getPosLeft()方法设置每个格子距离左端的距离
              gridCell.style.left = getPosLeft(i, j);
        }
    }
    updateBoardView();//通知前端对board二位数组进行设定。
}

function updateBoardView() {//更新数组的前端样式

}

因为显示数字的格子也是4×4的16个格子,所以我们直接就和init()方法一样,利用嵌套for循环的方式实现每个数字格的设置。

然后就向棋盘格上增加数字格:

function updateBoardView() {//更新数组的前端样式
    for (var i = 0; i < 4; i++) {
        for (var j = 0; j < 4; j++) {
            //向棋盘格上增加数字格
            var para=document.createElement("div");
            para.setAttribute("class", "number-cell")
            para.setAttribute("id", "number-cell-" + i + "-" + j)
            var element=document.getElementById("grid-container");
            element.appendChild(para);
        }
    }
}

然后再通过判断棋盘的值来设置数字格的高和宽,如果值为0,那么数字格的数字格的高和宽都设置为0,如果值不为0的话,则设置数字格的高和宽并设置背景色和前景色及数字值。

var theNumberCell = document.getElementById('number-cell-' + i + '-' + j)
                
//棋盘的值为0的话,数字格的高和宽都设置为0
if (board[i][j] == 0) {
    theNumberCell.style.width = '0rem';
    theNumberCell.style.height = '0rem';
    theNumberCell.style.top = getPosTop(i, j);
    theNumberCell.style.left = getPosLeft(i, j);
//棋盘的值不为0的话,则设置数字格的高和宽并设置背景色和前景色及数字值    
} else {
    theNumberCell.style.width = '4rem';
    theNumberCell.style.hegiht = '4rem';
    theNumberCell.style.top = getPosTop(i, j);
    theNumberCell.style.left = getPosLeft(i, j);
    //NumberCell覆盖
    theNumberCell.style.backgroundcolor = getNumberBackgroundColor(board[i][j]);//返回背景色
    theNumberCell.style.color = getNumberColor(board[i][j]);//返回前景色
    theNumberCell.innerHTML = board[i][j];
}

保存刷新网页:

这样就完成了数字格的添加以及样式的设置。 

原文地址:https://www.cnblogs.com/liuhui0308/p/14423639.html