128 lines
4.0 KiB
JavaScript
128 lines
4.0 KiB
JavaScript
'use client';
|
|
|
|
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: {
|
|
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(() => {});
|
|
|
|
// 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() {
|
|
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')}`;
|
|
}
|