Skip to content

🧩 Puzzle State Example

State in action: Not every puzzle is just solved or unsolved — some have phases. A player might start it, make progress, then finally crack it.

Why it matters: Instead of messy if checks, each state gets its own class, making puzzle logic clean, extensible, and easy to follow.

A puzzle in the escape room isn’t just “solved or unsolved.”
It might have progression:

  • Unsolved → Player hasn’t interacted yet.

  • In Progress → Player made progress (entered part of the code, found part of the clue).

  • Solved → Puzzle is complete.

Instead of tracking this with a boolean or lots of if statements, we give each state its own class.


public interface PuzzleState {
void interact(Puzzle puzzle);
}

// Unsolved state
public class UnsolvedState implements PuzzleState {
@Override
public void interact(Puzzle puzzle) {
System.out.println("You start working on the puzzle...");
puzzle.setState(new InProgressState());
}
}
// In progress state
public class InProgressState implements PuzzleState {
@Override
public void interact(Puzzle puzzle) {
System.out.println("You're making progress on the puzzle...");
puzzle.setState(new SolvedState());
}
}
// Solved state
public class SolvedState implements PuzzleState {
@Override
public void interact(Puzzle puzzle) {
System.out.println("The puzzle is already solved!");
}
}

public class Puzzle {
private PuzzleState state;
public Puzzle() {
this.state = new UnsolvedState();
}
public void setState(PuzzleState state) {
this.state = state;
}
public void interact() {
state.interact(this);
}
}

public class EscapeRoomGame {
public static void main(String[] args) {
Puzzle puzzle = new Puzzle();
puzzle.interact(); // "You start working on the puzzle..."
puzzle.interact(); // "You're making progress on the puzzle..."
puzzle.interact(); // "The puzzle is already solved!"
}
}

You start working on the puzzle...
You're making progress on the puzzle...
The puzzle is already solved!