Match The Tiles

1. Introduction

Match the Tiles is a simple and engaging memory game implemented in Java Swing. The objective is to flip two tiles at a time and find matching image pairs. If the selected tiles match, they stay visible; otherwise, they are flipped back after a short delay. The game tracks the number of moves made and congratulates the player once all tiles are matched.

The game board consists of 20 tiles arranged in a 5x4 grid. Each tile has a hidden image, and every image appears exactly twice. Players use their memory to recall the positions of previously revealed tiles and match them in as few moves as possible.

2. Core Gameplay Mechanics

1. Shuffling: A list of 10 unique image indices is duplicated and shuffled to randomize the tile positions before each game.
2. Initial Reveal: All tiles are displayed for 3 seconds at the beginning of the game to give the player a short preview.
3. Tile Flip: Clicking a tile reveals the hidden image. The game tracks whether a tile is already selected to compare pairs.
4. Match Detection: If two consecutively flipped tiles match, they remain visible and disabled. If they don’t, they are flipped back after 800 milliseconds.
5. Move Counter: Every pair flipped—regardless of whether it matched—counts as one move and is reflected in the "Moves" label.
6. Win Condition: Once all 10 pairs are matched (i.e., 20 matched tiles), a message box congratulates the player and disables further interaction.

3. How Matching Logic Works

The game maintains internal variables to track selected tiles and their states:

1. State Tracking: A boolean isATileSelected is used to know if a first tile has already been flipped.
2. Image Comparison: The index values from the shuffled image list are compared using numbers.get(index) for the first and second selected tiles.
3. On Match:
    • Both tiles remain visible.
    • Their listeners are removed.
    • The matched tile count increases by 2.
    • If total matched tiles equal 20, the game ends with a win dialog.

4. On Mismatch:
    • Both tiles are temporarily revealed.
    • A Timer runs for 800ms, then resets the tiles to their hidden state.
    • During this delay, all tile clicks are disabled by removing their action listeners.
    • After reset, listeners are re-added to allow new attempts.

4. Technical Design Details

1. Grid Layout: The UI uses a JPanel with GridLayout(5, 4) to create a uniform 20-tile layout.
2. Icon Management: Tile images are stored in an array and assigned based on a shuffled index list. The backside image is assigned after a 3-second delay using a one-time Swing Timer.
3. Sound Feedback: Each tile click plays a wooden sound using javax.sound.sampled audio APIs.
4. Move Tracking: A label at the top updates after every attempt using the variable noOfMoves.
5. Listener Control: The game disables all tile interactions during mismatches using removeActionListener() to prevent interference during the delay timer.