We've been told to build a Minesweeper game on a 3x3 grid using only JavaScript that can be played in the VS studio console.
With some help from a higher level student, I have a dynamic 2d array, I kind of understand how it works up until the line
for (let j = 0; j < gridSize; j++)
I get lost there:
const generateGrid = (gridSize) => { //NOTE - Creates a 2D array of objects
let grid = []; //Empty array
for (let i = 0; i < gridSize; i++) {
grid.push([]); //Pushes to empty array
for (let j = 0; j < gridSize; j++) {
grid[i][j] = [
];
}
}
return grid;
};
let grid = generateGrid(9); //Sets grid size i.e. 3 = 3x3 Grid, 9 = 9x9 Grid etc
I need a boolean function for my random mine generator so I've come up with below:
const isMine = () => Math.round(Math.random());//Boolean, Math.random returns number between 0.0 and 1.0, Math.round rounds 0.5 > to 0 or 0.5 < to 1
let placeMine = isMine();
console.log(placeMine)//NOTE - Testing Boolean returns 0 or 1
Someone had mentioned flattening the array before the placing of the mines so I think I figured out how to do that but I don't understand why I want to do this:
const flatten = (arr) => { //Flatten 2d array to 1d
let flattenArr = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
flattenArr = flattenArr.concat(flatten(arr[i]));
} else {
flattenArr.push(arr[i]);
}
}
return flattenArr;
};
console.log(flatten([grid]))
console.table(grid) //Prints 2D array to table
The dynamic board works fine, it prints to console.table a square array of [] whichever size you set it to as expected, the boolean function works as expected, I think the flatten function works? but its hard to tell, it turns the array into a single [].
Basically where do I go next? I've got a board, do I need to create cells as well? I know I need to push mines to the array but I have no clue how, someone mentioned you can create a list to store the mines locations and a function checks the list whenever the user input coordinates? I've been told to use Readline to prompt the user with a rl.question for entering user input i.e. the grid coordinates of cell they wish to reveal?