Skip to content
Tutorials Center
My learning

Topics

Lesson 186 of 201 ยท Projects

Project: Memory Card Game

Build a Java memory matching game with a testable game-state model, bots that prove the rules work, and a Swing grid view with javax.swing.Timer for flipping and the clock.

The memory game is simple to explain: a grid of face-down cards, two flips per turn, matching pairs stay up and mismatches flip back after a moment. It's also a perfect project for learning how to separate the rules of a game from the screen it's drawn on. Beginners usually put everything in the button click handler. That works until the first bug, and then you can't test the rules without clicking a window.

This project does it the professional way. You'll build the game's state as a plain Java class with no GUI at all, so you can run it in the editor and even simulate a thousand games with computer players. Then you'll build a Swing view that does nothing except forward clicks to the model and draw what the model says, using javax.swing.Timer to flip a mismatch back and to run the clock.

You'll practice enums, classes and encapsulation, collections and shuffling, the Swing basics, layout managers, event handling and timers.

Our server has no screen, as the GUI overview explains, so a real window can't open here. The model runs normally. The Swing view runs in headless mode: all components and the layout are created for real and we click the buttons programmatically with doClick(). Only the three lines that create a JFrame are shown read-only, and those are the only lines you need a desktop for.

Rules and states

Write the rules down before the code, because they decide the states:

  • Every card is hidden, face up (just flipped) or matched.
  • A turn is two flips. The first flip just shows a card.
  • The second flip counts as one move. If the two faces are equal, both become matched. If not, both stay face up until hideMismatch() flips them back, and no other card can be flipped in the meantime.
  • Flipping a card that isn't hidden does nothing.
  • The game is won when every card is matched.

That "wait until the mismatch is hidden" state is what the timer controls in the GUI. In the model it's just a boolean, awaitingHide(), which keeps the model free of time.

Stage 1: the game model

The model class stores the deck, one state per card and the indexes of the current picks. It never prints anything and knows nothing about Swing.

Java Stage 1: the memory game model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the printed lines against the rules:

  • Flipping 0 then 1 (A and B) is a mismatch: both cards stay face up, and the next flip 2 is IGNORED because the game is waiting for hideMismatch(). That one boolean is what stops a player from flipping a third card.
  • After hideMismatch() the same two cards are hidden again and moves still says 1, since a move is a pair of flips.
  • Cards 0 and 3 are both A, so they match and stay up. Flipping card 0 again is ignored.
  • faceAt returns ? for hidden cards. The view can't peek at hidden faces, because the model simply doesn't give them out. The only escape hatch is peekAtDeckForTesting, which makes the shuffling check possible.
  • Shuffling with a seeded Random gives the same deck every time. Real games use new Random(); tests use a seed so failures are repeatable.

Notice what flip returns: a FlipResult. The caller (the GUI, a bot, a test) needs to know what happened to decide what to do next, for example starting a timer after a MISMATCH. Returning information instead of printing or calling back keeps the model reusable.

Stage 2: proving the rules with bots

How do you know your rules are right? One way is to play many games automatically. The model has no GUI, so two computer players can use it directly through flip, faceAt and hideMismatch, just like a window would.

  • The random player flips two random hidden cards each turn. It has no memory.
  • The memory player remembers every face it has seen. If it knows where a pair is, it goes for it; otherwise it flips a card it has never seen.

Because both players only ever see what faceAt shows a human, they can't cheat. If the model had a bug, say a match that doesn't count or a game that never ends, the simulation would reveal it by looping forever or by averages that make no sense.

Java Stage 2: simulating games with two kinds of player

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The simulation tells a clear story. The player with memory finishes 16 cards in about 12 moves, close to the perfect 8, while the forgetful one needs over 60. Both always finish. Playing 2,000 games without a hang or an exception is decent evidence that the state machine can't get stuck. In a real project you'd turn these observations into assertions in unit tests: after any sequence of flips, moves never decreases, a won game has no hidden cards, and so on.

One detail in the memory player is worth studying: it asks the game for faceAt(first) after flipping, exactly like a human who looks at the card they turned over. The known map is the player's brain, not the game's data.

Stage 3: the Swing view

Now the part players see. The panel holds one JButton per card in a GridLayout, a label for moves, and a label for the clock. It has no game logic. Its job has three steps:

  1. When a button is clicked, call game.flip(index).
  2. If the result is MISMATCH, start a one-shot timer. When it fires, call game.hideMismatch().
  3. After every change, refresh: for each button, ask the model for faceAt and stateOf, and update the text and whether the button is enabled.

Two javax.swing.Timer objects drive time. javax.swing.Timer runs its action on the event dispatch thread, so the code inside can safely touch components, unlike java.util.Timer, which fires on its own thread. The hide timer is set to not repeat (setRepeats(false)), and the clock timer ticks every second.

The clock reads the time from a java.time.Clock. Passing the clock in (instead of calling Instant.now() inside) makes it easy to test with a fixed clock, as in the time lesson.

The program below builds the real panel and "plays" it headlessly: doClick() triggers exactly the listener a mouse click would. Between steps it waits for the hide timer and lets the event queue drain.

Java Stage 3: the Swing panel, driven without a window

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In the output, a * after a card face marks a disabled button:

  • After the mismatch, every button is disabled (awaitingHide), and the third click is ignored. The panel doesn't have to enforce the lock; the model does, and the buttons simply reflect it.
  • After 150 ms the hide timer fires on the event dispatch thread, the model flips both cards back, and refresh() re-enables the buttons. That's why the program waits for the timer and then runs an empty task on the event thread: it makes sure everything queued earlier has finished before the next line prints.
  • After a match, the two matched cards stay visible and disabled.
  • At the end, the status reads You won in 4 moves!.

The three lines that need a screen

To open the panel in a real window, add this main to a local file along with the same classes, and run it with java MemoryApp.java on your computer:

Java
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import java.time.Clock;
import java.util.List;
import java.util.Random;

public class MemoryApp {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            List<String> faces = List.of("โ™ ", "โ™ฅ", "โ™ฆ", "โ™ฃ", "โ˜…", "โ˜€", "โ˜‚", "โ˜Ž");
            MemoryGame game = MemoryGame.shuffled(faces, new Random());
            JFrame frame = new JFrame("Memory");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new GamePanel(game, 4, 800, Clock.systemUTC()));
            frame.setSize(420, 460);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}

Use the MemoryGame.shuffled method from Stage 1 here, and the panel class from Stage 3, which takes the hide delay (800 ms feels right) and the clock as constructor arguments. Everything else in the window, such as the grid, the labels and both timers, is the code you already ran.

Design notes

  • The model has no idea Swing exists. You could put the same MemoryGame behind a web page, a terminal or a bot, as you did in Stage 2. This is the core of the model-view split.
  • The view never computes game rules. It asks faceAt and stateOf for everything it draws. If the rules change, the panel doesn't.
  • javax.swing.Timer instead of Thread.sleep. Sleeping inside a click handler would freeze the window (see Swing events). A timer returns immediately and calls you back later on the right thread.
  • The clock is injected. GamePanel receives a Clock, so a test can pass a fixed one and check 00:00, or a custom one that advances.
  • State is refreshed from the model, not patched. refresh() rewrites all buttons every time. For a 16-card board that's trivially cheap, and it can't drift out of sync with the game.

Ideas to extend it

  • Add difficulty levels with 4x4, 6x6 and 8x8 boards, and a best-moves record per level (a Map<Integer, Integer>).
  • Replace the letters with drawn icons: JButton.setIcon with images you generate using BufferedImage and Graphics2D.
  • Add a two-player mode with a score per player. The model keeps a current-player index and gives the turn to the other player after a mismatch.
  • Animate the flip with a short repeating Timer that changes the button's colour.
  • Add a "New game" button that builds a fresh MemoryGame and calls refresh().
  • Replace the buttons with a custom component that overrides paintComponent and draws cards yourself (see Swing components).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does MemoryGame.faceAt return "?" for hidden cards instead of the real face?

    The model only reveals what a human player could see. A view or bot that asks faceAt gets the same information a person sees on the table.
  2. 2. What stops the player from flipping a third card while a mismatched pair is showing?

    After a mismatch the game stays in a waiting state until hideMismatch is called. The model ignores flips in that state, and the view also disables the buttons to show it.
  3. 3. Why use javax.swing.Timer to hide a mismatched pair instead of calling Thread.sleep in the click handler?

    Click handlers run on the event dispatch thread, which also paints the screen. Blocking it freezes the UI. A Swing Timer returns immediately and later runs its action on the same thread, where touching components is safe.
  4. 4. What is the main benefit of simulating thousands of games with bots in Stage 2?

    Because the model has no GUI, automated players can use it directly. If a rule were wrong, games would hang, throw exceptions or produce implausible averages.

Summary

  • Keep game rules in a model class with no GUI code. Return a result enum from actions so callers know what happened.
  • Represent "waiting for the mismatch to flip back" as an explicit state, and let the view's timer decide when to leave it.
  • Test the model with scripted flips, seeded shuffles and bots that play through the same public methods as the window.
  • The Swing view forwards clicks to the model, then refreshes every component from the model's state.
  • Use javax.swing.Timer for delayed actions and clocks; it runs on the event dispatch thread, so it can update components safely.
  • Pass dependencies such as Clock into the view so it stays testable.

Next: Project: A Simple Search Engine, where you'll build an inverted index and rank results by term frequency.