I have a function that I'm using to build an array-based grid for a game. It takes in a "blank" 8x8 array as follows:
const initialBoardState = [
[['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
[['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
[['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
[['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
[['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
[['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
[['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
[['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']]
]
I've written a function generateBoard to assign ['O'] at two random coordinates on the array.
Simply put, the function adds a single ['O'], then calls itself again with the intention of adding a second ['O'].
There is a count variable that counts how many times the function is executed. Because I only want two ['O'], the function terminates when count>1
However, the function is returning a grid with only one ['O']. Thoughts as to what I've done wrong?
Function:
let xRandomValue;
let yRandomValue;
let coordinates = [];
const generateBoard = (board) => {
let count = 0
xRandomValue = Math.floor(Math.random() * 8);
yRandomValue = Math.floor(Math.random() * 8);
for (let i = 0; i < board.length; i++) {
if (i === yRandomValue) {
for (let j = 0; j < board[yRandomValue].length; j++) {
if (j === xRandomValue) {
board[yRandomValue][xRandomValue] = ["O"];
}
}
}
}
coordinates.push(xRandomValue)
coordinates.push(yRandomValue)
count++
if(count>1){
generateBoard(board)
}
return board;
};
console.log(generateBoard(initialBoardState))