multiplayer return the game
This commit is contained in:
parent
aa04134600
commit
ff7870fff6
|
|
@ -20,7 +20,8 @@ returns `+` (right digit, right place) and `-` (right digit, wrong place).
|
||||||
- **Game Type**: Auto Guesstures, Player Guesstures or Time Challenge.
|
- **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.
|
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.
|
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
|
### Statuses
|
||||||
|
|
||||||
|
|
@ -28,7 +29,7 @@ returns `+` (right digit, right place) and `-` (right digit, wrong place).
|
||||||
|-----------|------------------------------------------------------------------------------------------|
|
|-----------|------------------------------------------------------------------------------------------|
|
||||||
| `WAITING` | Created, only 1 player. |
|
| `WAITING` | Created, only 1 player. |
|
||||||
| `PLAYING` | 2 players. In Player Guesstures this includes the "choose a number for your rival" step. |
|
| `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`.
|
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:
|
A player is identified only by their **player token**. The game ends early in only two cases:
|
||||||
- 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
|
1. **Abort.** The player clicks **Abort** on the game screen and confirms. The game ends immediately.
|
||||||
a `navigator.sendBeacon` leave request), or
|
2. **Lost token / no return.** The player has not polled the game for **15 minutes**
|
||||||
- stops polling for 20 s, for example after a network loss or crash. A server sweep runs every 2 s.
|
(`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
|
**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.
|
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
|
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 |
|
| GET | `/{id}/state` | – (token) | `GameView`, the player-specific view; also the heartbeat |
|
||||||
| POST | `/{id}/secret` | `{number}` (token) | `GameView` (Player Guesstures setup) |
|
| POST | `/{id}/secret` | `{number}` (token) | `GameView` (Player Guesstures setup) |
|
||||||
| POST | `/{id}/guess` | `{number}` (token) | `GameView` |
|
| 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`.
|
`type` is one of `AUTO_GUESSTURES`, `PLAYER_GUESSTURES` or `TIME_CHALLENGE`.
|
||||||
|
|
||||||
`GameView` contains `stage`, `round`, `elapsedMs`, `canGuess`, `waitingForRival`, `canChooseSecret`,
|
`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:
|
(`SOLVED`/`PLAYER_LEFT`) and `youLeft`. The server hides what a player must not see:
|
||||||
- the rival's guess in the current round,
|
- the rival's guess in the current round,
|
||||||
- all rival guesses in Time Challenge,
|
- 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`:
|
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.closed-retention-ms=300000 # closed games stay listed this long
|
||||||
multiplayer.sweep-interval-ms=2000
|
multiplayer.sweep-interval-ms=2000
|
||||||
```
|
```
|
||||||
|
|
@ -166,14 +185,14 @@ The single player code (`SingleGameController`, `SingleGameService`) was not cha
|
||||||
|
|
||||||
| File | Purpose |
|
| File | Purpose |
|
||||||
|------|---------|
|
|------|---------|
|
||||||
| `page.js` | Lobby: game list, Join, Create New Game modal (replaces the "Under Construction" page). |
|
| `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, result and score table. |
|
| `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). |
|
| `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. |
|
| `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 active game is kept per tab in **sessionStorage**, so each browser tab can be a separate player and you can
|
||||||
the same browser.
|
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.
|
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
|
- 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".
|
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).
|
shared state (for example Redis).
|
||||||
- Players have no names. Screens show "You" and "Rival". A nickname field would be an easy addition.
|
- 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.
|
- 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.
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,6 @@
|
||||||
# mastermind
|
# mastermind
|
||||||
|
|
||||||
Mastermind Game
|
Mastermind Game
|
||||||
|
|
||||||
|
$ docker compose up -d --build
|
||||||
|
$ docker compose down --rmi all
|
||||||
|
|
@ -10,7 +10,7 @@
|
||||||
</parent>
|
</parent>
|
||||||
<groupId>com.mmkilic.game</groupId>
|
<groupId>com.mmkilic.game</groupId>
|
||||||
<artifactId>ApiMastermind</artifactId>
|
<artifactId>ApiMastermind</artifactId>
|
||||||
<version>0.2</version>
|
<version>0.3</version>
|
||||||
<name>ApiMastermind</name>
|
<name>ApiMastermind</name>
|
||||||
<description>Mastermind Game REST API</description>
|
<description>Mastermind Game REST API</description>
|
||||||
<url/>
|
<url/>
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,12 @@ import java.util.List;
|
||||||
|
|
||||||
public record PlayerView(
|
public record PlayerView(
|
||||||
int slot,
|
int slot,
|
||||||
|
/** true while the player is polling (online). */
|
||||||
boolean connected,
|
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? */
|
/** PLAYER_GUESSTURES: has this player chosen the number for the rival? */
|
||||||
boolean secretChosen,
|
boolean secretChosen,
|
||||||
/** Own view only: the number you chose for the rival. */
|
/** Own view only: the number you chose for the rival. */
|
||||||
|
|
|
||||||
|
|
@ -28,8 +28,13 @@ import com.mmkilic.game.service.NumberRules;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* In-memory multiplayer games (no database). Every player is identified by a random token
|
* 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;
|
* 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.
|
* <ul>
|
||||||
|
* <li>A game only ends early when a player explicitly leaves ({@link #leave}, the Abort button).</li>
|
||||||
|
* <li>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.</li>
|
||||||
|
* <li>A player that has not polled for {@code playerTimeoutMs} (e.g. lost the token) is treated as having left.</li>
|
||||||
|
* </ul>
|
||||||
*/
|
*/
|
||||||
@Service
|
@Service
|
||||||
public class MultiGameService {
|
public class MultiGameService {
|
||||||
|
|
@ -39,12 +44,15 @@ public class MultiGameService {
|
||||||
private final Object createLock = new Object();
|
private final Object createLock = new Object();
|
||||||
|
|
||||||
private final long playerTimeoutMs;
|
private final long playerTimeoutMs;
|
||||||
|
private final long offlineAfterMs;
|
||||||
private final long closedRetentionMs;
|
private final long closedRetentionMs;
|
||||||
|
|
||||||
public MultiGameService(
|
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) {
|
@Value("${multiplayer.closed-retention-ms:300000}") long closedRetentionMs) {
|
||||||
this.playerTimeoutMs = playerTimeoutMs;
|
this.playerTimeoutMs = playerTimeoutMs;
|
||||||
|
this.offlineAfterMs = offlineAfterMs;
|
||||||
this.closedRetentionMs = closedRetentionMs;
|
this.closedRetentionMs = closedRetentionMs;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -297,12 +305,12 @@ public class MultiGameService {
|
||||||
roundBased ? game.getCompletedRounds() + 1 : me.getAttempts() + 1,
|
roundBased ? game.getCompletedRounds() + 1 : me.getAttempts() + 1,
|
||||||
canGuess, waitingForRival,
|
canGuess, waitingForRival,
|
||||||
"SETUP".equals(stage),
|
"SETUP".equals(stage),
|
||||||
playerView(game, me, true),
|
playerView(game, me, true, now),
|
||||||
rival == null ? null : playerView(game, rival, false),
|
rival == null ? null : playerView(game, rival, false, now),
|
||||||
outcome, game.getEndReason(), me.isLeft());
|
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 closed = game.getStatus() == GameStatus.CLOSED;
|
||||||
boolean roundBased = game.getType().isRoundBased();
|
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.
|
// Score and time: always for yourself once found, for the rival only when the game is over.
|
||||||
boolean showResult = closed || (own && p.isFound());
|
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(
|
return new PlayerView(
|
||||||
p.getSlot(),
|
p.getSlot(),
|
||||||
!p.isLeft(),
|
connected,
|
||||||
|
p.isLeft(),
|
||||||
|
returnWithinMs,
|
||||||
p.getSecretForRival() != null,
|
p.getSecretForRival() != null,
|
||||||
own ? p.getSecretForRival() : null,
|
own ? p.getSecretForRival() : null,
|
||||||
p.getAttempts(),
|
p.getAttempts(),
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,11 @@ spring.application.name=ApiMastermind
|
||||||
server.port=8080
|
server.port=8080
|
||||||
server.servlet.context-path=/api-mastermind
|
server.servlet.context-path=/api-mastermind
|
||||||
# Multiplayer (in-memory, no database)
|
# Multiplayer (in-memory, no database)
|
||||||
# A player that has not polled the game for this long is treated as having left.
|
# Closing the tab or losing the connection does not end a game; only the Abort button does.
|
||||||
multiplayer.player-timeout-ms=20000
|
# 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.
|
# Closed games stay in the lobby list for this long.
|
||||||
multiplayer.closed-retention-ms=300000
|
multiplayer.closed-retention-ms=300000
|
||||||
multiplayer.sweep-interval-ms=2000
|
multiplayer.sweep-interval-ms=2000
|
||||||
|
|
|
||||||
|
|
@ -22,3 +22,11 @@ There is a time counter in this game. the game continue until both user find the
|
||||||
Please create a score calculation rule depening on time and turn count.
|
Please create a score calculation rule depening on time and turn count.
|
||||||
Please update api service and web application.
|
Please update api service and web application.
|
||||||
Finally please create a summary note in the current directory
|
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
|
||||||
|
|
@ -3,6 +3,7 @@
|
||||||
const apiURL = process.env.NEXT_PUBLIC_API_URL || '';
|
const apiURL = process.env.NEXT_PUBLIC_API_URL || '';
|
||||||
const GAMES = `${apiURL}/multi/games`;
|
const GAMES = `${apiURL}/multi/games`;
|
||||||
const SESSION_KEY = 'mastermind.multi';
|
const SESSION_KEY = 'mastermind.multi';
|
||||||
|
const MY_GAMES_KEY = 'mastermind.multi.myGames';
|
||||||
|
|
||||||
export const GAME_TYPES = {
|
export const GAME_TYPES = {
|
||||||
AUTO_GUESSTURES: {
|
AUTO_GUESSTURES: {
|
||||||
|
|
@ -59,20 +60,48 @@ export const chooseSecret = (id, token, number) =>
|
||||||
export const leaveGame = (id, token) =>
|
export const leaveGame = (id, token) =>
|
||||||
call(`/${id}/leave`, { method: 'POST', token }).catch(() => {});
|
call(`/${id}/leave`, { method: 'POST', token }).catch(() => {});
|
||||||
|
|
||||||
/** Fire-and-forget leave that survives page close/refresh. */
|
// The active game of a tab lives in sessionStorage so every browser tab can be a separate player.
|
||||||
export function leaveGameBeacon(id, token) {
|
// Every token is also remembered in localStorage ("my games") so a player who closed the tab,
|
||||||
const url = `${GAMES}/${id}/leave?token=${encodeURIComponent(token)}`;
|
// refreshed or lost the connection can resume the game from the lobby.
|
||||||
try {
|
export function saveSession(gameId, token, slot) {
|
||||||
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) {
|
|
||||||
try {
|
try {
|
||||||
sessionStorage.setItem(SESSION_KEY, JSON.stringify({ gameId, token }));
|
sessionStorage.setItem(SESSION_KEY, JSON.stringify({ gameId, token }));
|
||||||
} catch {}
|
} 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() {
|
export function loadSession() {
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
import { useCallback, useState } from 'react';
|
import { useCallback, useState } from 'react';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { useRouter } from 'next/navigation';
|
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';
|
import useTicker from './useTicker';
|
||||||
|
|
||||||
const STATUS_STYLE = {
|
const STATUS_STYLE = {
|
||||||
|
|
@ -18,10 +18,13 @@ export default function MultiplayerLobby() {
|
||||||
const [showCreate, setShowCreate] = useState(false);
|
const [showCreate, setShowCreate] = useState(false);
|
||||||
const [joining, setJoining] = useState(null);
|
const [joining, setJoining] = useState(null);
|
||||||
const [joinError, setJoinError] = useState('');
|
const [joinError, setJoinError] = useState('');
|
||||||
|
const [myGames, setMyGames] = useState([]);
|
||||||
|
|
||||||
const refresh = useCallback(async () => {
|
const refresh = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
setGames(await listGames());
|
const list = await listGames();
|
||||||
|
setGames(list);
|
||||||
|
setMyGames(pruneMyGames(list));
|
||||||
setListError('');
|
setListError('');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setListError(err.message || 'Cannot reach the server');
|
setListError(err.message || 'Cannot reach the server');
|
||||||
|
|
@ -31,7 +34,13 @@ export default function MultiplayerLobby() {
|
||||||
useTicker(refresh, 3000);
|
useTicker(refresh, 3000);
|
||||||
|
|
||||||
const enterGame = (res) => {
|
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');
|
router.push('/multiplayer/play');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -79,7 +88,9 @@ export default function MultiplayerLobby() {
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<ul className="flex flex-col gap-2">
|
<ul className="flex flex-col gap-2">
|
||||||
{games?.map((g) => (
|
{games?.map((g) => {
|
||||||
|
const mine = myGames.filter((m) => m.gameId === g.id);
|
||||||
|
return (
|
||||||
<li
|
<li
|
||||||
key={g.id}
|
key={g.id}
|
||||||
className={`flex items-center gap-2 sm:gap-3 p-3 sm:p-4 rounded-lg bg-neutral-800 border border-neutral-700 ${
|
className={`flex items-center gap-2 sm:gap-3 p-3 sm:p-4 rounded-lg bg-neutral-800 border border-neutral-700 ${
|
||||||
|
|
@ -95,7 +106,17 @@ export default function MultiplayerLobby() {
|
||||||
<span className={`shrink-0 text-xs px-2 py-1 rounded-full border ${STATUS_STYLE[g.status]}`}>
|
<span className={`shrink-0 text-xs px-2 py-1 rounded-full border ${STATUS_STYLE[g.status]}`}>
|
||||||
{g.status.toLowerCase()}
|
{g.status.toLowerCase()}
|
||||||
</span>
|
</span>
|
||||||
{g.status === 'WAITING' && (
|
{g.status !== 'CLOSED' &&
|
||||||
|
mine.map((m) => (
|
||||||
|
<button
|
||||||
|
key={m.token}
|
||||||
|
onClick={() => handleResume(m)}
|
||||||
|
className="shrink-0 px-3 sm:px-4 py-2 rounded bg-purple-600 hover:bg-purple-700 text-sm font-semibold"
|
||||||
|
>
|
||||||
|
Resume{mine.length > 1 && m.slot ? ` P${m.slot}` : ''}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
{g.status === 'WAITING' && mine.length === 0 && (
|
||||||
<button
|
<button
|
||||||
onClick={() => handleJoin(g.id)}
|
onClick={() => handleJoin(g.id)}
|
||||||
disabled={joining !== null}
|
disabled={joining !== null}
|
||||||
|
|
@ -105,7 +126,8 @@ export default function MultiplayerLobby() {
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</li>
|
</li>
|
||||||
))}
|
);
|
||||||
|
})}
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -5,19 +5,18 @@ import {
|
||||||
GAME_TYPES,
|
GAME_TYPES,
|
||||||
chooseSecret,
|
chooseSecret,
|
||||||
clearSession,
|
clearSession,
|
||||||
|
forgetGame,
|
||||||
formatTime,
|
formatTime,
|
||||||
getState,
|
getState,
|
||||||
leaveGame,
|
leaveGame,
|
||||||
leaveGameBeacon,
|
|
||||||
loadSession,
|
loadSession,
|
||||||
sendGuess,
|
sendGuess,
|
||||||
} from '../api';
|
} from '../api';
|
||||||
import NumberPad from '../NumberPad';
|
import NumberPad from '../NumberPad';
|
||||||
import useTicker from '../useTicker';
|
import useTicker from '../useTicker';
|
||||||
|
|
||||||
// Leaving on unmount is deferred so React StrictMode's mount → unmount → mount (dev) does not end the game.
|
// Closing the tab, refreshing or navigating away does NOT end the game: the player can resume it
|
||||||
let pendingLeave = null;
|
// from the lobby. Only the Abort button ends it (or not returning within the server's player timeout).
|
||||||
|
|
||||||
export default function MultiplayerPlayPage() {
|
export default function MultiplayerPlayPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [session, setSession] = useState(null);
|
const [session, setSession] = useState(null);
|
||||||
|
|
@ -45,6 +44,7 @@ export default function MultiplayerPlayPage() {
|
||||||
setState(data);
|
setState(data);
|
||||||
setReceivedAt(Date.now());
|
setReceivedAt(Date.now());
|
||||||
activeRef.current = data.stage !== 'FINISHED';
|
activeRef.current = data.stage !== 'FINISHED';
|
||||||
|
if (data.stage === 'FINISHED' && session) forgetGame(session.token);
|
||||||
};
|
};
|
||||||
|
|
||||||
const poll = useCallback(async () => {
|
const poll = useCallback(async () => {
|
||||||
|
|
@ -56,6 +56,7 @@ export default function MultiplayerPlayPage() {
|
||||||
if (err.status === 404 || err.status === 403) {
|
if (err.status === 404 || err.status === 403) {
|
||||||
activeRef.current = false;
|
activeRef.current = false;
|
||||||
clearSession();
|
clearSession();
|
||||||
|
forgetGame(session.token);
|
||||||
setFatal('This game is no longer available.');
|
setFatal('This game is no longer available.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -70,30 +71,6 @@ export default function MultiplayerPlayPage() {
|
||||||
return () => clearInterval(t);
|
return () => clearInterval(t);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// Closing / refreshing the tab or navigating away leaves the game.
|
|
||||||
useEffect(() => {
|
|
||||||
if (!session) return;
|
|
||||||
clearTimeout(pendingLeave);
|
|
||||||
const onPageHide = () => {
|
|
||||||
if (activeRef.current) leaveGameBeacon(session.gameId, session.token);
|
|
||||||
};
|
|
||||||
const onBeforeUnload = (e) => {
|
|
||||||
if (activeRef.current) {
|
|
||||||
e.preventDefault();
|
|
||||||
e.returnValue = '';
|
|
||||||
}
|
|
||||||
};
|
|
||||||
window.addEventListener('pagehide', onPageHide);
|
|
||||||
window.addEventListener('beforeunload', onBeforeUnload);
|
|
||||||
return () => {
|
|
||||||
window.removeEventListener('pagehide', onPageHide);
|
|
||||||
window.removeEventListener('beforeunload', onBeforeUnload);
|
|
||||||
if (activeRef.current) {
|
|
||||||
pendingLeave = setTimeout(() => leaveGameBeacon(session.gameId, session.token), 300);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}, [session]);
|
|
||||||
|
|
||||||
const runAction = async (fn) => {
|
const runAction = async (fn) => {
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
setActionError('');
|
setActionError('');
|
||||||
|
|
@ -113,12 +90,18 @@ export default function MultiplayerPlayPage() {
|
||||||
const handleGuess = (number) => runAction(() => sendGuess(session.gameId, session.token, number));
|
const handleGuess = (number) => runAction(() => sendGuess(session.gameId, session.token, number));
|
||||||
const handleSecret = (number) => runAction(() => chooseSecret(session.gameId, session.token, number));
|
const handleSecret = (number) => runAction(() => chooseSecret(session.gameId, session.token, number));
|
||||||
|
|
||||||
const handleLeave = async () => {
|
// Abort: ends the game for both players.
|
||||||
if (activeRef.current) {
|
const handleAbort = async () => {
|
||||||
if (!window.confirm('Leaving ends the game for both players. Leave?')) return;
|
if (!window.confirm('Aborting ends the game for both players and your rival wins. Abort?')) return;
|
||||||
activeRef.current = false;
|
activeRef.current = false;
|
||||||
await leaveGame(session.gameId, session.token);
|
await leaveGame(session.gameId, session.token);
|
||||||
}
|
forgetGame(session.token);
|
||||||
|
clearSession();
|
||||||
|
router.push('/multiplayer');
|
||||||
|
};
|
||||||
|
|
||||||
|
// Back to lobby: the game keeps running and can be resumed from the lobby.
|
||||||
|
const handleLobby = () => {
|
||||||
clearSession();
|
clearSession();
|
||||||
router.push('/multiplayer');
|
router.push('/multiplayer');
|
||||||
};
|
};
|
||||||
|
|
@ -142,12 +125,23 @@ export default function MultiplayerPlayPage() {
|
||||||
return (
|
return (
|
||||||
<main className="h-dvh w-full flex flex-col">
|
<main className="h-dvh w-full flex flex-col">
|
||||||
<header className="p-2 sm:p-4 bg-neutral-800 shadow-lg flex items-center gap-2 sm:gap-3">
|
<header className="p-2 sm:p-4 bg-neutral-800 shadow-lg flex items-center gap-2 sm:gap-3">
|
||||||
|
<div className="shrink-0 flex flex-col sm:flex-row gap-1 sm:gap-2">
|
||||||
<button
|
<button
|
||||||
onClick={handleLeave}
|
onClick={handleLobby}
|
||||||
className="px-2 sm:px-3 py-2 bg-rose-700 hover:bg-rose-800 rounded text-xs sm:text-sm shrink-0"
|
title={finished ? 'Back to lobby' : 'Back to lobby. The game keeps running and you can resume it.'}
|
||||||
|
className="px-2 sm:px-3 py-2 bg-neutral-700 hover:bg-neutral-600 rounded text-xs sm:text-sm"
|
||||||
>
|
>
|
||||||
{finished ? '← Lobby' : 'Leave'}
|
← Lobby
|
||||||
</button>
|
</button>
|
||||||
|
{!finished && (
|
||||||
|
<button
|
||||||
|
onClick={handleAbort}
|
||||||
|
className="px-2 sm:px-3 py-2 bg-rose-700 hover:bg-rose-800 rounded text-xs sm:text-sm"
|
||||||
|
>
|
||||||
|
Abort
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
<div className="flex-grow text-center min-w-0">
|
<div className="flex-grow text-center min-w-0">
|
||||||
<h1 className="text-lg sm:text-2xl font-bold truncate">{state.name}</h1>
|
<h1 className="text-lg sm:text-2xl font-bold truncate">{state.name}</h1>
|
||||||
<p className="text-xs sm:text-sm opacity-70 truncate">
|
<p className="text-xs sm:text-sm opacity-70 truncate">
|
||||||
|
|
@ -173,6 +167,15 @@ export default function MultiplayerPlayPage() {
|
||||||
<div className="md:flex-1 flex flex-col items-center p-4 sm:p-6 gap-4 sm:gap-6 md:overflow-y-auto">
|
<div className="md:flex-1 flex flex-col items-center p-4 sm:p-6 gap-4 sm:gap-6 md:overflow-y-auto">
|
||||||
{/* my-auto centres the content when there is room without clipping its top when there isn't */}
|
{/* my-auto centres the content when there is room without clipping its top when there isn't */}
|
||||||
<div className="my-auto w-full flex flex-col items-center gap-4 sm:gap-6">
|
<div className="my-auto w-full flex flex-col items-center gap-4 sm:gap-6">
|
||||||
|
{!finished && state.rival && !state.rival.connected && state.rival.returnWithinMs != null && (
|
||||||
|
<p className="w-full max-w-md text-center text-sm rounded-lg border border-amber-500/40 bg-amber-500/10 text-amber-300 px-3 py-2">
|
||||||
|
Your rival is offline. The game continues; they have{' '}
|
||||||
|
<span className="font-mono">
|
||||||
|
{formatTime(state.rival.returnWithinMs - (Date.now() - receivedAt))}
|
||||||
|
</span>{' '}
|
||||||
|
to come back before the game ends.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
{state.stage === 'WAITING' && <WaitingPanel state={state} />}
|
{state.stage === 'WAITING' && <WaitingPanel state={state} />}
|
||||||
{state.stage === 'SETUP' && (
|
{state.stage === 'SETUP' && (
|
||||||
<SetupPanel state={state} busy={busy} onSubmit={handleSecret} />
|
<SetupPanel state={state} busy={busy} onSubmit={handleSecret} />
|
||||||
|
|
@ -180,7 +183,7 @@ export default function MultiplayerPlayPage() {
|
||||||
{state.stage === 'PLAYING' && (
|
{state.stage === 'PLAYING' && (
|
||||||
<PlayingPanel state={state} busy={busy} onSubmit={handleGuess} />
|
<PlayingPanel state={state} busy={busy} onSubmit={handleGuess} />
|
||||||
)}
|
)}
|
||||||
{finished && <ResultPanel state={state} onBack={handleLeave} />}
|
{finished && <ResultPanel state={state} onBack={handleLobby} />}
|
||||||
{actionError && <p className="text-rose-400 text-sm">{actionError}</p>}
|
{actionError && <p className="text-rose-400 text-sm">{actionError}</p>}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -217,8 +220,8 @@ function WaitingPanel({ state }) {
|
||||||
<div className="w-12 h-12 rounded-full border-4 border-purple-500 border-t-transparent animate-spin" />
|
<div className="w-12 h-12 rounded-full border-4 border-purple-500 border-t-transparent animate-spin" />
|
||||||
<p className="text-xl font-semibold">Waiting for a rival to join…</p>
|
<p className="text-xl font-semibold">Waiting for a rival to join…</p>
|
||||||
<p className="opacity-70 max-w-sm">
|
<p className="opacity-70 max-w-sm">
|
||||||
Your friend can join <span className="font-semibold">“{state.name}”</span> from the Multiplayer lobby. Keep this
|
Your friend can join <span className="font-semibold">“{state.name}”</span> from the Multiplayer lobby. You can
|
||||||
page open: leaving closes the game.
|
go back to the lobby and resume this game later; use Abort to close it.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
@ -296,7 +299,10 @@ function ResultPanel({ state, onBack }) {
|
||||||
}[outcome] || ['Game Closed', 'text-neutral-300'];
|
}[outcome] || ['Game Closed', 'text-neutral-300'];
|
||||||
|
|
||||||
let reason = '';
|
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 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.';
|
else reason = you.found && rival?.found ? 'Both players found their number in the same round.' : 'A number was found.';
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -21,7 +21,7 @@ export default function Home() {
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
<footer className="absolute bottom-4 left-0 w-full text-center text-sm text-neutral-500">
|
<footer className="absolute bottom-4 left-0 w-full text-center text-sm text-neutral-500">
|
||||||
© 2025 Mehmet Kılıç. All rights reserved. V0.2
|
© 2025 Mehmet Kılıç. All rights reserved. V0.3
|
||||||
</footer>
|
</footer>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue