SOURCE

//服务函数
function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min; //不含最大值,含最小值
}

//生成初盘
function generateInit() {
    let board=[
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        []
    ];
    preboard = [
        [1,2,3,4,5,6,7,8,9],
        [4,5,6,7,8,9,1,2,3],
        [7,8,9,1,2,3,4,5,6],
        [2,1,4,3,6,5,8,9,7],
        [3,6,5,8,9,7,2,1,4],
        [8,9,7,2,1,4,3,6,5],
        [5,3,1,6,4,2,9,7,8],
        [6,4,2,9,7,8,5,3,1],
        [9,7,8,5,3,1,6,4,2],
    ];

    for(let i=0;i<9;i++){
        for(let k = 0;k< 9; k++)
        {
            board[i][k] = preboard[i][k];
        }
    }

    let j=[];
    for (let i = 0; i< 12; i++)
    {
        j.push(getRandomInt(0,3))
    }
    for (let i = 0; i < 12; i=i+2)
    {
        if(j[i]===j[i+1]){
            j[i] =( j[i]+1)%3;
        }
    }
    zhongjian = [
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0]
    ];
    for (let n = 0, k = 0; n < 6; n = n + 2, k = k + 3)
    {
        for (let m = 0; m < 9; m++)
        {
            zhongjian[j[n] + k][m] = board[j[n] + k][m];
            board[j[n] + k][m] = board[j[n + 1] + k][m];
            board[j[n + 1] + k][m] = zhongjian[j[n] + k][m];
        }
    }
    for (let n = 6, k = 0; n < 12; n = n + 2, k = k + 3)
    {
        for (let m = 0; m < 9; m++)
        {
            zhongjian[m][j[n] + k] = board[m][j[n] + k];
            board[m][j[n] + k] = board[m][j[n + 1] + k];
            board[m][j[n + 1] + k] = zhongjian[m][j[n] + k];
        }
    }
    let count =getRandomInt(20,31);
    // rand() % 11+20;
    for (let i= 0; i < count; )
    {
        let m, n;
        m=getRandomInt(0,9);
        n=getRandomInt(0,9);
        if(board[m][n] !== 0)
        {
            board[m][n] = 0;
            i++;
        }
    }
    return board;
}

console.log(generateInit())
console 命令行工具 X clear

                    
>
console