mastermind/web/app/multiplayer/play/page.js

377 lines
14 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import {
GAME_TYPES,
chooseSecret,
clearSession,
forgetGame,
formatTime,
getState,
leaveGame,
loadSession,
sendGuess,
} from '../api';
import NumberPad from '../NumberPad';
import useTicker from '../useTicker';
// 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);
const [state, setState] = useState(null);
const [receivedAt, setReceivedAt] = useState(0);
const [fatal, setFatal] = useState('');
const [actionError, setActionError] = useState('');
const [busy, setBusy] = useState(false);
const [, setClock] = useState(0);
const seq = useRef(0);
const applied = useRef(0);
const activeRef = useRef(false);
useEffect(() => {
const s = loadSession();
if (!s) router.replace('/multiplayer');
else setSession(s);
}, [router]);
// Ignore responses that are older than the latest applied one (poll vs. guess races).
const apply = (id, data) => {
if (id < applied.current) return;
applied.current = id;
setState(data);
setReceivedAt(Date.now());
activeRef.current = data.stage !== 'FINISHED';
if (data.stage === 'FINISHED' && session) forgetGame(session.token);
};
const poll = useCallback(async () => {
if (!session) return;
const id = ++seq.current;
try {
apply(id, await getState(session.gameId, session.token));
} catch (err) {
if (err.status === 404 || err.status === 403) {
activeRef.current = false;
clearSession();
forgetGame(session.token);
setFatal('This game is no longer available.');
}
}
}, [session]);
const finished = state?.stage === 'FINISHED';
useTicker(poll, 1000, !!session && !finished && !fatal);
// Local clock for the timer display.
useEffect(() => {
const t = setInterval(() => setClock((c) => c + 1), 500);
return () => clearInterval(t);
}, []);
const runAction = async (fn) => {
setBusy(true);
setActionError('');
const id = ++seq.current;
try {
apply(id, await fn());
return true;
} catch (err) {
setActionError(err.message);
poll();
return false;
} finally {
setBusy(false);
}
};
const handleGuess = (number) => runAction(() => sendGuess(session.gameId, session.token, number));
const handleSecret = (number) => runAction(() => chooseSecret(session.gameId, session.token, number));
// 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');
};
if (fatal) {
return (
<CenterMessage>
<p className="text-xl">{fatal}</p>
<button onClick={() => router.push('/multiplayer')} className="px-4 py-2 rounded bg-purple-600 hover:bg-purple-700">
Back to lobby
</button>
</CenterMessage>
);
}
if (!state) return <CenterMessage><p className="opacity-70">Loading game…</p></CenterMessage>;
const type = GAME_TYPES[state.type];
const roundBased = state.type !== 'TIME_CHALLENGE';
const elapsed = state.stage === 'PLAYING' ? state.elapsedMs + (Date.now() - receivedAt) : state.elapsedMs;
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">
<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">
{type?.label} · {state.digits} digits
</p>
</div>
<div className="shrink-0 flex flex-col items-end gap-1 text-xs sm:text-sm">
{(state.stage === 'PLAYING' || finished) && state.elapsedMs > 0 && (
<span className="bg-neutral-900 px-2 sm:px-3 py-0.5 sm:py-1 rounded-full border border-neutral-700 font-mono">
⏱ {formatTime(elapsed)}
</span>
)}
{roundBased && state.stage === 'PLAYING' && (
<span className="bg-neutral-900 px-2 sm:px-3 py-0.5 sm:py-1 rounded-full border border-neutral-700">
Round {state.round}
</span>
)}
</div>
</header>
{/* Mobile: one scrolling column (game, then history). Desktop: side by side, each scrolls on its own. */}
<section className="flex-grow flex flex-col md:flex-row min-h-0 overflow-y-auto md:overflow-hidden">
<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} />
)}
{state.stage === 'PLAYING' && (
<PlayingPanel state={state} busy={busy} onSubmit={handleGuess} />
)}
{finished && <ResultPanel state={state} onBack={handleLobby} />}
{actionError && <p className="text-rose-400 text-sm">{actionError}</p>}
</div>
</div>
{(state.stage === 'PLAYING' || finished) && (
<aside className="md:w-[28rem] shrink-0 grid grid-cols-2 content-start gap-3 sm:gap-4 p-3 sm:p-6 border-t md:border-t-0 md:border-l border-neutral-800 md:overflow-y-auto">
<History title="Your guesses" history={state.you.history} />
{roundBased || finished ? (
<History title="Rival's guesses" history={state.rival?.history || []} />
) : (
<div>
<h3 className="text-base sm:text-lg font-semibold mb-2 sm:mb-3">Rival</h3>
<p className="text-sm opacity-70 mb-2">Rival guesses are hidden in Time Challenge.</p>
<p>Attempts: {state.rival?.attempts ?? 0}</p>
<p className={state.rival?.found ? 'text-emerald-400' : 'opacity-70'}>
{state.rival?.found ? 'Found the number!' : 'Still searching…'}
</p>
</div>
)}
</aside>
)}
</section>
</main>
);
}
function CenterMessage({ children }) {
return <main className="h-dvh w-full flex flex-col items-center justify-center gap-4 p-6 text-center">{children}</main>;
}
function WaitingPanel({ state }) {
return (
<div className="text-center flex flex-col items-center gap-4">
<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. You can
go back to the lobby and resume this game later; use Abort to close it.
</p>
</div>
);
}
function SetupPanel({ state, busy, onSubmit }) {
const { you, rival } = state;
return (
<>
<div className="text-center">
<p className="text-lg sm:text-xl font-semibold">Choose a {state.digits}-digit number for your rival</p>
<p className="text-sm opacity-70">Each digit can be used only once.</p>
</div>
<NumberPad
digitNumber={state.digits}
onSubmit={onSubmit}
busy={busy}
submitLabel={you.secretChosen ? 'Change Number' : 'Set Number'}
/>
<div className="text-center text-sm">
{you.secretChosen && (
<p>
Your rival will search for <span className="font-mono font-bold text-purple-300">{you.secretForRival}</span>
</p>
)}
<p className={rival?.secretChosen ? 'text-emerald-400' : 'opacity-70 animate-pulse'}>
{rival?.secretChosen ? 'Rival has chosen your number.' : 'Rival is choosing your number…'}
</p>
</div>
</>
);
}
function PlayingPanel({ state, busy, onSubmit }) {
const { you, rival } = state;
const roundBased = state.type !== 'TIME_CHALLENGE';
let status;
if (roundBased) {
if (state.waitingForRival) status = <span className="animate-pulse">Waiting for your rival&apos;s guess…</span>;
else if (rival && rival.attempts >= state.round) status = <span className="text-amber-300">Your rival has guessed. Your turn!</span>;
else status = 'Make your guess.';
} else if (you.found) {
status = (
<span className="text-emerald-400">
You found it in {you.attempts} turns ({formatTime(you.timeMs)}), score {you.score}. Waiting for your rival to
finish…
</span>
);
} else {
status = 'Find the number as fast as you can!';
}
return (
<>
<p className="text-center text-base sm:text-lg">{status}</p>
{!(state.type === 'TIME_CHALLENGE' && you.found) && (
<NumberPad digitNumber={state.digits} onSubmit={onSubmit} busy={busy} disabled={!state.canGuess} />
)}
{state.type === 'PLAYER_GUESSTURES' && you.secretForRival && (
<p className="text-sm opacity-70">
Your rival is searching for <span className="font-mono">{you.secretForRival}</span>
</p>
)}
</>
);
}
function ResultPanel({ state, onBack }) {
const { you, rival, outcome, endReason, youLeft } = state;
const banner = {
WIN: ['You Won!', 'text-emerald-400'],
LOSE: ['You Lost', 'text-rose-400'],
DRAW: ['Draw', 'text-amber-300'],
}[outcome] || ['Game Closed', 'text-neutral-300'];
let reason = '';
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.';
const rows = [
['Number to find', (p) => <span className="font-mono">{p?.numberToFind ?? '-'}</span>],
['Found', (p) => (p?.found ? '✔' : '✘')],
['Turns', (p) => p?.attempts ?? '-'],
['Time', (p) => formatTime(p?.timeMs)],
['Score', (p) => <span className="font-bold">{p?.score ?? '-'}</span>],
];
return (
<div className="flex flex-col items-center gap-4 w-full max-w-md">
<p className={`text-3xl font-bold ${banner[1]}`}>{banner[0]}</p>
<p className="opacity-80">{reason}</p>
{rival && (
<table className="w-full text-center border-collapse">
<thead>
<tr className="border-b border-neutral-700">
<th />
<th className="py-2">You</th>
<th className="py-2">Rival</th>
</tr>
</thead>
<tbody>
{rows.map(([label, render]) => (
<tr key={label} className="border-b border-neutral-800">
<td className="py-2 pr-2 text-left opacity-70 text-sm sm:text-base">{label}</td>
<td>{render(you)}</td>
<td>{render(rival)}</td>
</tr>
))}
</tbody>
</table>
)}
<p className="text-xs opacity-60 text-center">
Score = 1000 × digits − 100 × turns − 2 × seconds (min 100 if found, 0 if not found).
</p>
<button onClick={onBack} className="px-6 py-2 rounded bg-purple-600 hover:bg-purple-700 font-semibold">
Back to lobby
</button>
</div>
);
}
function History({ title, history }) {
const items = [...history].reverse();
return (
<div className="min-w-0">
<h3 className="text-base sm:text-lg font-semibold mb-2 sm:mb-3">{title}</h3>
{items.length === 0 && <p className="opacity-60 text-sm">No guesses yet.</p>}
{items.map((h) => (
<div
key={h.turn}
className="py-1.5 sm:py-2 px-2 sm:px-3 mb-2 bg-neutral-800 rounded border border-neutral-700 font-mono text-xs sm:text-base break-all"
>
<span className="opacity-50 mr-2">{h.turn}.</span>
{h.guess}
{h.positive === null ? (
<span className="opacity-60"> …</span>
) : (
<>
<span className="text-emerald-400"> +{h.positive}</span>
<span className="text-rose-400"> -{h.negative}</span>
</>
)}
</div>
))}
</div>
);
}