Mine Sweeper Made Easy

Thomas Kesler
3 min readDec 2, 2021

--

Took some time today to brush off some coding dust and decided to build a quick Mine Sweeper clone. Let’s see if I can walk you through the process I used in Unity3D.

Let’s start with the cells, which are basic Cubes with a Collider, a Text Element (Text Mesh Pro) and a couple of materials for the tinting.

For this project, the cells needed to know only three things about the game; Is it Mined, Is it Flagged, and Who are it’s neighbors. Whether is was a Mine Cell is up to the Game Manager to decide, but let’s set that access and control up.

Here we set a private boolean for are Mined flag and a couple of public calls for the Game Manager to discover and change it.

Knowing if it is flagged is important when we Open a Cell and when we Show the Mine locations at the End of a round.

In OpenCell(), we also use the information about Neighbors to open them as well if the current Cell has no mines around it, This let’s us clear out large areas of the board in a chain reaction effect.

We populate the Neighbors by using an OverlapSphere to grab all the colliders directly around the cell, then getting the Script component (Cell) and adding it an array of the neighbors. And we call this Method once all the cells are spawned and mined by the GameManager.

Using Unity’s OnMouseOver() and OnMouseExit() functions, we can change the coloration of the cell that the mouse is over. And with the input system, we can use the Left and Right Mouse buttons to Select a cell or Flag it respectively.

As for the GameManager, besides doing some basic checks during the Game Loop, it’s main function is to create and mine the boards. Both total number of cells and mines are determined by the difficulty setting and can be set in a Switch statement. Then with a bit of math, position the Camera over the center of the board and spawn the Cells in.

Once all the cells are in place, we randomly pick cells to mine, making sure to check whether they are mined already or not. Then we us an Event to tell all the Cells to run the Setup to grab their neighbors.

I ran through this exercise with a thought for expansion and further development. That is why there are places that get called and just call one other method. These points are places that would serve to expand the code and allow me to add functions later, such as animations and effects.

As a final statement, I would recommend to anyone, not already studying something, to take a brief break from your current projects and spend a couple hours working out how to code a simple classic game like MineSweeper. You never know what ‘simple’ things you have forgotten about while working away on more complex projects.

--

--

Thomas Kesler
Thomas Kesler

Written by Thomas Kesler

A Unity Developer with a fondness for Fantasy games and the challenge of pushing boundaries.