mastermind/web/app/multiplayer/api.js

128 lines
4.0 KiB
JavaScript
Raw Normal View History

2026-11-21 22:37:05 +03:00
'use client';
const apiURL = process.env.NEXT_PUBLIC_API_URL || '';
const GAMES = `${apiURL}/multi/games`;
const SESSION_KEY = 'mastermind.multi';
2026-11-22 16:11:04 +03:00
const MY_GAMES_KEY = 'mastermind.multi.myGames';
2026-11-21 22:37:05 +03:00
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(() => {});
2026-11-22 16:11:04 +03:00
// 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) {
2026-11-21 22:37:05 +03:00
try {
2026-11-22 16:11:04 +03:00
sessionStorage.setItem(SESSION_KEY, JSON.stringify({ gameId, token }));
2026-11-21 22:37:05 +03:00
} catch {}
2026-11-22 16:11:04 +03:00
rememberGame(gameId, token, slot);
2026-11-21 22:37:05 +03:00
}
2026-11-22 16:11:04 +03:00
export function loadMyGames() {
2026-11-21 22:37:05 +03:00
try {
2026-11-22 16:11:04 +03:00
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));
2026-11-21 22:37:05 +03:00
} catch {}
}
2026-11-22 16:11:04 +03:00
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;
}
2026-11-21 22:37:05 +03:00
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')}`;
}