Minesweeper

1. Introduction to Minesweeper

This is a Java Swing implementation of Minesweeper, a classic logic puzzle game where the objective is to reveal all non-mine tiles on a grid while avoiding hidden bombs. The game includes features such as first-click safety, flagging mines, game timer, and full GUI interaction through left and right mouse clicks.

The game grid consists of 14 × 14 tiles, with 30 randomly placed mines. On the first click, mines are generated such that the clicked tile is always safe. The interface is responsive and uses a Swing Timer to track elapsed time and remaining tiles.

2. Gameplay Features

1. Safe First Click: Mines are generated only after the first tile is clicked, ensuring the first move is never fatal.
2. Tile Flagging: Right-click toggles a flag emoji (🚩) to mark suspected mines.
3. Dynamic Timer: A real-time timer displays elapsed seconds and updates the count of unrevealed non-mine tiles.
4. Loss Detection: If a mine is revealed, all mines are shown (💥), the timer stops, and the game resets.
5. Victory Condition: Revealing all non-mine tiles triggers a win dialog with the time taken.


3. How the Flood Fill Algorithm Works

The flood fill algorithm is used to automatically reveal a group of adjacent empty tiles (tiles with 0 adjacent mines) after a tile is clicked. This mimics how traditional Minesweeper games uncover large empty areas.

The process is implemented recursively in the floodfill() method and works as follows:

1. Base Cases: The function exits immediately if:
    • The cell is out of bounds.
    • The cell is already visited.
    • The cell contains a mine (value -1).

2. Visitation Mark: The current tile is marked as visited to prevent infinite loops.

3. Empty Tile (0): If the tile has no adjacent mines:
    • It is revealed (blank with white background).
    • The method is recursively called on all 8 neighboring tiles.

4. Numbered Tile (1–8): If the tile has adjacent mines:
    • The number is displayed and the tile is revealed.
    • Recursion halts in this direction to avoid exposing more tiles.

4. Technical Design Overview

1. Grid Construction: A GridLayout of JButtons is used to build the 14×14 tile board.
2. Mine Placement: A shuffled 1D list is trimmed to the desired mine count and then mapped into 2D board indices.
3. Board State Array: A 2D array boardState[][] tracks cell status: -1 for mines, 0 for empty, and 1–8 for adjacent mine counts.
4. Mouse Events: Each button has a MouseListener that distinguishes left-click (reveal/flood fill) and right-click (flag toggle).
5. Timer & Status Bar: A JLabel shows live updates for time and unrevealed tile count, driven by a Swing Timer.