feat: add time controls, correspondence games, and tournament mode
**Zeitmodi (Blitz/Rapid):** - 5, 10, 30 Min Zeitkontrolle bei Spielerstellung - Server-seitige Uhren: Zeit wird bei jedem Zug abgezogen - Timeout-Erkennung via claimTimeout Socket-Event - Schachuhr-Anzeige in GamePage (rot bei < 30s) - Turnierspiele erhalten automatisch Zeitkontrolle **Tagespartien (Correspondence):** - Neue DB-Tabelle correspondence_game - REST API: erstellen, beitreten, Zug machen, aufgeben - Seite /correspondence: Liste aktiver Tagespartien - Seite /correspondence/[code]: Spielen mit interaktivem Brett - Einladungslink teilen, Gegner tritt via Link bei **Turniermodus (Round-Robin):** - Neue DB-Tabellen: tournament, tournament_player, tournament_round - Round-Robin Paarungen mit Circle-Methode - Turnier erstellen: /tournament/create - Turnierliste: /tournament - Turnierseite /tournament/[code]: Standings, Runden, Spiele - Automatische Aktivisierung der nächsten Runde - Turnierspiele werden als normale activeGames erstellt - Ergebnisse aktualisieren Punkte automatisch Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
85
server/src/controllers/correspondence.controller.ts
Normal file
85
server/src/controllers/correspondence.controller.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
import type { Request, Response } from "express";
|
||||
import CorrespondenceModel from "../db/models/correspondence.model.js";
|
||||
import { Chess } from "chess.js";
|
||||
|
||||
export const createCorrespondenceGame = async (req: Request, res: Response) => {
|
||||
if (!req.session.user?.id || typeof req.session.user.id === "string") { res.status(401).end(); return; }
|
||||
try {
|
||||
const game = await CorrespondenceModel.create(req.session.user.id as number, req.session.user.name!, req.body.daysPerMove || 3);
|
||||
res.status(201).json(game);
|
||||
} catch (e) { console.error(e); res.status(500).end(); }
|
||||
};
|
||||
|
||||
export const getMyCorrespondenceGames = async (req: Request, res: Response) => {
|
||||
if (!req.session.user?.id || typeof req.session.user.id === "string") { res.status(401).end(); return; }
|
||||
try {
|
||||
const games = await CorrespondenceModel.findByUserId(req.session.user.id as number);
|
||||
res.status(200).json(games);
|
||||
} catch (e) { res.status(500).end(); }
|
||||
};
|
||||
|
||||
export const getCorrespondenceGame = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const game = await CorrespondenceModel.findByCode(req.params.code);
|
||||
if (!game) { res.status(404).end(); return; }
|
||||
res.status(200).json(game);
|
||||
} catch (e) { res.status(500).end(); }
|
||||
};
|
||||
|
||||
export const joinCorrespondenceGame = async (req: Request, res: Response) => {
|
||||
if (!req.session.user?.id || typeof req.session.user.id === "string") { res.status(401).end(); return; }
|
||||
try {
|
||||
const game = await CorrespondenceModel.join(req.params.code, req.session.user.id as number, req.session.user.name!);
|
||||
if (!game) { res.status(400).json({ message: "Spiel nicht verfügbar." }); return; }
|
||||
res.status(200).json(game);
|
||||
} catch (e) { res.status(500).end(); }
|
||||
};
|
||||
|
||||
export const makeCorrespondenceMove = async (req: Request, res: Response) => {
|
||||
if (!req.session.user?.id || typeof req.session.user.id === "string") { res.status(401).end(); return; }
|
||||
try {
|
||||
const { from, to, promotion } = req.body;
|
||||
const game = await CorrespondenceModel.findByCode(req.params.code);
|
||||
if (!game || game.winner || game.endReason) { res.status(400).json({ message: "Spiel beendet." }); return; }
|
||||
if (!game.black?.id) { res.status(400).json({ message: "Kein Gegner." }); return; }
|
||||
|
||||
const chess = new Chess();
|
||||
if (game.pgn) chess.loadPgn(game.pgn);
|
||||
const turn = chess.turn();
|
||||
const userId = req.session.user.id as number;
|
||||
const isWhite = game.white?.id === userId;
|
||||
const isBlack = game.black?.id === userId;
|
||||
|
||||
if (!isWhite && !isBlack) { res.status(403).end(); return; }
|
||||
if ((turn === "w" && !isWhite) || (turn === "b" && !isBlack)) {
|
||||
res.status(403).json({ message: "Nicht dein Zug." }); return;
|
||||
}
|
||||
|
||||
const move = chess.move({ from, to, promotion: promotion || "q" });
|
||||
if (!move) { res.status(400).json({ message: "Ungültiger Zug." }); return; }
|
||||
|
||||
let winner: string | undefined, endReason: string | undefined;
|
||||
if (chess.isGameOver()) {
|
||||
if (chess.isCheckmate()) { endReason = "checkmate"; winner = turn === "w" ? "white" : "black"; }
|
||||
else if (chess.isStalemate()) { endReason = "stalemate"; winner = "draw"; }
|
||||
else if (chess.isThreefoldRepetition()) { endReason = "repetition"; winner = "draw"; }
|
||||
else if (chess.isInsufficientMaterial()) { endReason = "insufficient"; winner = "draw"; }
|
||||
else { endReason = "draw"; winner = "draw"; }
|
||||
}
|
||||
|
||||
const updated = await CorrespondenceModel.applyMove(req.params.code, chess.pgn(), winner, endReason);
|
||||
res.status(200).json(updated);
|
||||
} catch (e) { console.error(e); res.status(500).end(); }
|
||||
};
|
||||
|
||||
export const resignCorrespondenceGame = async (req: Request, res: Response) => {
|
||||
if (!req.session.user?.id || typeof req.session.user.id === "string") { res.status(401).end(); return; }
|
||||
try {
|
||||
const game = await CorrespondenceModel.findByCode(req.params.code);
|
||||
if (!game || game.endReason) { res.status(400).end(); return; }
|
||||
const userId = req.session.user.id as number;
|
||||
if (game.white?.id !== userId && game.black?.id !== userId) { res.status(403).end(); return; }
|
||||
const updated = await CorrespondenceModel.resign(req.params.code, userId);
|
||||
res.status(200).json(updated);
|
||||
} catch (e) { res.status(500).end(); }
|
||||
};
|
||||
@@ -78,11 +78,15 @@ export const createGame = async (req: Request, res: Response) => {
|
||||
connected: false
|
||||
};
|
||||
const unlisted: boolean = req.body.unlisted ?? false;
|
||||
const timeControl: number | undefined = req.body.timeControl ? parseInt(req.body.timeControl) : undefined;
|
||||
const game: Game = {
|
||||
code: nanoid(6),
|
||||
unlisted,
|
||||
host: user,
|
||||
pgn: ""
|
||||
pgn: "",
|
||||
timeControl: timeControl || undefined,
|
||||
whiteTimeMs: timeControl ? timeControl * 60 * 1000 : undefined,
|
||||
blackTimeMs: timeControl ? timeControl * 60 * 1000 : undefined
|
||||
};
|
||||
if (req.body.side === "white") {
|
||||
game.white = user;
|
||||
|
||||
82
server/src/controllers/tournament.controller.ts
Normal file
82
server/src/controllers/tournament.controller.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import type { Request, Response } from "express";
|
||||
import TournamentModel from "../db/models/tournament.model.js";
|
||||
import { activeGames } from "../db/models/game.model.js";
|
||||
import { nanoid } from "nanoid";
|
||||
import type { Game } from "@michess/types";
|
||||
|
||||
export const createTournament = async (req: Request, res: Response) => {
|
||||
if (!req.session.user?.id || typeof req.session.user.id === "string") { res.status(401).end(); return; }
|
||||
const { name, timeControl, maxPlayers } = req.body;
|
||||
if (!name) { res.status(400).json({ message: "Name erforderlich." }); return; }
|
||||
try {
|
||||
const tournament = await TournamentModel.createTournament(
|
||||
req.session.user.id as number, req.session.user.name!, name,
|
||||
timeControl ? parseInt(timeControl) : undefined, maxPlayers ? parseInt(maxPlayers) : 8
|
||||
);
|
||||
await TournamentModel.joinTournament(tournament.code!, req.session.user.id as number, req.session.user.name!);
|
||||
const updated = await TournamentModel.findByCode(tournament.code!);
|
||||
res.status(201).json(updated);
|
||||
} catch (e) { console.error(e); res.status(500).end(); }
|
||||
};
|
||||
|
||||
export const getTournaments = async (_req: Request, res: Response) => {
|
||||
try {
|
||||
const tournaments = await TournamentModel.findAll();
|
||||
res.status(200).json(tournaments);
|
||||
} catch (e) { res.status(500).end(); }
|
||||
};
|
||||
|
||||
export const getTournament = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const tournament = await TournamentModel.findByCode(req.params.code);
|
||||
if (!tournament) { res.status(404).end(); return; }
|
||||
res.status(200).json(tournament);
|
||||
} catch (e) { res.status(500).end(); }
|
||||
};
|
||||
|
||||
export const joinTournament = async (req: Request, res: Response) => {
|
||||
if (!req.session.user?.id || typeof req.session.user.id === "string") { res.status(401).end(); return; }
|
||||
try {
|
||||
const result = await TournamentModel.joinTournament(req.params.code, req.session.user.id as number, req.session.user.name!);
|
||||
if (!result) { res.status(400).json({ message: "Turnier nicht verfügbar." }); return; }
|
||||
const updated = await TournamentModel.findByCode(req.params.code);
|
||||
res.status(200).json(updated);
|
||||
} catch (e) { res.status(500).end(); }
|
||||
};
|
||||
|
||||
export const startTournament = async (req: Request, res: Response) => {
|
||||
if (!req.session.user?.id || typeof req.session.user.id === "string") { res.status(401).end(); return; }
|
||||
try {
|
||||
const tournament = await TournamentModel.findByCode(req.params.code);
|
||||
if (!tournament) { res.status(404).end(); return; }
|
||||
if (tournament.hostId !== req.session.user.id) { res.status(403).end(); return; }
|
||||
if (tournament.status !== "waiting") { res.status(400).json({ message: "Turnier bereits gestartet." }); return; }
|
||||
if (!tournament.players || tournament.players.length < 2) { res.status(400).json({ message: "Mindestens 2 Spieler erforderlich." }); return; }
|
||||
|
||||
const allRounds = await TournamentModel.startTournament(tournament.id!);
|
||||
if (!allRounds) { res.status(500).end(); return; }
|
||||
|
||||
// Create active games for round 1
|
||||
const round1 = allRounds[0];
|
||||
for (const roundRow of round1) {
|
||||
const code = nanoid(6);
|
||||
const tc = tournament.timeControl;
|
||||
const row = roundRow as any;
|
||||
const whiteUser = { id: row.white_id, name: row.white_name, connected: false };
|
||||
const blackUser = { id: row.black_id, name: row.black_name, connected: false };
|
||||
const game: Game = {
|
||||
code, unlisted: true, host: whiteUser,
|
||||
white: whiteUser, black: blackUser, pgn: "",
|
||||
startedAt: Date.now(),
|
||||
timeControl: tc || undefined,
|
||||
whiteTimeMs: tc ? tc * 60 * 1000 : undefined,
|
||||
blackTimeMs: tc ? tc * 60 * 1000 : undefined
|
||||
};
|
||||
activeGames.push(game);
|
||||
await TournamentModel.setRoundGameCode(row.id, code);
|
||||
}
|
||||
|
||||
const updated = await TournamentModel.findByCode(req.params.code);
|
||||
res.status(200).json(updated);
|
||||
} catch (e) { console.error(e); res.status(500).end(); }
|
||||
};
|
||||
@@ -48,4 +48,57 @@ export const INIT_TABLES = /* sql */ `
|
||||
ALTER TABLE "user" ADD COLUMN IF NOT EXISTS banned BOOLEAN DEFAULT FALSE;
|
||||
ALTER TABLE "game" ADD COLUMN IF NOT EXISTS vs_ai BOOLEAN DEFAULT FALSE;
|
||||
ALTER TABLE "game" ADD COLUMN IF NOT EXISTS ai_level INTEGER;
|
||||
ALTER TABLE "game" ADD COLUMN IF NOT EXISTS time_control INTEGER;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "correspondence_game" (
|
||||
id SERIAL PRIMARY KEY,
|
||||
code VARCHAR(8) UNIQUE NOT NULL,
|
||||
white_id INT REFERENCES "user"(id),
|
||||
black_id INT REFERENCES "user"(id),
|
||||
white_name VARCHAR(128),
|
||||
black_name VARCHAR(128),
|
||||
pgn TEXT DEFAULT '',
|
||||
winner VARCHAR(5),
|
||||
end_reason VARCHAR(16),
|
||||
days_per_move INTEGER DEFAULT 3,
|
||||
last_move_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
ended_at TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "tournament" (
|
||||
id SERIAL PRIMARY KEY,
|
||||
code VARCHAR(8) UNIQUE NOT NULL,
|
||||
name VARCHAR(128) NOT NULL,
|
||||
host_id INT REFERENCES "user"(id),
|
||||
host_name VARCHAR(128),
|
||||
status VARCHAR(16) DEFAULT 'waiting',
|
||||
time_control INTEGER,
|
||||
max_players INTEGER DEFAULT 8,
|
||||
current_round INTEGER DEFAULT 0,
|
||||
total_rounds INTEGER DEFAULT 0,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "tournament_player" (
|
||||
tournament_id INT REFERENCES "tournament"(id) ON DELETE CASCADE,
|
||||
user_id INT REFERENCES "user"(id) ON DELETE CASCADE,
|
||||
user_name VARCHAR(128),
|
||||
score DECIMAL(4,1) DEFAULT 0,
|
||||
games_played INTEGER DEFAULT 0,
|
||||
PRIMARY KEY (tournament_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "tournament_round" (
|
||||
id SERIAL PRIMARY KEY,
|
||||
tournament_id INT REFERENCES "tournament"(id) ON DELETE CASCADE,
|
||||
round INTEGER NOT NULL,
|
||||
game_code VARCHAR(8),
|
||||
game_id INT,
|
||||
white_id INT REFERENCES "user"(id),
|
||||
white_name VARCHAR(128),
|
||||
black_id INT REFERENCES "user"(id),
|
||||
black_name VARCHAR(128),
|
||||
result VARCHAR(5)
|
||||
);
|
||||
`;
|
||||
|
||||
79
server/src/db/models/correspondence.model.ts
Normal file
79
server/src/db/models/correspondence.model.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { db } from "../index.js";
|
||||
import type { CorrespondenceGame } from "@michess/types";
|
||||
import { nanoid } from "nanoid";
|
||||
|
||||
function mapRow(r: any): CorrespondenceGame {
|
||||
return {
|
||||
id: r.id,
|
||||
code: r.code,
|
||||
white: { id: r.white_id, name: r.white_name },
|
||||
black: r.black_id ? { id: r.black_id, name: r.black_name } : undefined,
|
||||
pgn: r.pgn || "",
|
||||
winner: r.winner,
|
||||
endReason: r.end_reason,
|
||||
daysPerMove: r.days_per_move,
|
||||
lastMoveAt: r.last_move_at?.getTime(),
|
||||
startedAt: r.started_at?.getTime(),
|
||||
endedAt: r.ended_at?.getTime()
|
||||
};
|
||||
}
|
||||
|
||||
export const create = async (userId: number, userName: string, daysPerMove = 3): Promise<CorrespondenceGame> => {
|
||||
const code = nanoid(8);
|
||||
const res = await db.query(
|
||||
`INSERT INTO "correspondence_game"(code, white_id, white_name, days_per_move) VALUES($1, $2, $3, $4) RETURNING *`,
|
||||
[code, userId, userName, daysPerMove]
|
||||
);
|
||||
return mapRow(res.rows[0]);
|
||||
};
|
||||
|
||||
export const join = async (code: string, userId: number, userName: string): Promise<CorrespondenceGame | null> => {
|
||||
const res = await db.query(
|
||||
`UPDATE "correspondence_game" SET black_id=$1, black_name=$2 WHERE code=$3 AND black_id IS NULL AND white_id != $1 RETURNING *`,
|
||||
[userId, userName, code]
|
||||
);
|
||||
return res.rows[0] ? mapRow(res.rows[0]) : null;
|
||||
};
|
||||
|
||||
export const findByCode = async (code: string): Promise<CorrespondenceGame | null> => {
|
||||
const res = await db.query(`SELECT * FROM "correspondence_game" WHERE code=$1`, [code]);
|
||||
return res.rows[0] ? mapRow(res.rows[0]) : null;
|
||||
};
|
||||
|
||||
export const findByUserId = async (userId: number): Promise<CorrespondenceGame[]> => {
|
||||
const res = await db.query(
|
||||
`SELECT * FROM "correspondence_game" WHERE (white_id=$1 OR black_id=$1) AND ended_at IS NULL ORDER BY last_move_at DESC`,
|
||||
[userId]
|
||||
);
|
||||
return res.rows.map(mapRow);
|
||||
};
|
||||
|
||||
export const applyMove = async (code: string, pgn: string, winner?: string, endReason?: string): Promise<CorrespondenceGame | null> => {
|
||||
let res;
|
||||
if (winner) {
|
||||
res = await db.query(
|
||||
`UPDATE "correspondence_game" SET pgn=$1, winner=$2, end_reason=$3, last_move_at=NOW(), ended_at=NOW() WHERE code=$4 RETURNING *`,
|
||||
[pgn, winner, endReason, code]
|
||||
);
|
||||
} else {
|
||||
res = await db.query(
|
||||
`UPDATE "correspondence_game" SET pgn=$1, last_move_at=NOW() WHERE code=$2 RETURNING *`,
|
||||
[pgn, code]
|
||||
);
|
||||
}
|
||||
return res.rows[0] ? mapRow(res.rows[0]) : null;
|
||||
};
|
||||
|
||||
export const resign = async (code: string, resigningUserId: number): Promise<CorrespondenceGame | null> => {
|
||||
const game = await findByCode(code);
|
||||
if (!game) return null;
|
||||
const winner = game.white?.id === resigningUserId ? "black" : "white";
|
||||
const res = await db.query(
|
||||
`UPDATE "correspondence_game" SET winner=$1, end_reason='resign', ended_at=NOW() WHERE code=$2 RETURNING *`,
|
||||
[winner, code]
|
||||
);
|
||||
return res.rows[0] ? mapRow(res.rows[0]) : null;
|
||||
};
|
||||
|
||||
const CorrespondenceModel = { create, join, findByCode, findByUserId, applyMove, resign };
|
||||
export default CorrespondenceModel;
|
||||
@@ -14,7 +14,7 @@ export const save = async (game: Game) => {
|
||||
black.id = game.black?.id;
|
||||
}
|
||||
const res = await db.query(
|
||||
`INSERT INTO "game"(winner, end_reason, pgn, white_id, white_name, black_id, black_name, started_at, vs_ai, ai_level) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING *`,
|
||||
`INSERT INTO "game"(winner, end_reason, pgn, white_id, white_name, black_id, black_name, started_at, vs_ai, ai_level, time_control) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING *`,
|
||||
[
|
||||
game.winner || null,
|
||||
game.endReason || null,
|
||||
@@ -25,7 +25,8 @@ export const save = async (game: Game) => {
|
||||
black.name || null,
|
||||
new Date(game.startedAt as number),
|
||||
game.vsAi || false,
|
||||
game.aiLevel || null
|
||||
game.aiLevel || null,
|
||||
game.timeControl || null
|
||||
]
|
||||
);
|
||||
if (black.id || white.id) {
|
||||
@@ -66,7 +67,8 @@ export const save = async (game: Game) => {
|
||||
startedAt: res.rows[0].started_at.getTime(),
|
||||
endedAt: res.rows[0].ended_at?.getTime() || undefined,
|
||||
vsAi: res.rows[0].vs_ai || undefined,
|
||||
aiLevel: res.rows[0].ai_level || undefined
|
||||
aiLevel: res.rows[0].ai_level || undefined,
|
||||
timeControl: res.rows[0].time_control || undefined
|
||||
} as Game;
|
||||
} catch (err: unknown) {
|
||||
console.log(err);
|
||||
|
||||
179
server/src/db/models/tournament.model.ts
Normal file
179
server/src/db/models/tournament.model.ts
Normal file
@@ -0,0 +1,179 @@
|
||||
import { db } from "../index.js";
|
||||
import { nanoid } from "nanoid";
|
||||
import type { Tournament, TournamentPlayer, TournamentRound } from "@michess/types";
|
||||
|
||||
// Circle method for round-robin tournament scheduling
|
||||
function generateRoundRobinPairings(players: TournamentPlayer[]): { white: TournamentPlayer; black: TournamentPlayer }[][] {
|
||||
let ps: (TournamentPlayer | null)[] = [...players];
|
||||
if (ps.length % 2 !== 0) ps.push(null); // BYE slot for odd number
|
||||
const n = ps.length;
|
||||
const rounds: { white: TournamentPlayer; black: TournamentPlayer }[][] = [];
|
||||
|
||||
for (let r = 0; r < n - 1; r++) {
|
||||
const games: { white: TournamentPlayer; black: TournamentPlayer }[] = [];
|
||||
for (let k = 0; k < n / 2; k++) {
|
||||
const home = ps[k];
|
||||
const away = ps[n - 1 - k];
|
||||
if (home && away) {
|
||||
// Alternate colors each round for fairness
|
||||
games.push(r % 2 === 0 ? { white: home, black: away } : { white: away, black: home });
|
||||
}
|
||||
}
|
||||
rounds.push(games);
|
||||
// Rotate: keep index 0 fixed, rotate the rest clockwise
|
||||
const last = ps[n - 1];
|
||||
for (let i = n - 1; i > 1; i--) ps[i] = ps[i - 1];
|
||||
ps[1] = last;
|
||||
}
|
||||
return rounds;
|
||||
}
|
||||
|
||||
function mapTournament(t: any, players: any[], rounds: any[]): Tournament {
|
||||
return {
|
||||
id: t.id,
|
||||
code: t.code,
|
||||
name: t.name,
|
||||
hostId: t.host_id,
|
||||
hostName: t.host_name,
|
||||
status: t.status,
|
||||
timeControl: t.time_control,
|
||||
maxPlayers: t.max_players,
|
||||
currentRound: t.current_round,
|
||||
totalRounds: t.total_rounds,
|
||||
players: players.map(p => ({
|
||||
tournamentId: p.tournament_id,
|
||||
userId: p.user_id,
|
||||
userName: p.user_name,
|
||||
score: parseFloat(p.score),
|
||||
gamesPlayed: p.games_played
|
||||
})),
|
||||
rounds: rounds.map(r => ({
|
||||
id: r.id,
|
||||
tournamentId: r.tournament_id,
|
||||
round: r.round,
|
||||
gameCode: r.game_code,
|
||||
gameId: r.game_id,
|
||||
whiteId: r.white_id,
|
||||
whiteName: r.white_name,
|
||||
blackId: r.black_id,
|
||||
blackName: r.black_name,
|
||||
result: r.result
|
||||
})),
|
||||
createdAt: t.created_at?.getTime()
|
||||
};
|
||||
}
|
||||
|
||||
export const createTournament = async (hostId: number, hostName: string, name: string, timeControl?: number, maxPlayers = 8): Promise<Tournament> => {
|
||||
const code = nanoid(6);
|
||||
const res = await db.query(
|
||||
`INSERT INTO "tournament"(code, name, host_id, host_name, time_control, max_players) VALUES($1,$2,$3,$4,$5,$6) RETURNING *`,
|
||||
[code, name, hostId, hostName, timeControl || null, maxPlayers]
|
||||
);
|
||||
return mapTournament(res.rows[0], [], []);
|
||||
};
|
||||
|
||||
export const joinTournament = async (code: string, userId: number, userName: string): Promise<boolean | null> => {
|
||||
const t = await findByCode(code);
|
||||
if (!t || t.status !== "waiting") return null;
|
||||
if ((t.players?.length ?? 0) >= (t.maxPlayers ?? 8)) return null;
|
||||
const existing = t.players?.find(p => p.userId === userId);
|
||||
if (existing) return true; // already joined
|
||||
try {
|
||||
await db.query(
|
||||
`INSERT INTO "tournament_player"(tournament_id, user_id, user_name) VALUES($1,$2,$3)`,
|
||||
[t.id, userId, userName]
|
||||
);
|
||||
return true;
|
||||
} catch { return null; }
|
||||
};
|
||||
|
||||
export const startTournament = async (tournamentId: number): Promise<TournamentRound[][] | null> => {
|
||||
const playersRes = await db.query(
|
||||
`SELECT * FROM "tournament_player" WHERE tournament_id=$1`,
|
||||
[tournamentId]
|
||||
);
|
||||
const players: TournamentPlayer[] = playersRes.rows.map(r => ({
|
||||
tournamentId: r.tournament_id, userId: r.user_id, userName: r.user_name, score: 0, gamesPlayed: 0
|
||||
}));
|
||||
if (players.length < 2) return null;
|
||||
|
||||
const pairings = generateRoundRobinPairings(players);
|
||||
const totalRounds = pairings.length;
|
||||
|
||||
const allRounds: TournamentRound[][] = [];
|
||||
for (let r = 0; r < pairings.length; r++) {
|
||||
const roundRows: TournamentRound[] = [];
|
||||
for (const game of pairings[r]) {
|
||||
const res = await db.query(
|
||||
`INSERT INTO "tournament_round"(tournament_id, round, white_id, white_name, black_id, black_name) VALUES($1,$2,$3,$4,$5,$6) RETURNING *`,
|
||||
[tournamentId, r + 1, game.white.userId, game.white.userName, game.black.userId, game.black.userName]
|
||||
);
|
||||
roundRows.push(res.rows[0]);
|
||||
}
|
||||
allRounds.push(roundRows);
|
||||
}
|
||||
|
||||
await db.query(
|
||||
`UPDATE "tournament" SET status='active', current_round=1, total_rounds=$1 WHERE id=$2`,
|
||||
[totalRounds, tournamentId]
|
||||
);
|
||||
return allRounds;
|
||||
};
|
||||
|
||||
export const findByCode = async (code: string): Promise<Tournament | null> => {
|
||||
const res = await db.query(`SELECT * FROM "tournament" WHERE code=$1`, [code]);
|
||||
if (!res.rows[0]) return null;
|
||||
const t = res.rows[0];
|
||||
const playersRes = await db.query(`SELECT * FROM "tournament_player" WHERE tournament_id=$1 ORDER BY score DESC, games_played`, [t.id]);
|
||||
const roundsRes = await db.query(`SELECT * FROM "tournament_round" WHERE tournament_id=$1 ORDER BY round, id`, [t.id]);
|
||||
return mapTournament(t, playersRes.rows, roundsRes.rows);
|
||||
};
|
||||
|
||||
export const findAll = async (): Promise<Tournament[]> => {
|
||||
const res = await db.query(`SELECT * FROM "tournament" WHERE status != 'finished' ORDER BY created_at DESC`);
|
||||
return res.rows.map(r => mapTournament(r, [], []));
|
||||
};
|
||||
|
||||
export const setRoundGameCode = async (roundId: number, gameCode: string): Promise<void> => {
|
||||
await db.query(`UPDATE "tournament_round" SET game_code=$1 WHERE id=$2`, [gameCode, roundId]);
|
||||
};
|
||||
|
||||
export const updateRoundResult = async (gameCode: string, result: "white" | "black" | "draw"): Promise<void> => {
|
||||
const roundRes = await db.query(
|
||||
`UPDATE "tournament_round" SET result=$1 WHERE game_code=$2 RETURNING *`,
|
||||
[result, gameCode]
|
||||
);
|
||||
if (!roundRes.rows[0]) return;
|
||||
const round = roundRes.rows[0];
|
||||
|
||||
// Update scores
|
||||
if (result === "white") {
|
||||
await db.query(`UPDATE "tournament_player" SET score=score+1, games_played=games_played+1 WHERE tournament_id=$1 AND user_id=$2`, [round.tournament_id, round.white_id]);
|
||||
await db.query(`UPDATE "tournament_player" SET games_played=games_played+1 WHERE tournament_id=$1 AND user_id=$2`, [round.tournament_id, round.black_id]);
|
||||
} else if (result === "black") {
|
||||
await db.query(`UPDATE "tournament_player" SET score=score+1, games_played=games_played+1 WHERE tournament_id=$1 AND user_id=$2`, [round.tournament_id, round.black_id]);
|
||||
await db.query(`UPDATE "tournament_player" SET games_played=games_played+1 WHERE tournament_id=$1 AND user_id=$2`, [round.tournament_id, round.white_id]);
|
||||
} else {
|
||||
await db.query(`UPDATE "tournament_player" SET score=score+0.5, games_played=games_played+1 WHERE tournament_id=$1 AND (user_id=$2 OR user_id=$3)`, [round.tournament_id, round.white_id, round.black_id]);
|
||||
}
|
||||
|
||||
// Check if all games in this round are done -> advance round or finish tournament
|
||||
const pendingRes = await db.query(
|
||||
`SELECT COUNT(*) FROM "tournament_round" WHERE tournament_id=$1 AND round=$2 AND result IS NULL`,
|
||||
[round.tournament_id, round.round]
|
||||
);
|
||||
if (parseInt(pendingRes.rows[0].count) === 0) {
|
||||
const nextRes = await db.query(
|
||||
`SELECT COUNT(*) FROM "tournament_round" WHERE tournament_id=$1 AND round=$2`,
|
||||
[round.tournament_id, round.round + 1]
|
||||
);
|
||||
if (parseInt(nextRes.rows[0].count) > 0) {
|
||||
await db.query(`UPDATE "tournament" SET current_round=current_round+1 WHERE id=$1`, [round.tournament_id]);
|
||||
} else {
|
||||
await db.query(`UPDATE "tournament" SET status='finished' WHERE id=$1`, [round.tournament_id]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const TournamentModel = { createTournament, joinTournament, startTournament, findByCode, findAll, setRoundGameCode, updateRoundResult };
|
||||
export default TournamentModel;
|
||||
14
server/src/routes/correspondence.route.ts
Normal file
14
server/src/routes/correspondence.route.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import express from "express";
|
||||
import {
|
||||
createCorrespondenceGame, getMyCorrespondenceGames, getCorrespondenceGame,
|
||||
joinCorrespondenceGame, makeCorrespondenceMove, resignCorrespondenceGame
|
||||
} from "../controllers/correspondence.controller.js";
|
||||
|
||||
const router = express.Router();
|
||||
router.post("/", createCorrespondenceGame);
|
||||
router.get("/", getMyCorrespondenceGames);
|
||||
router.get("/:code", getCorrespondenceGame);
|
||||
router.post("/:code/join", joinCorrespondenceGame);
|
||||
router.post("/:code/move", makeCorrespondenceMove);
|
||||
router.post("/:code/resign", resignCorrespondenceGame);
|
||||
export default router;
|
||||
@@ -3,8 +3,10 @@ import { Router } from "express";
|
||||
import admin from "./admin.route.js";
|
||||
import ai from "./ai.route.js";
|
||||
import auth from "./auth.route.js";
|
||||
import correspondence from "./correspondence.route.js";
|
||||
import friends from "./friends.route.js";
|
||||
import games from "./games.route.js";
|
||||
import tournaments from "./tournament.route.js";
|
||||
import users from "./users.route.js";
|
||||
|
||||
const router = Router();
|
||||
@@ -15,5 +17,7 @@ router.use("/users", users);
|
||||
router.use("/admin", admin);
|
||||
router.use("/friends", friends);
|
||||
router.use("/ai", ai);
|
||||
router.use("/correspondence", correspondence);
|
||||
router.use("/tournaments", tournaments);
|
||||
|
||||
export default router;
|
||||
|
||||
10
server/src/routes/tournament.route.ts
Normal file
10
server/src/routes/tournament.route.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import express from "express";
|
||||
import { createTournament, getTournaments, getTournament, joinTournament, startTournament } from "../controllers/tournament.controller.js";
|
||||
|
||||
const router = express.Router();
|
||||
router.post("/", createTournament);
|
||||
router.get("/", getTournaments);
|
||||
router.get("/:code", getTournament);
|
||||
router.post("/:code/join", joinTournament);
|
||||
router.post("/:code/start", startTournament);
|
||||
export default router;
|
||||
@@ -3,6 +3,7 @@ import { Chess } from "chess.js";
|
||||
import type { DisconnectReason, Socket } from "socket.io";
|
||||
|
||||
import GameModel, { activeGames } from "../db/models/game.model.js";
|
||||
import TournamentModel from "../db/models/tournament.model.js";
|
||||
import { io } from "../server.js";
|
||||
|
||||
// TODO: clean up
|
||||
@@ -49,6 +50,16 @@ export async function joinLobby(this: Socket, gameCode: string) {
|
||||
|
||||
await this.join(gameCode);
|
||||
io.to(game.code as string).emit("receivedLatestGame", game);
|
||||
|
||||
// Start clock if both players are connected and game has timeControl but hasn't started timing yet
|
||||
if (game.timeControl && game.white?.connected && game.black?.connected && !game.lastMoveAt && !game.pgn) {
|
||||
game.lastMoveAt = Date.now();
|
||||
io.to(game.code as string).emit("clockUpdate", {
|
||||
whiteTimeMs: game.whiteTimeMs,
|
||||
blackTimeMs: game.blackTimeMs,
|
||||
lastMoveAt: game.lastMoveAt
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function leaveLobby(this: Socket, reason?: DisconnectReason, code?: string) {
|
||||
@@ -141,6 +152,8 @@ export async function claimAbandoned(this: Socket, type: "win" | "draw") {
|
||||
const { id } = (await GameModel.save(game)) as Game;
|
||||
game.id = id;
|
||||
|
||||
await TournamentModel.updateRoundResult(game.code!, game.winner as "white" | "black" | "draw");
|
||||
|
||||
const gameOver = {
|
||||
reason: game.endReason,
|
||||
winnerName: this.request.session.user.name,
|
||||
@@ -178,11 +191,48 @@ export async function sendMove(this: Socket, m: { from: string; to: string; prom
|
||||
throw new Error("not turn to move");
|
||||
}
|
||||
|
||||
// Time tracking
|
||||
let timeExpired = false;
|
||||
if (game.timeControl && game.lastMoveAt && game.whiteTimeMs !== undefined && game.blackTimeMs !== undefined) {
|
||||
const elapsed = Date.now() - game.lastMoveAt;
|
||||
if (prevTurn === "w") {
|
||||
game.whiteTimeMs = Math.max(0, game.whiteTimeMs - elapsed);
|
||||
if (game.whiteTimeMs <= 0) timeExpired = true;
|
||||
} else {
|
||||
game.blackTimeMs = Math.max(0, game.blackTimeMs - elapsed);
|
||||
if (game.blackTimeMs <= 0) timeExpired = true;
|
||||
}
|
||||
game.lastMoveAt = Date.now();
|
||||
}
|
||||
|
||||
if (timeExpired) {
|
||||
game.winner = prevTurn === "w" ? "black" : "white";
|
||||
game.endReason = "timeout";
|
||||
const saved = (await GameModel.save(game)) as Game;
|
||||
const id = saved?.id;
|
||||
game.id = id;
|
||||
await TournamentModel.updateRoundResult(game.code!, game.winner as "white" | "black" | "draw");
|
||||
io.to(game.code as string).emit("gameOver", { reason: "timeout", winnerSide: game.winner, id });
|
||||
if (game.timeout) clearTimeout(game.timeout);
|
||||
activeGames.splice(activeGames.indexOf(game), 1);
|
||||
return;
|
||||
}
|
||||
|
||||
const newMove = chess.move(m);
|
||||
|
||||
if (newMove) {
|
||||
game.pgn = chess.pgn();
|
||||
this.to(game.code as string).emit("receivedMove", m);
|
||||
|
||||
// Emit clock update after move
|
||||
if (game.timeControl) {
|
||||
io.to(game.code as string).emit("clockUpdate", {
|
||||
whiteTimeMs: game.whiteTimeMs,
|
||||
blackTimeMs: game.blackTimeMs,
|
||||
lastMoveAt: game.lastMoveAt
|
||||
});
|
||||
}
|
||||
|
||||
if (chess.isGameOver()) {
|
||||
let reason: Game["endReason"];
|
||||
if (chess.isCheckmate()) reason = "checkmate";
|
||||
@@ -208,6 +258,7 @@ export async function sendMove(this: Socket, m: { from: string; to: string; prom
|
||||
|
||||
const { id } = (await GameModel.save(game)) as Game; // save game to db
|
||||
game.id = id;
|
||||
await TournamentModel.updateRoundResult(game.code!, game.winner as "white" | "black" | "draw");
|
||||
io.to(game.code as string).emit("gameOver", { reason, winnerName, winnerSide, id });
|
||||
|
||||
if (game.timeout) clearTimeout(game.timeout);
|
||||
@@ -240,6 +291,14 @@ export async function joinAsPlayer(this: Socket) {
|
||||
side: "white"
|
||||
});
|
||||
game.startedAt = Date.now();
|
||||
if (game.timeControl) {
|
||||
game.lastMoveAt = Date.now();
|
||||
io.to(game.code as string).emit("clockUpdate", {
|
||||
whiteTimeMs: game.whiteTimeMs,
|
||||
blackTimeMs: game.blackTimeMs,
|
||||
lastMoveAt: game.lastMoveAt
|
||||
});
|
||||
}
|
||||
} else if (!game.black) {
|
||||
const sessionUser = {
|
||||
id: this.request.session.user.id,
|
||||
@@ -253,6 +312,14 @@ export async function joinAsPlayer(this: Socket) {
|
||||
side: "black"
|
||||
});
|
||||
game.startedAt = Date.now();
|
||||
if (game.timeControl) {
|
||||
game.lastMoveAt = Date.now();
|
||||
io.to(game.code as string).emit("clockUpdate", {
|
||||
whiteTimeMs: game.whiteTimeMs,
|
||||
blackTimeMs: game.blackTimeMs,
|
||||
lastMoveAt: game.lastMoveAt
|
||||
});
|
||||
}
|
||||
} else {
|
||||
console.log("joinAsPlayer: attempted to join a game with already 2 players");
|
||||
}
|
||||
@@ -265,3 +332,29 @@ export async function chat(this: Socket, message: string) {
|
||||
message
|
||||
});
|
||||
}
|
||||
|
||||
export async function claimTimeout(this: Socket) {
|
||||
const game = activeGames.find(g => g.code === Array.from(this.rooms)[1]);
|
||||
if (!game || !game.timeControl || !game.lastMoveAt || game.endReason || game.winner) return;
|
||||
if (!game.white || !game.black) return;
|
||||
|
||||
const chess = new Chess();
|
||||
if (game.pgn) chess.loadPgn(game.pgn);
|
||||
|
||||
const elapsed = Date.now() - game.lastMoveAt;
|
||||
const turn = chess.turn(); // 'w' or 'b'
|
||||
const currentTimeMs = turn === "w" ? (game.whiteTimeMs ?? 0) : (game.blackTimeMs ?? 0);
|
||||
|
||||
if (currentTimeMs - elapsed > 1000) return; // 1s tolerance
|
||||
|
||||
game.winner = turn === "w" ? "black" : "white";
|
||||
game.endReason = "timeout";
|
||||
|
||||
const saved = (await GameModel.save(game)) as Game;
|
||||
const id = saved?.id;
|
||||
game.id = id;
|
||||
await TournamentModel.updateRoundResult(game.code!, game.winner as "white" | "black" | "draw");
|
||||
io.to(game.code as string).emit("gameOver", { reason: "timeout", winnerSide: game.winner, id });
|
||||
if (game.timeout) clearTimeout(game.timeout);
|
||||
activeGames.splice(activeGames.indexOf(game), 1);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { io } from "../server.js";
|
||||
import {
|
||||
chat,
|
||||
claimAbandoned,
|
||||
claimTimeout,
|
||||
getLatestGame,
|
||||
joinAsPlayer,
|
||||
joinLobby,
|
||||
@@ -34,6 +35,7 @@ const socketConnect = (socket: Socket) => {
|
||||
socket.on("joinAsPlayer", joinAsPlayer);
|
||||
socket.on("chat", chat);
|
||||
socket.on("claimAbandoned", claimAbandoned);
|
||||
socket.on("claimTimeout", claimTimeout);
|
||||
};
|
||||
|
||||
export const init = () => {
|
||||
|
||||
Reference in New Issue
Block a user