Hey guys, long time no talk
Since finishing the FCC Javascript module, I have been taking on another javascript and i’m working on creating a Minesweeper game.
Everything is going well so far BUT I have an issue when it comes to generating mines randomly.
/* function to generate mine locations on the board */
export function generateMines(numberOfMines, boardSize) {
// while loop until you reach the number of mines
const minePositions = [];
while (minePositions.length < numberOfMines) {
const position = {
x: getRandomIntInclusive(boardSize),
y: getRandomIntInclusive(boardSize),
};
if (
!minePositions.some((p) => {
comparePositions(p, position);
})
) {
minePositions.push(position);
}
}
return minePositions;
}
/* function to generate random integers to use for mine locations */
function getRandomIntInclusive(size) {
const min = 1;
const max = size;
return Math.floor(Math.random() * (max - min + 1) + min);
}
/* function to compare X and Y positions */
export function comparePositions(a, b) {
return a.x === b.x && a.y === b.y;
}
Here is what the code does
- Create an empty array
- Generate random X and Y, check if they’re in the array already and if not, push them to the array
But when I run that function, sometimes I wold end up with two items having the same coordinates, and I can’t figure out why…
Anything I’m missing?