I have the following code, to set up the mines in a minesweeper game, but I keep getting an error in the plantMines() function, "TypeError: data[randomx] is undefined". I'm new to React, so perhaps I'm missing something simple, but I just cannot see where the problem is.
initBoardData(height, width, mines) {
let data = this.createEmptyArray(height, width);
data = this.plantMines(data, height, width, mines);
return data;
}
// Create array of grid
createEmptyArray(height, width) {
let data = [];
for (let i = 0; i < height; i++) {
data.push([]);
for (let j = 0; j < width; j++) {
data[i][j] = {
x: i,
y: j,
isMine: false,
neighbour: 0,
isRevealed: false,
isEmpty: false,
isFlagged: false
};
}
}
return data;
}
// Place mines on board
plantMines(data, height, width, mines) {
let randomx, randomy, minesPlanted = 0;
while (minesPlanted < mines) {
randomx = this.getRandomNumber(width);
randomy = this.getRandomNumber(height);
if (!(data[randomx][randomy].isMine)) { //--ERROR ON THIS LINE
data[randomx][randomy].isMine = true;
minesPlanted++;
}
}
return (data);
}
getRandomNumber(dimension) {
return Math.floor((Math.random() * 1000) + 1 % dimension);
}
EDIT: codesandbox - https://codesandbox.io/s/minesweeper-luono?file=/src/Board.js
if (!(data[randomx][randomy].isMine))which is the original issue.<Board height={height} width={width} mines={mines} />