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.
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
# mastermind
|
||||
|
||||
Mastermind Game
|
||||
Mastermind Game
|
||||
|
||||
$ docker compose up -d --build
|
||||
$ docker compose down --rmi all
|
||||
|
|
@ -10,7 +10,7 @@
|
|||
</parent>
|
||||
<groupId>com.mmkilic.game</groupId>
|
||||
<artifactId>ApiMastermind</artifactId>
|
||||
<version>0.2</version>
|
||||
<version>0.3</version>
|
||||
<name>ApiMastermind</name>
|
||||
<description>Mastermind Game REST API</description>
|
||||
<url/>
|
||||
|
|
|
|||
|
|
@ -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. */
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
* <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
|
||||
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(),
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
10
notes.txt
10
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
|
||||
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 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() {
|
||||
|
|
|
|||
|
|
@ -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() {
|
|||
)}
|
||||
|
||||
<ul className="flex flex-col gap-2">
|
||||
{games?.map((g) => (
|
||||
{games?.map((g) => {
|
||||
const mine = myGames.filter((m) => m.gameId === g.id);
|
||||
return (
|
||||
<li
|
||||
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 ${
|
||||
|
|
@ -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]}`}>
|
||||
{g.status.toLowerCase()}
|
||||
</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
|
||||
onClick={() => handleJoin(g.id)}
|
||||
disabled={joining !== null}
|
||||
|
|
@ -105,7 +126,8 @@ export default function MultiplayerLobby() {
|
|||
</button>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
|
|
|
|||
|
|
@ -5,19 +5,18 @@ import {
|
|||
GAME_TYPES,
|
||||
chooseSecret,
|
||||
clearSession,
|
||||
forgetGame,
|
||||
formatTime,
|
||||
getState,
|
||||
leaveGame,
|
||||
leaveGameBeacon,
|
||||
loadSession,
|
||||
sendGuess,
|
||||
} from '../api';
|
||||
import NumberPad from '../NumberPad';
|
||||
import useTicker from '../useTicker';
|
||||
|
||||
// Leaving on unmount is deferred so React StrictMode's mount → unmount → mount (dev) does not end the game.
|
||||
let pendingLeave = null;
|
||||
|
||||
// Closing the tab, refreshing or navigating away does NOT end the game: the player can resume it
|
||||
// from the lobby. Only the Abort button ends it (or not returning within the server's player timeout).
|
||||
export default function MultiplayerPlayPage() {
|
||||
const router = useRouter();
|
||||
const [session, setSession] = useState(null);
|
||||
|
|
@ -45,6 +44,7 @@ export default function MultiplayerPlayPage() {
|
|||
setState(data);
|
||||
setReceivedAt(Date.now());
|
||||
activeRef.current = data.stage !== 'FINISHED';
|
||||
if (data.stage === 'FINISHED' && session) forgetGame(session.token);
|
||||
};
|
||||
|
||||
const poll = useCallback(async () => {
|
||||
|
|
@ -56,6 +56,7 @@ export default function MultiplayerPlayPage() {
|
|||
if (err.status === 404 || err.status === 403) {
|
||||
activeRef.current = false;
|
||||
clearSession();
|
||||
forgetGame(session.token);
|
||||
setFatal('This game is no longer available.');
|
||||
}
|
||||
}
|
||||
|
|
@ -70,30 +71,6 @@ export default function MultiplayerPlayPage() {
|
|||
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) => {
|
||||
setBusy(true);
|
||||
setActionError('');
|
||||
|
|
@ -113,12 +90,18 @@ export default function MultiplayerPlayPage() {
|
|||
const handleGuess = (number) => runAction(() => sendGuess(session.gameId, session.token, number));
|
||||
const handleSecret = (number) => runAction(() => chooseSecret(session.gameId, session.token, number));
|
||||
|
||||
const handleLeave = async () => {
|
||||
if (activeRef.current) {
|
||||
if (!window.confirm('Leaving ends the game for both players. Leave?')) return;
|
||||
activeRef.current = false;
|
||||
await leaveGame(session.gameId, session.token);
|
||||
}
|
||||
// Abort: ends the game for both players.
|
||||
const handleAbort = async () => {
|
||||
if (!window.confirm('Aborting ends the game for both players and your rival wins. Abort?')) return;
|
||||
activeRef.current = false;
|
||||
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();
|
||||
router.push('/multiplayer');
|
||||
};
|
||||
|
|
@ -142,12 +125,23 @@ export default function MultiplayerPlayPage() {
|
|||
return (
|
||||
<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">
|
||||
<button
|
||||
onClick={handleLeave}
|
||||
className="px-2 sm:px-3 py-2 bg-rose-700 hover:bg-rose-800 rounded text-xs sm:text-sm shrink-0"
|
||||
>
|
||||
{finished ? '← Lobby' : 'Leave'}
|
||||
</button>
|
||||
<div className="shrink-0 flex flex-col sm:flex-row gap-1 sm:gap-2">
|
||||
<button
|
||||
onClick={handleLobby}
|
||||
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"
|
||||
>
|
||||
← Lobby
|
||||
</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">
|
||||
<h1 className="text-lg sm:text-2xl font-bold truncate">{state.name}</h1>
|
||||
<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">
|
||||
{/* 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">
|
||||
{!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 === 'SETUP' && (
|
||||
<SetupPanel state={state} busy={busy} onSubmit={handleSecret} />
|
||||
|
|
@ -180,7 +183,7 @@ export default function MultiplayerPlayPage() {
|
|||
{state.stage === 'PLAYING' && (
|
||||
<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>}
|
||||
</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" />
|
||||
<p className="text-xl font-semibold">Waiting for a rival to join…</p>
|
||||
<p className="opacity-70 max-w-sm">
|
||||
Your friend can join <span className="font-semibold">“{state.name}”</span> from the Multiplayer lobby. Keep this
|
||||
page open: leaving closes the game.
|
||||
Your friend can join <span className="font-semibold">“{state.name}”</span> from the Multiplayer lobby. You can
|
||||
go back to the lobby and resume this game later; use Abort to close it.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
|
|
@ -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.';
|
||||
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ export default function Home() {
|
|||
</Link>
|
||||
</div>
|
||||
<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>
|
||||
</main>
|
||||
);
|
||||
|
|
|
|||
Loading…
Reference in New Issue