HTML and CSS Reference
In-Depth Information
function randomizeBoard(board) {
var newBoard = new Array();
var cols = board.length;
var rows = board[0].length
Next, we loop through every column and row, randomly choosing a piece from the
board array and moving it into newBoard :
for (var i = 0; i < cols; i++) {
We use two nested for:next loops here once again.
Every time we come to an iteration of the outer nested loop, we create a new array that
we will fill up in the second nested loop. Then we drop into that nested loop. The
found variable will be set to true when we have found a random location to place the
piece in the newBoard array. The rndRow and rndCol variables hold the random values
we will create to try and find a random location for the puzzle pieces:
newBoard[i] = new Array();
for (var j =0; j < rows; j++) {
var found = false;
var rndCol = 0;
var rndRow = 0;
Now we need to find a location in newBoard in which to put the puzzle piece from the
board array. We use a while() loop that continues to iterate as long as the found variable
is false . To find a piece to move, we randomly choose a row and column, and then use
them to see whether that space ( board[rndCol][rndRow] ) is set to false . If it is not
false , we have found a piece to move to the newBoard array. We then set found equal
to true so we can get out of the while() loop and move to the next space in newBoard
that we need to fill:
while (!found) {
var rndCol = Math.floor(Math.random() * cols);
var rndRow = Math.floor(Math.random() * rows);
if (board[rndCol][rndRow] != false) {
found = true;
Finally, we move the piece we found in board to the current location we are filling in
newBoard . Then, we set the piece in the board array to false so that when we test for the
next piece, we won't try to use the same piece we just found. When we are done filling
up newBoard , we return it as the newly randomized array of puzzle pieces:
newBoard[i][j] = board[rndCol][rndRow];
board[rndCol][rndRow] = false;
Search WWH ::

Custom Search