Create a Minesweeper Game Clone with Vanilla Javascript
This time we’re going to code a simple copy of the minesweeper game that has become a classic in Windows OS. If you want to see the result directly, you can watch the fast-code video above. You can also read the codes here.
We start with a simple HTML file. We create a div element with the id of mineSweeper
. We add a div element into it class-named grid
.
Nothing complicated on the CSS side. We use the display:grid
property for the grid element . We will give the required values in javascript according to the number of columns and rows. We will also class-name cell
elements for cells, and we style ::after
virtual classes to cover the contents of the cells.
On the javascript side, we start by the file mineSweeper.js
. Here we will load the helper module and call functions that can be used multiple times. With the square module, we import the necessary classes for the cells.
We define the variables in which the numbers of columns, rows and bombs in the game are kept. We will keep the data of our cells in the array named grid, but this array will be one-dimensional. Normally, a cell of a 5-column grid with position {2,4} will have {9} position in this array.
We give the column number style of the grid element according to our column count.
We determine random locations for our bombs and place them first. Then we loop these bomb positions again and increase the values of their neighbors. These values will show the number of bombs around a game cell. Of course, if the neighbor index is null in the grid array, we fill it with a Cell class instance.
Finally, we loop through whole grid, fill in the null indexes if any, and create and add DOM elements to tree. With the click event handlers given to the DOM elements of the cells, if it is a bomb, we finish the game and if not, we show all neighbor cells that are not bomb and whose value is zero with a chain reaction.