I am trying to fill a game board (8 by 8) with random game pieces (images), but not the entire board is filled. Some will be empty. To do so, I am randomly generating x,y coordinates on the board and assigning a random number to it. Since fillBoard is private function in a module, I am copy it over to copyBoard, which is public function.
The idea is to randomly generate an x,y coordinate and put it in an array[x], array[y]. I am having trouble copying the array array though, since not all of them is defined. I was wondering how do you do so?
Here’s what I got so far. Its displaying an error because splice() cannot work for an undefined variable.
function fillBoard(){
var x, y;
monsters=[]; //empty array
x = Math.floor(Math.random()*cols);
y = Math.floor(Math.random()*rows);
monsters[x] = []; /* making x variable an array */
monsters[x][y] = Math.floor(Math.random() * numMonsterTypes);
}
function copyBoard() {
var copy = [],
x;
for (x = 0; x < cols; x++) {
if(monsters[x]){
copy[x] = monsters[x].slice(0); //slice(array) -> returns the selected elements in an array
};
};
return copy;
}
Here’s the solution: