12 KiB
Mastermind – Multiplayer Summary
Multiplayer was added to both projects:
- ApiMastermind – Spring Boot REST API
- mastermind – Next.js web app (static export)
It follows the same rules as single player: an N-digit number where every digit is used only once, and each guess
returns + (right digit, right place) and - (right digit, wrong place).
1. Game flow
- Lobby (
/multiplayer) lists every game in memory and refreshes every 3 s. Each row shows the name, type, digit count, players (x/2) and status. A Join button appears onwaitinggames. - Create New Game opens a modal with these fields:
- Game Name: required, max 30 characters, unique (case-insensitive) among games that are not closed.
- Number Limit: 3–10 digits.
- Game Type: Auto Guesstures, Player Guesstures or Time Challenge.
- The creator goes straight to the game screen (
/multiplayer/play) and waits for a rival. - When a second player joins, the game starts. A game always has exactly 2 players, and a third join is rejected.
- The game continues until it is won or a player clicks Abort. Closing the tab, refreshing or losing the connection does not end it: the player can come back with Resume in the lobby (see section 4).
Statuses
| Status | Meaning |
|---|---|
WAITING |
Created, only 1 player. |
PLAYING |
2 players. In Player Guesstures this includes the "choose a number for your rival" step. |
CLOSED |
Finished by the rules, by Abort, or because a player did not return within 15 minutes. Stays in the lobby list for 5 minutes. |
The game screen also uses a finer stage value: WAITING → SETUP (Player Guesstures only) → PLAYING → FINISHED.
2. Game types
Auto Guesstures
- The server generates two different secret numbers, one for each player.
- Rounds run together. After a player guesses, they wait until the rival has also guessed that round.
- The round result is revealed once both guesses are in. Each player then sees their own result and the rival's guess and result.
- When a player finds their number, the game ends at the end of that round. Both scores, both secret numbers and the full histories are shown. Both players always have the same number of turns.
Player Guesstures
- Before the first round, each player chooses the number the rival must find, using the same digit rule. A player can change their choice until the rival has also chosen.
- After that it works exactly like Auto Guesstures.
Time Challenge
- The server generates one number for both players.
- Turns are independent, so each player guesses at their own pace.
- Rival guesses are hidden. You only see the rival's attempt count and whether they have found the number. Their guesses are revealed when the game ends.
- A game timer is shown. The game continues until both players find the number, and the best score wins.
3. Score rule
The same rule applies to all game types:
found: score = max(100, 1000 × digits − 100 × turns − 2 × seconds)
not found: score = 0
- digits: the number length. Longer numbers are worth more.
- turns: guesses used, including the winning guess.
- seconds: the player's own time:
- Time Challenge: from game start until the player found the number.
- Round-based modes: the sum of each round's time from round start until the player's guess. Time spent waiting for the rival does not count.
- One extra turn costs as much as 50 seconds, so fewer turns matter most and speed decides close games.
- A found number is always worth at least 100, so finding the number always beats not finding it.
- The higher score wins. Equal scores are a draw. In round-based modes, if both players find their number in the same round, the faster thinker wins.
Examples with 4 digits:
| Turns | Time | Score |
|---|---|---|
| 6 | 1:30 | 4000 − 600 − 180 = 3220 |
| 6 | 3:00 | 4000 − 600 − 360 = 3040 |
| 9 | 1:00 | 4000 − 900 − 120 = 2980 |
| – | – | not found = 0 |
The formula is implemented in ApiMastermind/.../multi/service/ScoreCalculator.java. Change the constants there to tune it.
4. Leaving, disconnects and resuming
A player is identified only by their player token. The game ends early in only two cases:
- Abort. The player clicks Abort on the game screen and confirms. The game ends immediately.
- Lost token / no return. The player has not polled the game for 15 minutes
(
multiplayer.player-timeout-ms=900000), for example because they lost their token (cleared browser data, another device or browser). A server sweep checks this every 2 s.
Everything else keeps the game running:
- ← Lobby on the game screen goes back to the lobby without ending the game.
- Closing or refreshing the tab, navigating away, a crash or a network loss do not end it.
- After 5 s without a poll (
multiplayer.offline-after-ms) the rival sees a banner: "Your rival is offline. They have mm:ss to come back before the game ends." The countdown resets as soon as the player is back. - The game clock keeps running while a player is away. In Time Challenge and in the round where a player is away, that time counts towards their score.
Resuming. On create and join, the web client stores the token in localStorage ("my games",
key mastermind.multi.myGames). The lobby shows a Resume button on every unfinished game that this browser has
a token for. Resume reopens the game with the same token, so the player continues exactly where they left off.
Finished, aborted or removed games are dropped from "my games" automatically.
Who wins when someone leaves: the player who stayed, unless the leaver had already found the number and the
stayer had not (possible in Time Challenge). A game closed while still WAITING has no winner.
The client polls from a Web Worker timer. Browsers throttle normal timers in background tabs, which would otherwise make a player who switched tabs look offline.
5. REST API (/api-mastermind/multi/games)
Each player gets a random player token when they create or join a game. Send it in the X-Player-Token header.
Errors are returned as {"message": "..."} with status 400 (invalid input), 403 (not a player), 404 (unknown game)
or 409 (wrong state, duplicate name, game full, waiting for rival).
| Method | Path | Body | Returns |
|---|---|---|---|
| GET | / |
– | GameSummary[] (lobby) |
| POST | / |
{name, digits, type} |
{gameId, playerToken, state} |
| POST | /{id}/join |
– | {gameId, playerToken, state} |
| GET | /{id}/state |
– (token) | GameView, the player-specific view; also the heartbeat |
| POST | /{id}/secret |
{number} (token) |
GameView (Player Guesstures setup) |
| POST | /{id}/guess |
{number} (token) |
GameView |
| POST | /{id}/leave |
– (token header or ?token=) |
204 (Abort: ends the game) |
type is one of AUTO_GUESSTURES, PLAYER_GUESSTURES or TIME_CHALLENGE.
GameView contains stage, round, elapsedMs, canGuess, waitingForRival, canChooseSecret,
you/rival (attempts, found, timeMs, score, history, connected, left, returnWithinMs, …), outcome (WIN/LOSE/DRAW), endReason
(SOLVED/PLAYER_LEFT) and youLeft. The server hides what a player must not see:
- the rival's guess in the current round,
- all rival guesses in Time Challenge,
- the secret numbers until the game ends,
- the rival's score and time until the game ends.
Settings in application.properties:
connected is false when the player has not polled for offline-after-ms. returnWithinMs is the time an
offline player has left to come back (null when online or when the game is closed).
multiplayer.player-timeout-ms=900000 # no poll for this long (15 min) = player left, game over
multiplayer.offline-after-ms=5000 # no poll for this long = shown as offline (can still return)
multiplayer.closed-retention-ms=300000 # closed games stay listed this long
multiplayer.sweep-interval-ms=2000
6. Files
API (ApiMastermind/src/main/java/com/mmkilic/game/)
| File | Purpose |
|---|---|
service/NumberRules.java |
Shared number rules: generate, validate, check +/-. |
multi/model/* |
MultiGame, Player, GuessRecord, GameType, GameStatus, EndReason. |
multi/dto/* |
Request and response records. |
multi/service/MultiGameService.java |
In-memory game store (ConcurrentHashMap, one lock per game), all rules, disconnect sweeper. |
multi/service/ScoreCalculator.java |
Score rule. |
multi/service/GameException.java |
Error with an HTTP status. |
multi/controller/MultiGameController.java |
REST endpoints. |
multi/controller/MultiGameExceptionHandler.java |
JSON error responses, scoped to the multiplayer controller. |
config/SchedulingConfig.java |
Enables @Scheduled for the sweeper. |
resources/application.properties |
Multiplayer settings. |
The single player code (SingleGameController, SingleGameService) was not changed.
Web (mastermind/app/multiplayer/)
| File | Purpose |
|---|---|
page.js |
Lobby: game list, Join, Resume, Create New Game modal (replaces the "Under Construction" page). |
play/page.js |
Game screen: waiting, number selection, guessing, histories, timer, rival-offline banner, Lobby/Abort buttons, result and score table. |
NumberPad.js |
Digit pad with the each-digit-once rule. Supports mouse and keyboard (0-9, Backspace, Enter). |
useTicker.js |
Web Worker-based polling interval. |
api.js |
API calls, session (active game of the tab in sessionStorage), "my games" tokens in localStorage, type labels, time formatting. |
The active game is kept per tab in sessionStorage, so each browser tab can be a separate player and you can test with two tabs in the same browser. In that case the lobby shows Resume P1 and Resume P2 for the game.
7. Running and testing locally
# API (http://localhost:8080/api-mastermind)
cd ApiMastermind && ./mvnw spring-boot:run
# Web (http://localhost:3000)
cd mastermind && npm install && npm run dev
Open http://localhost:3000/multiplayer in two tabs. Create a game in one tab and join it from the other.
What was verified:
- An API script played all three game types to the end. It also checked duplicate names, a third player joining, guessing twice in one round, hidden rival guesses, invalid input, leaving, and the heartbeat timeout.
- A headless browser test with two tabs played a full Player Guesstures game, and a Time Challenge where closing the rival's tab ended the game as "Your rival left".
npm run build(static export and lint) passed for the first version.- Reconnect update: an API smoke test (with short timeouts) checked that a silent player shows as offline with a
countdown, can return with the same token, that the game ends with
PLAYER_LEFTafter the timeout, and that Abort still ends it immediately. The web changes were not run throughnpm run buildor a browser yet.
8. Limitations and ideas
- Everything is in memory. Restarting the API removes all games, and running several API instances would need shared state (for example Redis).
- Players have no names. Screens show "You" and "Rival". A nickname field would be an easy addition.
- Polling (1 s) is simple and works through any proxy. WebSocket/SSE would make updates instant if needed.
- Tokens live in the browser's
localStorage. A player cannot resume from another device or browser; in that case the game ends after 15 minutes. A short "rejoin code" shown on screen would make cross-device return possible. - While one player is offline, the other may have to wait up to 15 minutes in round-based modes. Only Abort ends the game sooner.