diff --git a/MULTIPLAYER.md b/MULTIPLAYER.md
index 55a81da..6ef76db 100644
--- a/MULTIPLAYER.md
+++ b/MULTIPLAYER.md
@@ -20,7 +20,8 @@ returns `+` (right digit, right place) and `-` (right digit, wrong place).
- **Game Type**: Auto Guesstures, Player Guesstures or Time Challenge.
3. The creator goes straight to the game screen (`/multiplayer/play`) and waits for a rival.
4. When a second player joins, the game starts. A game always has exactly 2 players, and a third join is rejected.
-5. If either player leaves, the game is over and both players see the result screen.
+5. 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
@@ -28,7 +29,7 @@ returns `+` (right digit, right place) and `-` (right digit, wrong place).
|-----------|------------------------------------------------------------------------------------------|
| `WAITING` | Created, only 1 player. |
| `PLAYING` | 2 players. In Player Guesstures this includes the "choose a number for your rival" step. |
-| `CLOSED` | Finished, either by the rules or because a player left. Stays in the lobby list for 5 minutes. |
+| `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`.
@@ -91,19 +92,33 @@ The formula is implemented in `ApiMastermind/.../multi/service/ScoreCalculator.j
---
-## 4. Leaving / disconnects
+## 4. Leaving, disconnects and resuming
-The game ends when a player:
-- clicks **Leave Game** (the browser asks for confirmation first),
-- closes or refreshes the tab, or navigates away (the browser shows a "leave page?" warning, then the client sends
- a `navigator.sendBeacon` leave request), or
-- stops polling for 20 s, for example after a network loss or crash. A server sweep runs every 2 s.
+A player is identified only by their **player token**. The game ends early in only two cases:
+
+1. **Abort.** The player clicks **Abort** on the game screen and confirms. The game ends immediately.
+2. **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 disconnected.
+make a player who switched tabs look offline.
---
@@ -121,12 +136,12 @@ or 409 (wrong state, duplicate name, game full, waiting for rival).
| 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 |
+| 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, …), `outcome` (`WIN`/`LOSE`/`DRAW`), `endReason`
+`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,
@@ -135,8 +150,12 @@ or 409 (wrong state, duplicate name, game full, waiting for rival).
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=20000 # no poll for this long = player left
+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
```
@@ -166,14 +185,14 @@ The single player code (`SingleGameController`, `SingleGameService`) was not cha
| File | Purpose |
|------|---------|
-| `page.js` | Lobby: game list, Join, Create New Game modal (replaces the "Under Construction" page). |
-| `play/page.js` | Game screen: waiting, number selection, guessing, histories, timer, result and score table. |
+| `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 (gameId and token in `sessionStorage`), type labels, time formatting. |
+| `api.js` | API calls, session (active game of the tab in `sessionStorage`), "my games" tokens in `localStorage`, type labels, time formatting. |
-The token is stored in **sessionStorage**, so each browser tab is a separate player. You can test with two tabs in
-the same browser.
+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.
---
@@ -194,7 +213,10 @@ What was verified:
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) passes.
+- `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_LEFT` after the timeout, and that Abort
+ still ends it immediately. The web changes were not run through `npm run build` or a browser yet.
---
@@ -204,4 +226,7 @@ What was verified:
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.
-- Refreshing the page during a game counts as leaving, as the requirement says. The browser warns before it happens.
+- 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.
diff --git a/README.md b/README.md
index 4344b70..f9ff04a 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,6 @@
# mastermind
-Mastermind Game
\ No newline at end of file
+Mastermind Game
+
+$ docker compose up -d --build
+$ docker compose down --rmi all
\ No newline at end of file
diff --git a/api/pom.xml b/api/pom.xml
index e0e4dd5..a39d5fe 100644
--- a/api/pom.xml
+++ b/api/pom.xml
@@ -10,7 +10,7 @@
com.mmkilic.gameApiMastermind
- 0.2
+ 0.3ApiMastermindMastermind Game REST API
diff --git a/api/src/main/java/com/mmkilic/game/multi/dto/PlayerView.java b/api/src/main/java/com/mmkilic/game/multi/dto/PlayerView.java
index e0e9f8b..9948ab7 100644
--- a/api/src/main/java/com/mmkilic/game/multi/dto/PlayerView.java
+++ b/api/src/main/java/com/mmkilic/game/multi/dto/PlayerView.java
@@ -4,7 +4,12 @@ import java.util.List;
public record PlayerView(
int slot,
+ /** true while the player is polling (online). */
boolean connected,
+ /** true if the player aborted the game or did not return within the player timeout. */
+ boolean left,
+ /** While offline: ms left to come back before the game ends; null when online or closed. */
+ Long returnWithinMs,
/** PLAYER_GUESSTURES: has this player chosen the number for the rival? */
boolean secretChosen,
/** Own view only: the number you chose for the rival. */
diff --git a/api/src/main/java/com/mmkilic/game/multi/service/MultiGameService.java b/api/src/main/java/com/mmkilic/game/multi/service/MultiGameService.java
index 32857cb..e5e4d5c 100644
--- a/api/src/main/java/com/mmkilic/game/multi/service/MultiGameService.java
+++ b/api/src/main/java/com/mmkilic/game/multi/service/MultiGameService.java
@@ -28,8 +28,13 @@ import com.mmkilic.game.service.NumberRules;
/**
* In-memory multiplayer games (no database). Every player is identified by a random token
- * returned on create/join. Clients poll {@link #state} which also works as a heartbeat;
- * a player that stops polling for {@code playerTimeoutMs} is treated as having left.
+ * returned on create/join. Clients poll {@link #state} which also works as a heartbeat.
+ *
+ *
A game only ends early when a player explicitly leaves ({@link #leave}, the Abort button).
+ *
Closing the tab or losing the connection does not end the game: the player is shown as
+ * offline after {@code offlineAfterMs} and can come back with the same token.
+ *
A player that has not polled for {@code playerTimeoutMs} (e.g. lost the token) is treated as having left.
+ *
*/
@Service
public class MultiGameService {
@@ -39,12 +44,15 @@ public class MultiGameService {
private final Object createLock = new Object();
private final long playerTimeoutMs;
+ private final long offlineAfterMs;
private final long closedRetentionMs;
public MultiGameService(
- @Value("${multiplayer.player-timeout-ms:20000}") long playerTimeoutMs,
+ @Value("${multiplayer.player-timeout-ms:900000}") long playerTimeoutMs,
+ @Value("${multiplayer.offline-after-ms:5000}") long offlineAfterMs,
@Value("${multiplayer.closed-retention-ms:300000}") long closedRetentionMs) {
this.playerTimeoutMs = playerTimeoutMs;
+ this.offlineAfterMs = offlineAfterMs;
this.closedRetentionMs = closedRetentionMs;
}
@@ -297,12 +305,12 @@ public class MultiGameService {
roundBased ? game.getCompletedRounds() + 1 : me.getAttempts() + 1,
canGuess, waitingForRival,
"SETUP".equals(stage),
- playerView(game, me, true),
- rival == null ? null : playerView(game, rival, false),
+ playerView(game, me, true, now),
+ rival == null ? null : playerView(game, rival, false, now),
outcome, game.getEndReason(), me.isLeft());
}
- private PlayerView playerView(MultiGame game, Player p, boolean own) {
+ private PlayerView playerView(MultiGame game, Player p, boolean own, long now) {
boolean closed = game.getStatus() == GameStatus.CLOSED;
boolean roundBased = game.getType().isRoundBased();
@@ -319,9 +327,17 @@ public class MultiGameService {
// Score and time: always for yourself once found, for the rival only when the game is over.
boolean showResult = closed || (own && p.isFound());
+
+ // A player that has not polled for a few seconds is offline, but may still come back.
+ long silentMs = now - p.getLastSeen();
+ boolean connected = !p.isLeft() && silentMs <= offlineAfterMs;
+ Long returnWithinMs = (!closed && !connected && !p.isLeft()) ? Math.max(0, playerTimeoutMs - silentMs) : null;
+
return new PlayerView(
p.getSlot(),
- !p.isLeft(),
+ connected,
+ p.isLeft(),
+ returnWithinMs,
p.getSecretForRival() != null,
own ? p.getSecretForRival() : null,
p.getAttempts(),
diff --git a/api/src/main/resources/application.properties b/api/src/main/resources/application.properties
index e6e8d6e..4c8eee8 100644
--- a/api/src/main/resources/application.properties
+++ b/api/src/main/resources/application.properties
@@ -2,8 +2,11 @@ spring.application.name=ApiMastermind
server.port=8080
server.servlet.context-path=/api-mastermind
# Multiplayer (in-memory, no database)
-# A player that has not polled the game for this long is treated as having left.
-multiplayer.player-timeout-ms=20000
+# Closing the tab or losing the connection does not end a game; only the Abort button does.
+# A player that has not polled the game for this long (e.g. lost the token) is treated as having left (15 min).
+multiplayer.player-timeout-ms=900000
+# A player that has not polled for this long is shown to the rival as offline (they can still return).
+multiplayer.offline-after-ms=5000
# Closed games stay in the lobby list for this long.
multiplayer.closed-retention-ms=300000
multiplayer.sweep-interval-ms=2000
diff --git a/notes.txt b/notes.txt
index 945b59c..e206134 100644
--- a/notes.txt
+++ b/notes.txt
@@ -21,4 +21,12 @@ time challenge: the game creates a number for the both players. turns go forward
There is a time counter in this game. the game continue until both user find the number. the best score win the game.
Please create a score calculation rule depening on time and turn count.
Please update api service and web application.
-Finally please create a summary note in the current directory
\ No newline at end of file
+Finally please create a summary note in the current directory
+
+I increased the property like that multiplayer.player-timeout-ms=900000.
+If it is possible, please update the code according to the following Requirements
+- Until play do not click aboard button, game continues.
+- if players left the game in a reason, they can return their own game.
+- as far as I understand we recognise a player from its token. If they loss their token, game is over after 15 min.
+- backend code is available in app directory
+Finally please update the summary note in the current directory
\ No newline at end of file
diff --git a/web/app/multiplayer/api.js b/web/app/multiplayer/api.js
index 6fffb17..184d0d2 100644
--- a/web/app/multiplayer/api.js
+++ b/web/app/multiplayer/api.js
@@ -3,6 +3,7 @@
const apiURL = process.env.NEXT_PUBLIC_API_URL || '';
const GAMES = `${apiURL}/multi/games`;
const SESSION_KEY = 'mastermind.multi';
+const MY_GAMES_KEY = 'mastermind.multi.myGames';
export const GAME_TYPES = {
AUTO_GUESSTURES: {
@@ -59,20 +60,48 @@ export const chooseSecret = (id, token, number) =>
export const leaveGame = (id, token) =>
call(`/${id}/leave`, { method: 'POST', token }).catch(() => {});
-/** Fire-and-forget leave that survives page close/refresh. */
-export function leaveGameBeacon(id, token) {
- const url = `${GAMES}/${id}/leave?token=${encodeURIComponent(token)}`;
- try {
- if (navigator.sendBeacon && navigator.sendBeacon(url)) return;
- } catch {}
- fetch(url, { method: 'POST', keepalive: true }).catch(() => {});
-}
-
-// The player token lives in sessionStorage so every browser tab is a separate player.
-export function saveSession(gameId, token) {
+// The active game of a tab lives in sessionStorage so every browser tab can be a separate player.
+// Every token is also remembered in localStorage ("my games") so a player who closed the tab,
+// refreshed or lost the connection can resume the game from the lobby.
+export function saveSession(gameId, token, slot) {
try {
sessionStorage.setItem(SESSION_KEY, JSON.stringify({ gameId, token }));
} catch {}
+ rememberGame(gameId, token, slot);
+}
+
+export function loadMyGames() {
+ try {
+ const list = JSON.parse(localStorage.getItem(MY_GAMES_KEY));
+ return Array.isArray(list) ? list : [];
+ } catch {
+ return [];
+ }
+}
+
+function storeMyGames(list) {
+ try {
+ localStorage.setItem(MY_GAMES_KEY, JSON.stringify(list));
+ } catch {}
+}
+
+function rememberGame(gameId, token, slot) {
+ const list = loadMyGames().filter((g) => g.token !== token);
+ list.push({ gameId, token, slot });
+ storeMyGames(list);
+}
+
+export function forgetGame(token) {
+ storeMyGames(loadMyGames().filter((g) => g.token !== token));
+}
+
+/** Drops remembered games that the server no longer lists or that are closed. */
+export function pruneMyGames(games) {
+ const open = new Set(games.filter((g) => g.status !== 'CLOSED').map((g) => g.id));
+ const list = loadMyGames();
+ const kept = list.filter((g) => open.has(g.gameId));
+ if (kept.length !== list.length) storeMyGames(kept);
+ return kept;
}
export function loadSession() {
diff --git a/web/app/multiplayer/page.js b/web/app/multiplayer/page.js
index 2f4e9c6..f33ce25 100755
--- a/web/app/multiplayer/page.js
+++ b/web/app/multiplayer/page.js
@@ -2,7 +2,7 @@
import { useCallback, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
-import { GAME_TYPES, createGame, joinGame, listGames, saveSession } from './api';
+import { GAME_TYPES, createGame, joinGame, listGames, pruneMyGames, saveSession } from './api';
import useTicker from './useTicker';
const STATUS_STYLE = {
@@ -18,10 +18,13 @@ export default function MultiplayerLobby() {
const [showCreate, setShowCreate] = useState(false);
const [joining, setJoining] = useState(null);
const [joinError, setJoinError] = useState('');
+ const [myGames, setMyGames] = useState([]);
const refresh = useCallback(async () => {
try {
- setGames(await listGames());
+ const list = await listGames();
+ setGames(list);
+ setMyGames(pruneMyGames(list));
setListError('');
} catch (err) {
setListError(err.message || 'Cannot reach the server');
@@ -31,7 +34,13 @@ export default function MultiplayerLobby() {
useTicker(refresh, 3000);
const enterGame = (res) => {
- saveSession(res.gameId, res.playerToken);
+ saveSession(res.gameId, res.playerToken, res.state?.you?.slot);
+ router.push('/multiplayer/play');
+ };
+
+ // Return to one of your own unfinished games (after closing the tab, a refresh or a connection loss).
+ const handleResume = (mine) => {
+ saveSession(mine.gameId, mine.token, mine.slot);
router.push('/multiplayer/play');
};
@@ -79,7 +88,9 @@ export default function MultiplayerLobby() {
)}
+ Your rival is offline. The game continues; they have{' '}
+
+ {formatTime(state.rival.returnWithinMs - (Date.now() - receivedAt))}
+ {' '}
+ to come back before the game ends.
+
@@ -217,8 +220,8 @@ function WaitingPanel({ state }) {
Waiting for a rival to join…
- Your friend can join “{state.name}” from the Multiplayer lobby. Keep this
- page open: leaving closes the game.
+ Your friend can join “{state.name}” from the Multiplayer lobby. You can
+ go back to the lobby and resume this game later; use Abort to close it.
);
@@ -296,7 +299,10 @@ function ResultPanel({ state, onBack }) {
}[outcome] || ['Game Closed', 'text-neutral-300'];
let reason = '';
- if (endReason === 'PLAYER_LEFT') reason = youLeft ? 'You left the game.' : 'Your rival left the game.';
+ if (endReason === 'PLAYER_LEFT')
+ reason = youLeft
+ ? 'You aborted the game or did not come back in time.'
+ : 'Your rival aborted the game or did not come back in time.';
else if (state.type === 'TIME_CHALLENGE') reason = 'Both players found the number.';
else reason = you.found && rival?.found ? 'Both players found their number in the same round.' : 'A number was found.';
diff --git a/web/app/page.js b/web/app/page.js
index e0b1485..c4d8151 100755
--- a/web/app/page.js
+++ b/web/app/page.js
@@ -21,7 +21,7 @@ export default function Home() {
);