mastermind/web/app/multiplayer/api.js

99 lines
3.1 KiB
JavaScript

'use client';
const apiURL = process.env.NEXT_PUBLIC_API_URL || '';
const GAMES = `${apiURL}/multi/games`;
const SESSION_KEY = 'mastermind.multi';
export const GAME_TYPES = {
AUTO_GUESSTURES: {
label: 'Auto Guesstures',
short: 'Auto',
description:
'The game picks a different number for each player. Rounds are played together and you see both results after every round.',
},
PLAYER_GUESSTURES: {
label: 'Player Guesstures',
short: 'Player',
description:
'Each player chooses the number the rival has to find. Then rounds are played together like Auto Guesstures.',
},
TIME_CHALLENGE: {
label: 'Time Challenge',
short: 'Time',
description:
'Both players find the same number, independently and against the clock. Rival guesses stay hidden. Best score wins.',
},
};
async function call(path, { method = 'GET', token, body } = {}) {
const headers = {};
if (body !== undefined) headers['Content-Type'] = 'application/json';
if (token) headers['X-Player-Token'] = token;
const res = await fetch(`${GAMES}${path}`, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
});
if (!res.ok) {
let message = '';
try {
message = (await res.json()).message;
} catch {}
const err = new Error(message || `Server error (HTTP ${res.status})`);
err.status = res.status;
throw err;
}
return res.status === 204 ? null : res.json();
}
export const listGames = () => call('');
export const createGame = (name, digits, type) =>
call('', { method: 'POST', body: { name, digits, type } });
export const joinGame = (id) => call(`/${id}/join`, { method: 'POST' });
export const getState = (id, token) => call(`/${id}/state`, { token });
export const sendGuess = (id, token, number) =>
call(`/${id}/guess`, { method: 'POST', token, body: { number } });
export const chooseSecret = (id, token, number) =>
call(`/${id}/secret`, { method: 'POST', token, body: { 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) {
try {
sessionStorage.setItem(SESSION_KEY, JSON.stringify({ gameId, token }));
} catch {}
}
export function loadSession() {
try {
return JSON.parse(sessionStorage.getItem(SESSION_KEY)) || null;
} catch {
return null;
}
}
export function clearSession() {
try {
sessionStorage.removeItem(SESSION_KEY);
} catch {}
}
export function formatTime(ms) {
if (ms == null) return '-';
const total = Math.max(0, Math.floor(ms / 1000));
const m = Math.floor(total / 60);
const s = total % 60;
return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
}