為什么會出現在同一個盒子生成數字?
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;
randx = parseInt(Math.floor(Math.random() * 4));
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;
}
2019-12-10
你是想問這段代碼為什么要判斷同一個格子生成兩個數字的情況么?
因為隨機數無法做判重處理,所以得通過一步if操作來進行判斷;
如果格子有數字,那么這個位置的數組值肯定不為0;如果為0,說明這個格子還沒有數字,之后才能往這個位置寫入數字