Minesweeper looks simple at first glance — it's a grid of numbers and mines. But implementing it from scratch reveals several interesting technical decisions: how do you distribute mines in a truly random way? How do you guarantee the first click is never a mine? How do you implement the cascading reveal of empty cells without freezing the UI? In this article I show how I solved each of these questions in Campo Minado Evolution.
Updated on October 22, 2026: this article was revised to reflect the app's current implementation — immutable cells, mine placement with a shuffled list, and an iterative queue-based flood fill.
The data structure: modeling a cell
Each board position is represented by an immutable Cell object holding all the state needed for rendering and game logic:
class Cell {
final int row;
final int col;
final bool isMine;
final bool isRevealed;
final bool isFlagged;
final int adjacentMines;
final bool isExploded;
const Cell({
required this.row,
required this.col,
required this.isMine,
required this.isRevealed,
required this.isFlagged,
required this.adjacentMines,
this.isExploded = false,
});
Cell copyWith({
bool? isMine,
bool? isRevealed,
bool? isFlagged,
int? adjacentMines,
bool? isExploded,
}) {
return Cell(
row: row,
col: col,
isMine: isMine ?? this.isMine,
isRevealed: isRevealed ?? this.isRevealed,
isFlagged: isFlagged ?? this.isFlagged,
adjacentMines: adjacentMines ?? this.adjacentMines,
isExploded: isExploded ?? this.isExploded,
);
}
}
Every field is final: any change produces a new cell via copyWith. That rules out hidden side effects and lets Riverpod compare the old state with the new one to know exactly what changed.
The entire board is a two-dimensional list initialized with clean cells. No mine is placed at creation time — this initial board is just a placeholder, and the mines are drawn on the first tap, as we'll see next.
List<List<Cell>> createEmptyBoard(int rows, int cols) {
return List.generate(
rows,
(r) => List.generate(
cols,
(c) => Cell(
row: r,
col: c,
isMine: false,
isRevealed: false,
isFlagged: false,
adjacentMines: 0,
),
),
);
}
Distributing the mines: the first-click problem
A classic Minesweeper rule: the first click can never explode a mine. That means mines need to be distributed after the first click, excluding the tapped cell and all of its neighbors from the draw. In the app, the first tap regenerates the board, passing the tapped position as the safe zone:
void placeMines(
List<List<Cell>> board,
int count, {
int? safeRow,
int? safeCol,
}) {
final rows = board.length;
final cols = board[0].length;
final excluded = <(int, int)>{};
if (safeRow != null && safeCol != null) {
for (final dr in [-1, 0, 1]) {
for (final dc in [-1, 0, 1]) {
excluded.add((safeRow + dr, safeCol + dc));
}
}
}
final positions = [
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
if (!excluded.contains((r, c))) (r, c),
];
positions.shuffle(Random());
for (int i = 0; i < count; i++) {
final (r, c) = positions[i];
board[r][c] = board[r][c].copyWith(isMine: true);
}
}
Instead of drawing random coordinates and discarding duplicates until the mine total is reached, I build the list of candidate positions (everything outside the safe zone), shuffle it, and take the first count. The cost is predictable, there is no loop that could spin indefinitely, and the distribution stays uniform. The 3×3 exclusion zone guarantees the first tap opens up some room for the player to reason. If the number of mines exceeds the available positions, the use case throws instead of producing an invalid board (the code above is a simplified version).
Calculating the adjacent numbers
After distributing the mines, we walk the entire board and calculate how many mines exist among the 8 neighbors of every non-mine cell:
void calculateAdjacentCounts(List<List<Cell>> board) {
final rows = board.length;
final cols = board[0].length;
const offsets = [-1, 0, 1];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (board[r][c].isMine) continue;
int count = 0;
for (final dr in offsets) {
for (final dc in offsets) {
if (dr == 0 && dc == 0) continue;
final nr = r + dr;
final nc = c + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols &&
board[nr][nc].isMine) {
count++;
}
}
}
board[r][c] = board[r][c].copyWith(adjacentMines: count);
}
}
}
The cascading reveal: iterative flood fill with a queue
When the player taps a cell with adjacentMines == 0, every connected empty cell must be revealed automatically — along with the numbers at the edges of that region. This is a flood fill algorithm, the same technique used by bucket-fill tools in paint programs.
List<List<Cell>> reveal(List<List<Cell>> board, int row, int col) {
final updated = board.map((r) => [...r]).toList();
final pending = Queue<(int, int)>()..add((row, col));
while (pending.isNotEmpty) {
final (r, c) = pending.removeFirst();
final cell = updated[r][c];
if (cell.isRevealed || cell.isFlagged) continue;
updated[r][c] = cell.copyWith(isRevealed: true);
if (cell.adjacentMines == 0 && !cell.isMine) {
for (final neighbor in neighborsOf(updated, r, c)) {
pending.add((neighbor.row, neighbor.col));
}
}
}
return updated;
}
The recursive version is the simplest to write, but the call stack grows with the size of the empty region — which is a risk on large boards. That's why the reveal uses a queue (Queue): each empty cell enqueues its neighbors to process later, and the loop ends when the queue is empty. Cells that are already revealed or flagged are skipped, and cells with a number greater than zero are revealed but don't expand the search (the edges of the region). The reveal works on a copy of the board, preserving the immutability of the state. The neighborsOf helper returns the up-to-8 neighboring cells that fall within the board bounds.
Rendering the board with Flutter
The board is rendered with GridView.builder using a fixed cross-axis-count delegate. The cell size is computed from the available space so the grid fills the screen on any device. Each cell is a ConsumerWidget that watches only its own position in the state:
class CellWidget extends ConsumerWidget {
// ...
@override
Widget build(BuildContext context, WidgetRef ref) {
final cell = ref.watch(
gameProvider.select((s) => s.game.board[row][col]),
);
return GestureDetector(
onTap: () => _onTap(ref),
onLongPress: () => _onLongPress(ref),
child: CellContentWidget(cell: cell, cellSize: cellSize),
);
}
}
Because select compares the old Cell with the new one, only the cells that changed are rebuilt — essential on Hard, with hundreds of cells. A simple tap reveals the cell; a long press places a flag. There's also a flag-mode button that makes a simple tap place a flag instead of revealing, for players who prefer not to long-press.
GridView.builder(
physics: const NeverScrollableScrollPhysics(),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: cols,
childAspectRatio: 1.0,
mainAxisSpacing: spacing,
crossAxisSpacing: spacing,
),
itemCount: rows * cols,
itemBuilder: (context, index) {
final row = index ~/ cols;
final col = index % cols;
return CellWidget(
key: ValueKey('cell_${row}_$col'),
row: row,
col: col,
cellSize: cellSize,
);
},
)
The CellContentWidget decides what to display: a covered cell, a flag, a colored number, or a mine. The number colors follow the classic Minesweeper convention: 1 blue, 2 green, 3 red, and so on.
Win and loss conditions
Both conditions are checked after every move. A loss happens when the revealed cell is a mine; a win, when no covered non-mine cell remains:
bool checkVictory(List<List<Cell>> board) {
return board
.expand((row) => row)
.where((cell) => !cell.isRevealed && !cell.isMine)
.isEmpty;
}
On a win, the timer stops, the app plays the victory sound, vibrates, and saves the time to the stats (Drift/SQLite), which feed the best time and win rate per difficulty. On a loss, every mine is revealed, the one that exploded is marked with isExploded: true so it gets its own animation, and the defeat is recorded too.
Implementing Minesweeper in Flutter is an excellent exercise because it combines classic algorithms (flood fill, constrained random generation) with reactive UI. All the logic lives outside the widget tree, in pure use cases — GenerateBoardUseCase, RevealCellUseCase, CheckVictoryUseCase, and ToggleFlagUseCase — orchestrated by a GameViewModel (a Riverpod Notifier). Since they are functions over immutable state, they're simple to test without mocks, and the UI only rebuilds what changed.
Try Campo Minado Evolution for free on Google Play:
Download Campo Minado Evolution