1. Code
  2. Coding Fundamentals
  3. Game Development

Build a Grid-Based Puzzle Game Like Minesweeper in Unity: Winning

Scroll to top
This post is part of a series called Build a Grid-Based Puzzle Game Like Minesweeper in Unity.
Build a Grid-Based Puzzle Game Like Minesweeper in Unity: Interaction

In the final part of this series, we put the finishing touches on our grid-based Unity puzzle game, and make it playable. By the end of this part, the player will be able to win or lose the game.

Now that you've completed the previous tutorials, our game can create a field of tiles, and assign mines randomly to them. We also have a nice light-up effect when the player hovers over a tile with the mouse, and it's possible to place and remove flags.

Internally, each tile also knows about their neighboring tiles, and can already calculate how many mines are nearby.

Uncovering Tiles

We've already added the ability to place flags with a right click. Now, let's add the ability to uncover tiles with a left click.

In the OnMouseOver() function, where we have the click recognition code, we need to recognize a left click. Adapt the function so that it looks like this:

1
function OnMouseOver()
2
{
3
    if(state == "idle")
4
    {
5
        renderer.material = materialLightup;
6
    
7
        if (Input.GetMouseButtonDown(0))
8
            UncoverTile();
9
    
10
        if (Input.GetMouseButtonDown(1))
11
            SetFlag();
12
    }
13
    else if(state == "flagged")
14
    {
15
        renderer.material = materialLightup;
16
    
17
        if (Input.GetMouseButtonDown(1))
18
            SetFlag();
19
    }
20
}

When the left mouse button is pressed, the UncoverTile() function will be called. Make sure that you create this function, so that this won't cause a bug!

1
function UncoverTile()
2
{
3
    if(!isMined)
4
    {
5
        state = "uncovered";
6
        displayText.renderer.enabled = true;
7
        renderer.material = materialUncovered;
8
    }
9
    else
10
        Explode();
11
}

For this to work, we need to introduce a new material.

1
public var materialUncovered: Material;

Create something that has a different color than the basic tiles—so if your basic tiles are blue, you could choose green for the uncovered state. But don't use red; we'll need that later to show that we've triggered a mine.

When call that function, the following happens: 

  • First, we check whether the tile is actually mined. 
  • If not, we set the state to uncovered, activate the text display that shows us the number of nearby mines, and set the material to the uncovered material. 
  • Afterwards, the tile cannot be clicked again, and also won't light up again, which means the passive feedback of tiles reacting to the mouse cursor will only happen on tiles we can actually click.

Before we can try this out, we need to make sure that the material isn't changed when the mouse cursor exits the tile. For this, adapt the OnMouseExit() function like so:

1
function OnMouseExit()
2
{
3
    if(state == "idle" || state == "flagged")
4
        renderer.material = materialIdle;
5
}

This way, the color only gets switched back if the tile has not yet been uncovered.

Try it out! You should be able to uncover tiles. If a tile is mined, though, nothing will happen right now.

Making Empty Tiles Uncover Each Other

This will be a bit tricky. In Minesweeper, when you uncover a tile with no mines next to, it will uncover all the tiles adjacent to it that also have no mines, and the tiles adjacent to them that have no mines, and so on.

Consider this field:

We don't actually see the numbers or mines, only regular tiles.

When a tile with zero nearby mines is uncovered, all tiles next to it should automatically be uncovered, too. The uncovered tile then uncovers all neighbors.

These newly uncovered tiles will then check their neighbors, too, and, if there are no mines, uncover them as well.

This will ripple through the field until we reach tiles that actually have mines adjacent to them, where it will stop.

This creates the empty areas we can see in Minesweeper.

To make this work, we need two more functions, UncoverAdjacentTiles() and UncoverTileExternal():

1
private function UncoverAdjacentTiles()
2
{
3
    for(var currentTile: Tile in adjacentTiles)
4
    {
5
        //uncover all adjacent nodes with 0 adjacent mines
6
        if(!currentTile.isMined && currentTile.state == "idle" && currentTile.adjacentMines == 0)
7
            currentTile.UncoverTile();
8
        
9
        //uncover all adjacent nodes with more than 1 adjacent mine, then stop uncovering
10
        else if(!currentTile.isMined && currentTile.state == "idle" && currentTile.adjacentMines > 0)
11
            currentTile.UncoverTileExternal();
12
    }
13
}
14
15
public function UncoverTileExternal()
16
{
17
    state = "uncovered";
18
    displayText.renderer.enabled = true;
19
    renderer.material = materialUncovered;
20
}

We also need to make this modification to the UncoverTile() function:

1
function UncoverTile()
2
{
3
    if(!isMined)
4
    {
5
        state = "uncovered";
6
        displayText.renderer.enabled = true;
7
        renderer.material = materialUncovered;
8
        
9
        if(adjacentMines == 0)
10
            UncoverAdjacentTiles();
11
    }
12
}

When we uncover a tile, and there are no mines next to it, we call the UncoverAdjacentTiles() function. This then checks each neighboring tile to see whether it has mines or not. too. If there aren't any, it uncovers this tile as well, and initiates another round of checking. If there are mines nearby, it only uncovers the tile it is currently at.

Now, try it out. To get good chance of an empty field appearing, create a rather large field with a few mines—say, 81 tiles, with nine tiles per row, and 10 mines in total.

You can actually now play this as a game, except that you cannot trigger mines yet. We'll add that feature next.

Triggering Mines

When we uncover a tile that is mined, the game stops and the player loses. Additionally, all other mined tiles become visible. For this to happen, we need one more material, for the detonated mine tiles:

1
public var materialDetonated: Material;

I suggest using something red for this.

Also, we need to add two more functions to handle exploding all of the mines:

1
function Explode()
2
{
3
    state = "detonated";
4
    renderer.material = materialDetonated;
5
    
6
    for (var currentTile: Tile in Grid.tilesMined)
7
        currentTile.ExplodeExternal();
8
}
9
10
function ExplodeExternal()
11
{
12
    state = "detonated";
13
    renderer.material = materialDetonated;
14
}

We trigger those methods in the UncoverTile() function:

1
function UncoverTile()
2
{
3
    if(!isMined)
4
    {
5
        state = "uncovered";
6
        displayText.renderer.enabled = true;
7
        renderer.material = materialUncovered;
8
        
9
        if(adjacentMines == 0)
10
            UncoverAdjacentTiles();
11
    }
12
    else
13
        Explode();
14
}

If a tile is mined, the tile explodes. The Explode() function then sends an "explode" command to all other tiles with mines, revealing them all.

Winning the Game

The game is won once all tiles with mines have been flagged correctly. At this point, all tiles that are not uncovered are uncovered too. So how do we track that?

Let's start by adding a state variable to the Grid class, so that we can track which part of the game we are currently in (still playing, lost, or won).

1
static var state: String = "inGame";

While we're at it, we can also begin to add a simple GUI, so that we can display necessary information on the screen. Unity comes with its own GUI system which we'll use for this.

1
function OnGUI()
2
{
3
    GUI.Box(Rect(10,10,100,50), state);
4
}

This will show us which state we are currently in. We'll call these states inGame, gameOver, and gameWon.

We can also add checks to the Tile, to make sure we can only interact with the tiles while the current game state is inGame.

In the OnMouseOver() and OnMouseExit functions, move all the existing code into an if block that checks whether Grid.state is currently inGame, like so:

1
function OnMouseOver()
2
{
3
    if(Grid.state == "inGame")
4
    {
5
        if(state == "idle")
6
        {
7
            renderer.material = materialLightup;
8
            
9
            if (Input.GetMouseButtonDown(0))
10
                UncoverTile();
11
            
12
            if (Input.GetMouseButtonDown(1))
13
                SetFlag();
14
        }
15
        else if(state == "flagged")
16
        {
17
            renderer.material = materialLightup;
18
        
19
            if (Input.GetMouseButtonDown(1))
20
                SetFlag();
21
        }
22
    }
23
}
24
25
function OnMouseExit()
26
{
27
    if(Grid.state == "inGame")
28
    {
29
        if(state == "idle" || state == "flagged")
30
            renderer.material = materialIdle;
31
    }
32
}

There are actually two ways to check whether the game has been won: we can count how many mines have been marked correctly, or we can check whether all tiles that are not mines have been uncovered. For that, we need the following variables; add them to the Grid class:

1
static var minesMarkedCorrectly: int = 0;
2
static var tilesUncovered: int = 0;
3
static var minesRemaining: int = 0;

Don't forget to set minesRemaining in the Start() function to numberOfMines, and the other variables to 0. The Start() function should now look like this:

1
function Start()
2
{
3
    CreateTiles();
4
    
5
    minesRemaining = numberOfMines;
6
    minesMarkedCorrectly = 0;
7
    tilesUncovered = 0;
8
    
9
    state = "inGame";
10
}

The last line sets the state for the game. (This will be important when we want to introduce a "restart" function later.)

We then check for our end-game conditions in the Update() function:

1
function Update()
2
{
3
    if(state == "inGame")
4
    {
5
        if((minesRemaining == 0 && minesMarkedCorrectly == numberOfMines) || (tilesUncovered == numberOfTiles - numberOfMines))
6
            FinishGame();
7
    }
8
}

We finish the game by setting the state to gameWon, uncovering all remaining tiles, and flagging all remaining mines:

1
function FinishGame()
2
{
3
    state = "gameWon";
4
    
5
    //uncovers remaining fields if all nodes have been placed

6
    for(var currentTile: Tile in tilesAll)     
7
        if(currentTile.state == "idle" && !currentTile.isMined)
8
            currentTile.UncoverTileExternal();
9
    
10
    //marks remaining mines if all nodes except the mines have been uncovered

11
    for(var currentTile: Tile in Grid.tilesMined)    
12
        if(currentTile.state != "flagged")
13
            currentTile.SetFlag();
14
}

For all this to actually work, we need to increment the variables that track our progress at the right spots. Adapt the UncoverTile() function to do that:

1
function UncoverTile()
2
{
3
    if(!isMined)
4
    {
5
        state = "uncovered";
6
        displayText.renderer.enabled = true;
7
        renderer.material = materialUncovered;
8
        
9
        Grid.tilesUncovered += 1;
10
        
11
        if(adjacentMines == 0)
12
            UncoverAdjacentTiles();
13
    }
14
    else
15
        Explode();
16
}

...as well as the UncoverTileExternal() function:

1
function UncoverTileExternal()
2
{
3
    state = "uncovered";
4
    displayText.renderer.enabled = true;
5
    renderer.material = materialUncovered;
6
    Grid.tilesUncovered += 1;
7
}

We also need to increment and decrement the minesMarkedCorrectly and minesRemaining variables depending on whether a flag has been set:

1
function SetFlag()
2
{
3
    if(state == "idle")
4
    {
5
        state = "flagged";
6
        displayFlag.renderer.enabled = true;
7
        Grid.minesRemaining -= 1;
8
        if(isMined)
9
            Grid.minesMarkedCorrectly += 1;
10
    }
11
    else if(state == "flagged")
12
    {
13
        state = "idle";
14
        displayFlag.renderer.enabled = false;
15
        Grid.minesRemaining += 1;
16
        if(isMined)
17
            Grid.minesMarkedCorrectly -= 1;
18
    }
19
}

Losing the Game

In the same way, we need to make it possible to lose a game. We accomplish this via the Explode() function within the tile. 

Simply add this line to the Explode() function:

1
Grid.state = "gameOver";

Once that line is run, the state of the game is switched to gameOver, and the tiles can no longer be interacted with.

Adding a More Functional GUI

We used the Unity GUI a few steps ago to tell the player which game state they're currently in. Now we'll extend it to show some actual messages.

The framework for this looks like the following:

1
function OnGUI()
2
{
3
    if(state == "inGame")
4
    {
5
    }
6
    else if(state == "gameOver")
7
    {
8
    
9
    }
10
    else if(state == "gameWon")
11
    {
12
    
13
    }
14
}

Depending on the state, different messages get displayed in the GUI. If the game is lost or won, for example, we can display messages saying so:

1
function OnGUI()
2
{
3
    if(state == "inGame")
4
    {
5
    }
6
    else if(state == "gameOver")
7
    {
8
        GUI.Box(Rect(10,10,200,50), "You lose");
9
    }
10
    else if(state == "gameWon")
11
    {
12
        GUI.Box(Rect(10,10,200,50), "You rock!");
13
    }
14
}

We can also show the number of mines found so far, or add a button that reloads the level once the game is over:

1
function OnGUI()
2
{
3
    if(state == "inGame")
4
    {
5
        GUI.Box(Rect(10,10,200,50), "Mines left: " + minesRemaining);
6
    }
7
    else if(state == "gameOver")
8
    {
9
        GUI.Box(Rect(10,10,200,50), "You lose");
10
    
11
        if(GUI.Button(Rect(10,70,200,50), "Restart"))
12
            Restart();
13
    }
14
    else if(state == "gameWon")
15
    {
16
        GUI.Box(Rect(10,10,200,50), "You rock!");
17
    
18
        if(GUI.Button(Rect(10,70,200,50), "Restart"))
19
            Restart();
20
    }
21
}
22
23
function Restart()
24
{
25
    state = "loading";
26
    Application.LoadLevel(Application.loadedLevel);
27
}

You can try it all out in this final build!

Conclusion

That's it! We have created a simple puzzle game with Unity, which you can use as a basis to create your own. I hope you've enjoyed this series; please ask any questions you have in the comments!





Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.