2048游戏的随机单元格中的随机数

时间:2015-03-01 23:05:39

标签: java arrays

我正在尝试在4x4网格板中的随机单元格中创建一个随机数。基本上我正在尝试编写2048游戏,但不知道如何摆脱随机数。随机数应该是2和4,90%是2和10%是4.这是我得到的网格代码:

int[][] board = new int[4][4];  //the size of the board is 4x4
Scanner input = new Scanner(System.in);
String horizontal = "+----+----+----+----+";
String vertical = "\u2502";
//to print out the grid 4x4
System.out.print(horizontal + "\n"); // Top line            

for (int i = 0; i < 4; i++) 
{
    System.out.print(vertical); // first column layout  
    for (int j = 0; j < 4; j++) 
    {
        if (board[i][j] != 0) 
        {
            String sized = Integer.toString(board[i][j]);
            int check = 4 - sized.length();
            for (int k = 0; k < check; k++) 
            {
                System.out.print(" "); // Top line
            }
            System.out.print(board[i][j]);
        } else System.out.print("    ");
        if (j < 3) System.out.print(vertical);  
        else System.out.println(vertical);
    }
    System.out.print(horizontal + "\n"); // Bottom line
}

1 个答案:

答案 0 :(得分:2)

(Math.random() >= .9 ? 4 : 2)

该表达式产生随机数0&lt; = x&lt; 1,然后如果x在0和0.9之间(即概率为90%),则输出2,否则输出4(概率为10%)。