Each cell is an object that has several properties:
Our board is a collection of cells. We could represent our board in many different ways. I chose to represent it as an object with key value pairs. As we saw earlier, each cell has an id. The board is just a mapping between these unique keys and their corresponding cells.
After creating the board we have to do two more tasks: randomly assign the mines and calculate the neighboring mine counts. We’ll talk more about these tasks in the next section.
One of the first things we have to do before a game of minesweeper can be played is assign mines to cells. For this, I created a function that takes the board and the desired mine count as parameters.
For every mine we place, we must generate a random row and column. Furthermore, the same row and column combination should never appear more than once. Otherwise we would end up with less than our desired number of mines. We must repeat the random number generation if a duplicate appears.
As each random cell coordinate is generated we set the *mined *property to true of the corresponding cell in our board.
I created a helper function in order to help with the task of generating random numbers within our desired range. See below:
Helper function for generating random integers.
Now let’s look at what it takes to calculate the neighboring mine count of each cell in our board.
You’ll notice that we start by looping through each row and column on the board, a very common pattern. This will allow us to execute the same code on each of our cells.
We first check if each cell is mined. If it is, there is no need to check the neighboring mine count. After all, if the player clicks on it he/she will lose the game!
If the cell is not mined then we need to see how many mines are surrounding it. The first thing we do is call our *getNeighbors *helper function, which returns a list of ids of the neighboring cells. Then we loop through this list, add up the number of mines, and update the cell’s *neighborMineCount *property appropriately.
Let’s take a closer look at that *getNeighbors *function, as it will be used several more times throughout the code. I mentioned earlier that some of my design choices won’t scale to larger board sizes. Now would be a good time to try and spot them.
Next, we use the row and column to calculate potential ids of each neighboring cell and push them onto a list. Our list should have eight ids in it before cleaning it up to handle special scenarios.
A minesweeper cell and its neighbors.
While this is fine for the general case, there are some special cases we have to worry about. Namely, cells along the borders of our game board. These cells will have less than eight neighbors.
In order to take care of this, we loop through our list of neighbor ids and remove any id that is greater than 2 in length. All invalid neighbors will either be -1 or 10, so this little check solves the problem nicely.
We also have to decrement our index variable whenever we remove an id from our list in order to keep it in sync.
Okay, we have one last function to talk about in this section: isMined.
The *isMined *function is pretty simple. It just checks if the cell is mined or not. The function returns a 1 if it is mined, and a 0 if it is not mined. This feature allows us to sum up the function’s return values as we call it repeatedly in the loop.
That wraps up the algorithms for getting our minesweeper game board set up. Let’s move on to the actual game play.
Alright let’s dive right into this bad boy. We execute this function whenever a player clicks on a cell. It does a lot of work, and it also uses something called recursion. If you are unfamiliar with the concept, see the definition below:
Recursion: See recursion.
Ah, computer science jokes. They always go over so well at bars and coffee shops. You really ought to try them out on that cutie you’ve been crushing on.
Anyways, a recursive function is just a function that calls itself. Sounds like a stack overflow waiting to happen, right? That’s why you need a base case that returns a value without making any subsequent recursive calls.
Our function will eventually stop calling itself because there will be no more cells that need to be opened. We could have written this code without recursion, but I thought you all might want to see an example of it in action.
The *handleClick *function takes a cell id as a parameter. We need to handle the case where the player pressed the ctrl button while clicking on the cell, but we will talk about that in a later section.
Assuming the game isn’t over and we are handling a basic left click event, there are a few checks we need to make. We want to ignore the click if the player already opened or flagged the cell. It would be frustrating for the player if an inaccurate click on an already flagged cell ended the game.
If neither of those are true then we will proceed. If a mine is present in the cell we need to initiate the game over logic and display the exploded mine in red. Otherwise, we will open the cell.
If the opened cell has mines surrounding it we will display the neighboring mine count to the player in the appropriate font color. If there are no mines surrounding the cell, then it is time for our recursion to kick in. After setting the background color of the cell to a slightly darker shade of gray, we call *handleClick *on each unopened neighboring cell without a flag.
Let’s take a look at the helper functions we are using inside the handleClick *function. We’ve already talked about *getNeighbors, so we’ll skip that one. Let’s start with the *loss *function.
When a loss occurs, we set the variable that tracks this and then display a message letting the player know that the game is over. We also loop through each cell and display the mine locations. Then we stop the clock.
Second, we have the *getNumberColor *function. This function is responsible for giving us the color corresponding to the neighboring mine count.
I tried to match up the colors just like the classic Windows version of minesweeper does it. Maybe I should have used a switch statement, but I already took the screen shot, and it’s not really a big deal. Let’s move on to what the code looks like for putting a flag on a cell.
Right clicking on a cell will place a flag on it. If the player right clicks on an empty cell and we have more mines that need to be flagged we will display the red flag on the cell, update its flagged property to true, and decrement the number of mines remaining. We do the opposite if the cell already had a flag. Finally, we update the GUI to display the number of mines remaining.
We have covered the actions of opening cells and marking them with flags, so let’s talk about the last action a player can take: opening an already opened cell’s neighboring cells. The *handleCtrlClick *function contains the logic for this. This player can perform this action by holding ctrl and left clicking on an opened cell that contains neighboring mines.
The first thing we do after checking those conditions is build up a list of the neighboring flagged cells. If the number of flagged cells matches the actual number of surrounding mines then we can proceed. Otherwise, we do nothing and exit the function.
If we were able to proceed, the next thing we do is check if any of the flagged cells did not contain a mine. If this is true, we know that the player predicted the mine locations incorrectly, and clicking on all of the non-flagged, neighboring cells will end in a loss. We will need to set the local lost variable and call the *loss *function. We talked about the *loss *function earlier in the article.
If the player did not lose, then we will need to open up the non-flagged neighboring cells. We simply need to loop through them and call the *handleClick *function on each. However, we must first set the *ctrlIsPressed *variable to false to prevent falling into the *handleCtrlClick *function by mistake.
The first thing we do is initialize a few variables. We need some constants for storing the html codes for the flag and mine icons. We also need some constants for storing the board size, the number of mines, the timer value, and the number of mines remaining.
Additionally, we need a variable for storing if the player is pushing the ctrl button. We utilize jQuery to add the event handlers to the document, and these handlers are responsible for setting the *ctrlIsPressed *variable.
Finally, we call the *newGame *function and also bind this function to the new game button.
Th newGame *function is responsible for resetting our variables so that our game is in a ready-to-play state. This includes resetting the values that are displayed to the player, calling *initializeCells, and creating a new random board. It also includes resetting the clock, which gets updated every second.
Let’s wrap things up by looking at initializeCells.
The main purpose of this function is to add additional properties to our html game cells. Each cell needs the appropriate id added so that we can access it easily from the game logic. Every cell also needs a background image applied for stylistic reasons.
We also need to attach a click handler to every cell so that we can detect left and right clicks.
The function that handles left clicks calls handleClick, passing in the appropriate id. Then it checks to see if every cell without a mine has been opened. If this is true then the player has won the game and we can congratulate him/her appropriately.
The function that handles right clicks calls handleRightClick, passing in the appropriate id. Then it simply returns false. This causes the context menu not to pop up, which is the default behavior of a right click on a web page. You wouldn’t want to do this sort of thing for a standard business CRUD application, but for minesweeper it is appropriate.
Want to develop a website or re-design using CSS Development? We build a website and we implemented CSS successfully if you are planning to **[Hire CSS Developer](https://hourlydeveloper.io/hire-dedicated-css-developer/ "Hire CSS Developer")**...
We are here to bridge your dreams to reality by offering you the best ludo game development. Our Ludo game software development is the best option to choose if you want to launch a game like ludo king in a short time.