Building a console Minesweeper in C++
A look back at my first C++ project: a single-file, terminal Minesweeper with several difficulty modes, a flood-fill reveal, and a list of things I would now do differently.
This is a look back at my first C++ project: a Minesweeper that runs in the terminal. It is one file of about 570 lines, created on 15 October 2024 as the first exercise of a course titled Programmation impérative. The rules and special cases are modelled on minesweeper.online.
The game works, but it is full of choices I would now make differently. That is the reason it is worth writing about.
Download the source if you want to follow along.
What the game does
The player picks a mode, then types moves such as a3 or b15 (a column letter followed by a row number). A move either reveals a square or places a flag, which the player chooses before each move.
| Mode | Grid | Bombs |
|---|---|---|
| Beginner | 9 × 9 | 7% |
| Intermediate | 15 × 15 | 12% |
| Expert | 26 × 26 | 25% |
| Custom | 4 × 4 to 52 × 52 | 10% to 40% |
| Infinite | 4, 8, 16, then 32 | 15% |
In infinite mode the grid doubles after each win and halves after each loss. Winning on 32 × 32 beats the mode, and losing on 4 × 4 fails it. A debug mode prints the bomb positions and the move number, which made testing much easier.
This is what the board looks like after a first move on the beginner grid. The program prints it with [#] for hidden squares:
a b c d e f g h i
___________________________
1 [ ][ ][1][#][#][#][#][1][ ]
2 [ ][ ][1][#][1][1][1][1][ ]
3 [ ][ ][1][1][1][ ][ ][ ][ ]
4 [ ][ ][ ][ ][ ][ ][ ][ ][ ]
5 [ ][ ][ ][ ][ ][1][2][2][1]
6 [ ][ ][ ][ ][1][2][#][#][#]
7 [1][1][ ][ ][1][#][3][2][1]
8 [#][1][ ][ ][1][1][1][ ][ ]
9 [#][1][ ][ ][ ][ ][ ][ ][ ]
The structure: Draw, Input, Logic
main runs a loop with three functions, which is a common shape for small games:
Drawclears the screen and prints the board.Inputasks for an action and a square, and validates them.Logicplaces bombs on the first move, checks for a loss, and reveals squares.
When a game ends, endMessage frees the memory and, in infinite mode, sets up the next grid.
The board is a flat array
The board is a one-dimensional array of strings. Every square holds "#" (hidden), "F" (flag), " " (empty), or a digit. A move such as c4 is converted to a single index:
twoDBoard = new string[SQUARES];
for (int i = 0; i < SQUARES; ++i) {
twoDBoard[i] = "#";
}
// ...
playerMove = ((indexRow * boardDimensions) + indexColumn);
The index is row * dimensions + column. A flat array is simple and fast, but it hides one trap: the square to the right of the last column is the first square of the next row. Every neighbour calculation has to deal with that.
Placing bombs after the first move
Bombs are generated on the first move, not at the start, so the first move can be kept safe. The idea is to roll a random square for each bomb and re-roll if it collides with the player’s move or an earlier bomb:
for (int i = 0; i < numberOfBombs; ++i) {
int bomb = rand() % numberOfSquares;
bombPositionsList[i] = bomb;
for (int j = 0; j < numberOfElementsInBombPositionsList; ++j) {
while (bombPositionsList[i] == bombPositionsList[j] || bombPositionsList[i] == playerMove || bombPositionsList[j] == playerMove) {
int bomb = rand() % numberOfSquares;
bombPositionsList[i] = bomb;
}
}
++numberOfElementsInBombPositionsList;
}
This code has two flaws, and I only found them while writing this article:
- For the very first bomb the inner loop does not run, so nothing compares it with
playerMove. The first bomb can land on the square the player just chose. - A re-rolled value is only compared against one earlier bomb at a time, so it can end up duplicating a bomb that was already checked.
A shuffle would fix both. Fill a list with every index except the player’s square, shuffle it, and take the first numberOfBombs entries.
Revealing squares with recursion
When the player opens a square with no bombs around it, the game opens all its neighbours, and repeats for each of them that is also empty. That is a flood fill, and revealSquares implements it recursively:
for (int i = -1; i <= 1; ++i) {
for (int j = -1; j <= 1; ++j) {
if (i == 0 && j == 0) continue;
int newRow = row + i;
int newCol = col + j;
int newIndex = newRow * boardDimensions + newCol;
if (newRow >= 0 && newRow < boardDimensions && newCol >= 0 && newCol < boardDimensions && newIndex >= 0 && newIndex < SQUARES) {
revealSquares(newIndex, /* ... */);
}
}
}
The function marks each square as visited before recursing, so the depth can never exceed the number of squares. On the largest board that is 52 × 52 = 2704 calls. Checking the row and column separately, rather than only the flat index, is what stops a neighbour from wrapping around the edge of the grid.
The code that counts the bombs around a square is less clean. It uses a nine-element array and some modulo arithmetic to detect the edges, and I left a comment next to it saying there were problems there. Reusing the row and column approach from the flood fill would have been simpler.
What I would change today
- Everything. I would rewrite it from scratch, but more specifically:
- Memory.
Inputallocates new arrays on every call andLogicallocates a new visited array every turn. Most of them are never freed. Usingstd::vectorremoves the problem entirely. It was prohibited by the teacher because we had to “learn” memory management. - Restarting. The program restarts by calling
main()again, which the C++ standard does not allow. An outer loop inmainis the right choice. - Parameter lists. Some functions take more than fifteen references. A
Gamestruct holding the board, the bombs, the flags and the mode would replace all of them. I even noted in a comment that I would have preferred a header file, which was also prohibited because the project had to hold in one file. - Portability.
system("cls")only works on Windows, andusing namespace stdis better avoided. - Unused ideas. A bonus and malus system is partly defined: there are constants for it and two extra square types are accepted as input, but nothing places them on the board yet.
Takeaways
This project taught me how a game loop is organised, how to turn a 2D grid into a flat array, and why recursion needs a clear stopping condition. It also left me with a precise list of what to improve in the next one, and more importantly, the need to learn more about programming and C++.