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

359 lines
13 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,
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;
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';
};
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();
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);
}, []);
// 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('');
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));
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);
}
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-screen w-full flex flex-col">
<header className="p-3 sm:p-4 bg-neutral-800 shadow-lg flex items-center gap-3">
<button onClick={handleLeave} className="px-3 py-2 bg-rose-700 hover:bg-rose-800 rounded text-sm shrink-0">
{finished ? '← Lobby' : 'Leave Game'}
</button>
<div className="flex-grow text-center min-w-0">
<h1 className="text-xl sm:text-2xl font-bold truncate">{state.name}</h1>
<p className="text-xs sm:text-sm opacity-70">
{type?.label} · {state.digits} digits
</p>
</div>
<div className="shrink-0 flex flex-col items-end gap-1 text-sm">
{(state.stage === 'PLAYING' || finished) && state.elapsedMs > 0 && (
<span className="bg-neutral-900 px-3 py-1 rounded-full border border-neutral-700 font-mono">
⏱ {formatTime(elapsed)}
</span>
)}
{roundBased && state.stage === 'PLAYING' && (
<span className="bg-neutral-900 px-3 py-1 rounded-full border border-neutral-700">Round {state.round}</span>
)}
</div>
</header>
<section className="flex-grow flex flex-col md:flex-row min-h-0">
<div className="flex-1 flex flex-col items-center justify-center p-6 gap-6 overflow-y-auto">
{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={handleLeave} />}
{actionError && <p className="text-rose-400 text-sm">{actionError}</p>}
</div>
{(state.stage === 'PLAYING' || finished) && (
<aside className="md:w-[28rem] grid grid-cols-2 gap-4 p-4 sm:p-6 border-t md:border-t-0 md:border-l border-neutral-800 overflow-y-auto max-h-[35vh] md:max-h-none">
<History title="Your guesses" history={state.you.history} />
{roundBased || finished ? (
<History title="Rival's guesses" history={state.rival?.history || []} />
) : (
<div>
<h3 className="text-lg font-semibold 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-screen 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. Keep this
page open: leaving closes the game.
</p>
</div>
);
}
function SetupPanel({ state, busy, onSubmit }) {
const { you, rival } = state;
return (
<>
<div className="text-center">
<p className="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-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 left the game.' : 'Your rival left the game.';
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 text-left opacity-70">{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-lg font-semibold 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-2 px-3 mb-2 bg-neutral-800 rounded border border-neutral-700 font-mono text-sm sm:text-base">
<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>
);
}