feat(tour): better frontend for tournament start phase, and auto start after X seconds

This commit is contained in:
Maieul BOYER 2026-01-10 17:43:04 +01:00 committed by Maix0
parent 3c95af8ede
commit 901e3e5a8e
6 changed files with 140 additions and 42 deletions

View file

@ -2,22 +2,29 @@
<div id="mainbox" class="pong-mainboxDisplay rounded-elem"> <div id="mainbox" class="pong-mainboxDisplay rounded-elem">
<div class="grid grid-cols-3"> <div class="grid grid-cols-3">
<div class="flex flex-col gap-2"> <div class="flex flex-col gap-2">
<button id="QueueBtn" class="fit-all pong-btn-style gray-color rounded-elem blue-hover">Queue Up</button> <button id="QueueBtn" class="fit-all pong-btn-style gray-color rounded-elem blue-hover">Queue
<button id="LocalBtn" class="fit-all pong-btn-style gray-color rounded-elem blue-hover">Local Game</button> Up</button>
<button id="LocalBtn" class="fit-all pong-btn-style gray-color rounded-elem blue-hover">Local
Game</button>
<button id="TourBtn" class="fit-all pong-btn-style gray-color rounded-elem blue-hover"> <button id="TourBtn" class="fit-all pong-btn-style gray-color rounded-elem blue-hover">
<span class="mx-2">Create Tournament</span> <span class="mx-2">Create Tournament</span>
</button> <!-- tournament hdl --> </button>
<!-- tournament hdl -->
</div> </div>
<div class="flex flex-col gap-2"> <div class="flex flex-col gap-2">
<h1 class="page-title">Pong Box</h1> <h1 class="page-title">Pong Box</h1>
<br> <br />
</div> </div>
<div class="flex flex-col gap-2 items-end"> <div class="flex flex-col gap-2 items-end">
<span id="queue-info" class="fit-all rounded-elem gray-color text-white">?👤 ?⏳ ?▮•▮</span> <!-- total | in queue | games--> <span id="queue-info" class="fit-all rounded-elem gray-color text-white">?👤 ?⏳ ?▮•▮</span>
<button id="play-info" class="circle-8 pong-btn-style gray-color blue-hover">?</button> <!-- how to play? pong-how-to-play rounded-elem rounded-full blue-hover--> <!-- total | in queue | games-->
<span id="tour-info" class="fit-all rounded-elem gray-color text-white">⚪️ ?👤 ?▮•▮</span>
<!-- [Owner|Registered|NotRegisterd|nonExistant] | Player | games -->
<!-- 👑 ✅ ❌ ⚪️ -->
<button id="play-info" class="circle-8 pong-btn-style gray-color blue-hover">?</button>
<!-- how to play? pong-how-to-play rounded-elem rounded-full blue-hover-->
</div> </div>
</div> </div>
<!-- Horizontal Message Box --> <!-- Horizontal Message Box -->
<div id="score-box" class="grid grid-cols-3 items-center"> <div id="score-box" class="grid grid-cols-3 items-center">
<h1 id="player-left"></h1> <h1 id="player-left"></h1>
@ -34,11 +41,13 @@
<kbd class="pong-protips-key">W</kbd> <kbd class="pong-protips-key">W</kbd>
down: down:
<kbd class="pong-protips-key">S</kbd> <kbd class="pong-protips-key">S</kbd>
<br> <br />
You are <span class="text-red-500">red</span>. <br> Your goal is to bounce the ball back to the You are <span class="text-red-500">red</span>.
adversary. <br />
<br> Your goal is to bounce the ball back to the adversary.
<span class="text-gray-400">local games keys for the left paddle:<br> <br />
<span class="text-gray-400">local games keys for the left paddle:
<br />
up: up:
<kbd class="disp-key">O</kbd> <kbd class="disp-key">O</kbd>
down: down:
@ -56,4 +65,4 @@
</div> </div>
</div> </div>
</div> </div>
</div> </div>

View file

@ -42,6 +42,14 @@ enum TourBtnState {
AbeToProcreate = "He would be proud", AbeToProcreate = "He would be proud",
} }
enum TourInfoState {
Running = "🟢",
Owner = "👑",
Registered = "✅",
NotRegisted = "❌",
NoTournament = "⚪️",
}
document.addEventListener("ft:pageChange", (newUrl) => { document.addEventListener("ft:pageChange", (newUrl) => {
if ( if (
newUrl.detail.startsWith("/app/pong") || newUrl.detail.startsWith("/app/pong") ||
@ -105,6 +113,8 @@ function pongClient(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
document.querySelector<HTMLDivElement>("#pong-end-screen"); document.querySelector<HTMLDivElement>("#pong-end-screen");
const tournamentBtn = const tournamentBtn =
document.querySelector<HTMLButtonElement>("#TourBtn"); document.querySelector<HTMLButtonElement>("#TourBtn");
const tour_infos =
document.querySelector<HTMLSpanElement>("#tour-info");
let socket = getSocket(); let socket = getSocket();
@ -126,7 +136,8 @@ function pongClient(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
!LocalGameBtn || !LocalGameBtn ||
!rdy_btn || !rdy_btn ||
!end_scr || !end_scr ||
!tournamentBtn !tournamentBtn ||
!tour_infos
) )
// sanity check // sanity check
return showError("fatal error"); return showError("fatal error");
@ -137,7 +148,7 @@ function pongClient(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
switch (tournamentBtn.innerText) { switch (tournamentBtn.innerText) {
case TourBtnState.AbleToStart: case TourBtnState.AbleToStart:
//socket.emit('') socket.emit('tourStart')
break; break;
case TourBtnState.AbleToJoin: case TourBtnState.AbleToJoin:
socket.emit("tourRegister"); socket.emit("tourRegister");
@ -152,8 +163,6 @@ function pongClient(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
socket.emit("tourUnregister"); socket.emit("tourUnregister");
break; break;
case TourBtnState.Started: case TourBtnState.Started:
showInfo("tournament Started");
//socket.emit("tourStart");
break; break;
} }
}); });
@ -264,6 +273,10 @@ function pongClient(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
socket.on("gameUpdate", (state: GameUpdate) => { socket.on("gameUpdate", (state: GameUpdate) => {
render(state); render(state);
}); });
socket.on("tourEnding", (ending) => {
showInfo(ending);
})
// --- // ---
// position logic (client) end // position logic (client) end
// --- // ---
@ -405,19 +418,23 @@ function pongClient(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
if (s === null) { if (s === null) {
tournamentBtn.innerText = TourBtnState.AbleToCreate; tournamentBtn.innerText = TourBtnState.AbleToCreate;
// create tournament // create tournament
tour_infos.innerText = `${TourInfoState.NoTournament} 0👤 0▮•▮`;
return; return;
} }
let weIn = s.players.some((p) => p.id === user.id); let weIn = s.players.some((p) => p.id === user.id);
let imOwner = s.ownerId === user.id; let imOwner = s.ownerId === user.id;
// TODO: fix this so the number of remaining games are correct
switch (s.state) { switch (s.state) {
case "ended": case "ended":
tournamentBtn.innerText = TourBtnState.AbleToCreate; tournamentBtn.innerText = TourBtnState.AbleToCreate;
break; break;
case "playing": case "playing":
tournamentBtn.innerText = TourBtnState.Started; tournamentBtn.innerText = TourBtnState.Started;
tour_infos.innerText = `${TourInfoState.Running} ${s.players.length}👤 ?▮•▮`;
break; break;
case "prestart": case "prestart":
tour_infos.innerText = `${imOwner ? TourInfoState.Owner : (weIn ? TourInfoState.Registered : TourInfoState.NotRegisted)} ${s.players.length}👤 ?▮•▮`;
if (imOwner) { if (imOwner) {
tournamentBtn.innerText = TourBtnState.AbleToStart; tournamentBtn.innerText = TourBtnState.AbleToStart;
} else { } else {
@ -427,8 +444,6 @@ function pongClient(_url: string, _args: RouteHandlerParams): RouteHandlerReturn
} }
break; break;
} }
console.log(s.players);
}); });
socket.on("tournamentRegister", ({ kind, msg }) => { socket.on("tournamentRegister", ({ kind, msg }) => {

View file

@ -32,7 +32,7 @@ export type GameMove = {
export type TourInfo = { export type TourInfo = {
ownerId: string; ownerId: string;
state: 'prestart' | 'playing' | 'ended'; state: 'prestart' | 'playing' | 'ended' | 'canceled';
players: { id: string; name: string; score: number }[]; players: { id: string; name: string; score: number }[];
currentGameInfo: GameUpdate | null; currentGameInfo: GameUpdate | null;
}; };
@ -42,17 +42,19 @@ export interface ClientToServer {
dequeue: () => void; dequeue: () => void;
readyUp: () => void; readyUp: () => void;
readyDown: () => void; readyDown: () => void;
debugInfo: () => void;
gameMove: (up: GameMove) => void; gameMove: (up: GameMove) => void;
connectedToGame: (gameId: string) => void; connectedToGame: (gameId: string) => void;
localGame: () => void; localGame: () => void;
hello: () => void;
// TOURNAMENT // TOURNAMENT
tourRegister: () => void; tourRegister: () => void;
tourUnregister: () => void; tourUnregister: () => void;
tourCreate: () => void; tourCreate: () => void;
tourStart: () => void;
} }
export interface ServerToClient { export interface ServerToClient {
@ -74,6 +76,8 @@ export interface ServerToClient {
msg?: string; msg?: string;
}) => void; }) => void;
tournamentInfo: (info: TourInfo | null) => void; tournamentInfo: (info: TourInfo | null) => void;
tourEnding: (msg: string) => void;
} }
export type SSocket = Socket<ClientToServer, ServerToClient>; export type SSocket = Socket<ClientToServer, ServerToClient>;

View file

@ -32,7 +32,7 @@ export type GameMove = {
export type TourInfo = { export type TourInfo = {
ownerId: string; ownerId: string;
state: 'prestart' | 'playing' | 'ended'; state: 'prestart' | 'playing' | 'ended' | 'canceled';
players: { id: string; name: string; score: number }[]; players: { id: string; name: string; score: number }[];
currentGameInfo: GameUpdate | null; currentGameInfo: GameUpdate | null;
}; };
@ -42,18 +42,19 @@ export interface ClientToServer {
dequeue: () => void; dequeue: () => void;
readyUp: () => void; readyUp: () => void;
readyDown: () => void; readyDown: () => void;
debugInfo: () => void;
gameMove: (up: GameMove) => void; gameMove: (up: GameMove) => void;
connectedToGame: (gameId: string) => void; connectedToGame: (gameId: string) => void;
localGame: () => void; localGame: () => void;
hello: () => void;
// TOURNAMENT // TOURNAMENT
tourRegister: () => void; tourRegister: () => void;
tourUnregister: () => void; tourUnregister: () => void;
tourCreate: () => void; tourCreate: () => void;
// tourStart: () => void; tourStart: () => void;
} }
export interface ServerToClient { export interface ServerToClient {
@ -75,6 +76,8 @@ export interface ServerToClient {
msg?: string; msg?: string;
}) => void; }) => void;
tournamentInfo: (info: TourInfo | null) => void; tournamentInfo: (info: TourInfo | null) => void;
tourEnding: (msg: string) => void;
} }
export type SSocket = Socket<ClientToServer, ServerToClient>; export type SSocket = Socket<ClientToServer, ServerToClient>;

View file

@ -13,22 +13,29 @@ type PUser = {
socket: SSocket, socket: SSocket,
windowId: string, windowId: string,
updateInterval: NodeJS.Timeout, updateInterval: NodeJS.Timeout,
killSelfInterval: NodeJS.Timeout,
lastSeen: number,
}; };
type GameId = PongGameId; type GameId = PongGameId;
class StateI { class StateI {
public static readonly UPDATE_INTERVAL_FRAMES: number = 60; public static readonly UPDATE_INTERVAL_FRAMES: number = 60;
public static readonly KEEP_ALIVE_MS: number = 30 * 1000;
public static readonly START_TIMER_TOURNAMENT: number = 60 * 2 * 1000;
private users: Map<UserId, PUser> = new Map(); private users: Map<UserId, PUser> = new Map();
private queue: Set<UserId> = new Set(); private queue: Set<UserId> = new Set();
private queueInterval: NodeJS.Timeout; private queueInterval: NodeJS.Timeout;
private tournamentInterval: NodeJS.Timeout;
private games: Map<GameId, Pong> = new Map(); private games: Map<GameId, Pong> = new Map();
private tournament: Tournament | null = null; private tournament: Tournament | null = null;
public constructor(private fastify: FastifyInstance) { public constructor(private fastify: FastifyInstance) {
this.queueInterval = setInterval(() => this.queuerFunction()); this.queueInterval = setInterval(() => this.queuerFunction());
this.tournamentInterval = setInterval(() => this.tournamentIntervalFunc());
void this.queueInterval; void this.queueInterval;
void this.tournamentInterval;
} }
private static getGameUpdateData(id: GameId, g: Pong): GameUpdate { private static getGameUpdateData(id: GameId, g: Pong): GameUpdate {
@ -49,7 +56,7 @@ class StateI {
sock.emit('tournamentRegister', { kind: 'failure', msg: 'No tournament exists' }); sock.emit('tournamentRegister', { kind: 'failure', msg: 'No tournament exists' });
return; return;
} }
if (this.tournament.started) { if (this.tournament.state !== 'prestart') {
sock.emit('tournamentRegister', { kind: 'failure', msg: 'No tournament already started' }); sock.emit('tournamentRegister', { kind: 'failure', msg: 'No tournament already started' });
return; return;
} }
@ -72,7 +79,7 @@ class StateI {
sock.emit('tournamentRegister', { kind: 'failure', msg: 'No tournament exists' }); sock.emit('tournamentRegister', { kind: 'failure', msg: 'No tournament exists' });
return; return;
} }
if (this.tournament.started) { if (this.tournament.state !== 'prestart') {
sock.emit('tournamentRegister', { kind: 'failure', msg: 'No tournament already started' }); sock.emit('tournamentRegister', { kind: 'failure', msg: 'No tournament already started' });
return; return;
} }
@ -88,25 +95,36 @@ class StateI {
if (this.tournament !== null) { if (this.tournament !== null) {
sock.emit('tournamentCreateMsg', { kind: 'failure', msg: 'A tournament already exists' }); sock.emit('tournamentCreateMsg', { kind: 'failure', msg: 'A tournament already exists' });
return ; return;
} }
this.tournament = new Tournament(user.id); this.tournament = new Tournament(user.id);
this.registerForTournament(sock, null); this.registerForTournament(sock, null);
this.tournament.startTimeout = setTimeout(() => this.tournament?.start(), StateI.START_TIMER_TOURNAMENT);
} }
private tournamentStart(sock: SSocket) { private cleanupTournament() {
if (this.tournament === null) return;
// we remove all the games we might have done for the tournament, and voila :D
this.tournament.games.keys().forEach((g) => this.games.delete(g));
this.tournament = null;
}
private startTournament(sock: SSocket) {
if (isNullish(this.tournament)) return; if (isNullish(this.tournament)) return;
const user = this.users.get(sock.authUser.id); const user = this.users.get(sock.authUser.id);
if (isNullish(user)) return; if (isNullish(user)) return;
if (user.id !== this.tournament.owner) return;
clearInterval(this.tournament.startTimeout);
this.tournament.start(); this.tournament.start();
} }
public newPausedGame(suid1 : string, suid2 : string) : GameId | undefined { public newPausedGame(suid1: string, suid2: string): GameId | undefined {
if (!this.users.has(suid1 as UserId) || !this.users.has(suid2 as UserId)) { return (undefined); } if (!this.users.has(suid1 as UserId) || !this.users.has(suid2 as UserId)) { return (undefined); }
const uid1 : UserId = suid1 as UserId; const uid1: UserId = suid1 as UserId;
const uid2 : UserId = suid2 as UserId; const uid2: UserId = suid2 as UserId;
const g = new Pong(uid1, uid2); const g = new Pong(uid1, uid2);
g.rdy_timer = -1; g.rdy_timer = -1;
const gameId = newUUID() as unknown as GameId; const gameId = newUUID() as unknown as GameId;
@ -114,8 +132,8 @@ class StateI {
this.games.set(gameId, g); this.games.set(gameId, g);
return (gameId); return (gameId);
} }
public startPausedGame(g_id: PongGameId) : boolean { public startPausedGame(g_id: PongGameId): boolean {
let game : Pong | undefined; let game: Pong | undefined;
if (!this.games.has(g_id) || (game = this.games.get(g_id)) === undefined) { return (false); } if (!this.games.has(g_id) || (game = this.games.get(g_id)) === undefined) { return (false); }
game.rdy_timer = Date.now(); game.rdy_timer = Date.now();
@ -143,11 +161,30 @@ class StateI {
this.gameUpdate(g_id, usr1.socket); this.gameUpdate(g_id, usr1.socket);
this.gameUpdate(g_id, usr2.socket); this.gameUpdate(g_id, usr2.socket);
} }
if (game.checkWinner() !== null) {this.cleanupGame(g_id, game); } if (game.checkWinner() !== null) { this.cleanupGame(g_id, game); }
}, 1000 / StateI.UPDATE_INTERVAL_FRAMES); }, 1000 / StateI.UPDATE_INTERVAL_FRAMES);
return (true); return (true);
} }
private tournamentIntervalFunc() {
const broadcastTourEnding = (msg: string) => {
this.users.forEach((u) => { u.socket.emit('tourEnding', msg); });
};
if (this.tournament) {
if (this.tournament.state === 'canceled') {
broadcastTourEnding('Tournament was canceled');
this.cleanupTournament();
}
else if (this.tournament.state === 'ended') {
broadcastTourEnding('Tournament is finished !');
this.cleanupTournament();
}
else if (this.tournament.state === 'playing') {
this.tournament.checkCurrentGame();
}
}
}
private queuerFunction(): void { private queuerFunction(): void {
const values = Array.from(this.queue.values()); const values = Array.from(this.queue.values());
shuffle(values); shuffle(values);
@ -246,6 +283,15 @@ class StateI {
game.updateLastSeen(user.id); game.updateLastSeen(user.id);
} }
public checkKillSelf(sock: SSocket) {
const user = this.users.get(sock.authUser.id);
if (isNullish(user)) return;
if (Date.now() - user.lastSeen < StateI.KEEP_ALIVE_MS) return;
this.cleanupUser(sock);
}
public registerUser(socket: SSocket): void { public registerUser(socket: SSocket): void {
this.fastify.log.info('Registering new user'); this.fastify.log.info('Registering new user');
@ -259,7 +305,9 @@ class StateI {
id: socket.authUser.id, id: socket.authUser.id,
windowId: socket.id, windowId: socket.id,
updateInterval: setInterval(() => this.updateClient(socket), 100), updateInterval: setInterval(() => this.updateClient(socket), 100),
killSelfInterval: setInterval(() => this.checkKillSelf(socket), 100),
currentGame: null, currentGame: null,
lastSeen: Date.now(),
}); });
this.fastify.log.info('Registered new user'); this.fastify.log.info('Registered new user');
@ -278,6 +326,7 @@ class StateI {
socket.on('tourUnregister', () => this.unregisterForTournament(socket)); socket.on('tourUnregister', () => this.unregisterForTournament(socket));
socket.on('tourCreate', () => this.createTournament(socket)); socket.on('tourCreate', () => this.createTournament(socket));
socket.on('tourStart', () => this.startTournament(socket));
} }
private updateClient(socket: SSocket): void { private updateClient(socket: SSocket): void {
@ -290,7 +339,7 @@ class StateI {
if (this.tournament !== null) { if (this.tournament !== null) {
tourInfo = { tourInfo = {
ownerId: this.tournament.owner, ownerId: this.tournament.owner,
state: this.tournament.started ? 'playing' : 'prestart', state: this.tournament.state,
players: this.tournament.users.values().toArray(), players: this.tournament.users.values().toArray(),
currentGameInfo: (() => { currentGameInfo: (() => {
if (this.tournament.currentGame === null) return null; if (this.tournament.currentGame === null) return null;
@ -307,8 +356,15 @@ class StateI {
if (!this.users.has(socket.authUser.id)) return; if (!this.users.has(socket.authUser.id)) return;
clearInterval(this.users.get(socket.authUser.id)?.updateInterval); clearInterval(this.users.get(socket.authUser.id)?.updateInterval);
clearInterval(this.users.get(socket.authUser.id)?.killSelfInterval);
this.users.delete(socket.authUser.id); this.users.delete(socket.authUser.id);
this.queue.delete(socket.authUser.id); this.queue.delete(socket.authUser.id);
// if the user is in the tournament, and the tournament owner isn't the owner => we remove the user from the tournament !
if (this.tournament?.users.has(socket.authUser.id) && this.tournament?.owner !== socket.authUser.id) {
this.tournament.removeUser(socket.authUser.id);
}
} }
private async cleanupGame(gameId: GameId, game: Pong): Promise<void> { private async cleanupGame(gameId: GameId, game: Pong): Promise<void> {

View file

@ -10,27 +10,33 @@ type TourUser = {
name: string; name: string;
}; };
type TournamentState = 'prestart' | 'playing' | 'ended' | 'canceled';
export class Tournament { export class Tournament {
public users: Map<UserId, TourUser> = new Map(); public users: Map<UserId, TourUser> = new Map();
public currentGame: PongGameId | null = null; public currentGame: PongGameId | null = null;
public games: Map<PongGameId, Pong> = new Map(); public games: Map<PongGameId, Pong> = new Map();
public started: boolean = false; public state: TournamentState = 'prestart';
public gameUpdate: NodeJS.Timeout | undefined; public startTimeout: NodeJS.Timeout | undefined;
constructor(public owner: UserId) { } constructor(public owner: UserId) { }
public addUser(id: UserId, name: string) { public addUser(id: UserId, name: string) {
if (this.started) return; if (this.state !== 'prestart') return;
this.users.set(id, { id, name, score: 0 }); this.users.set(id, { id, name, score: 0 });
} }
public removeUser(id: UserId) { public removeUser(id: UserId) {
if (this.started) return; if (this.state !== 'prestart') return;
this.users.delete(id); this.users.delete(id);
} }
public start() { public start() {
this.started = true; if (this.state !== 'prestart') return;
if (this.users.size < 2) {
this.state = 'canceled';
return;
}
this.state = 'playing';
const users = Array.from(this.users.keys()); const users = Array.from(this.users.keys());
const comb: [UserId, UserId][] = []; const comb: [UserId, UserId][] = [];
@ -48,7 +54,12 @@ export class Tournament {
const g = new Pong(u1, u2); const g = new Pong(u1, u2);
this.games.set(gameId, g); this.games.set(gameId, g);
}); });
this.currentGame = this.games.keys().next().value ?? null; this.currentGame = this.games.keys().next().value ?? null;
} }
public checkCurrentGame() {
void 0;
}
} }