- A player opens a group with one card and a chosen role; others join from the board with a free role, and the creator launches it once enough players are in. - At departure the Veilleur de la Guilde holds empty places without a role, each member rolls their own loot multiplied by the number of players, and distinct collections add a cohesion bonus. - An unlaunched group departs on its own at the end of recruitment with enough players, or dissolves and tells its members; leaving, dissolving and deleted accounts free cards or forfeit shares. - The Guild tile flags joinable groups; Administration › Guilde tunes group places, players, stars, recruitment, loot multipliers, keeper stats, cohesion and the score bonus cap. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
249 lines
17 KiB
JavaScript
249 lines
17 KiB
JavaScript
// Rôle : expéditions de groupe Sokko TCG : tableau de la Guilde, ouverture, inscription, départ par le créateur, garde-fou d'inscription.
|
||
// Ces méthodes s'ajoutent à ExpeditionService (Object.assign sur son prototype) et utilisent `this` comme lui.
|
||
import { randomUUID } from "node:crypto";
|
||
import { dailyDayKey } from "./daily.js";
|
||
import {
|
||
cardExpeditionData, cohesionPct, dangerCount, editionExpeditionData, evaluateTeam, expectedLoot, groupLootPct, groupSlots, guildKeeperSlot, hasCondition, requirementsFor,
|
||
ROLE_BY_STAT, STAT_BY_ROLE
|
||
} from "./expedition-rules.js";
|
||
|
||
const HOUR_MS = 3_600_000;
|
||
|
||
function fail(status, code, message) {
|
||
throw Object.assign(new Error(message), { status, code });
|
||
}
|
||
|
||
const roleStat = (role) => (role ? STAT_BY_ROLE[role] : null);
|
||
|
||
export const groupMethods = {
|
||
// Places des joueurs d'un groupe, prêtes pour l'évaluation (stats figées à l'inscription, étiquettes et collection du catalogue).
|
||
memberSlots(expeditionId) {
|
||
return this.db.prepare(`SELECT s.position, s.role, s.player_id, s.edition_id, s.card_id, s.level, s.stats_json, p.display_name
|
||
FROM expedition_slots s LEFT JOIN players p ON p.id = s.player_id WHERE s.expedition_id = ? AND s.player_id IS NOT NULL ORDER BY s.position`).all(expeditionId)
|
||
.map((row) => {
|
||
const data = cardExpeditionData(this.cards.catalog, row.card_id);
|
||
return {
|
||
position: row.position, role: roleStat(row.role), playerId: row.player_id, playerName: row.display_name, editionId: row.edition_id, cardId: row.card_id,
|
||
level: row.level, stats: JSON.parse(row.stats_json), tags: data?.tags || [], collectionId: data?.collectionId ?? null
|
||
};
|
||
});
|
||
},
|
||
|
||
// Résultat d'un groupe : ses joueurs, complétés par le Veilleur de la Guilde, et la cohésion de leurs collections.
|
||
evaluateGroup(setup, playerSlots, settings) {
|
||
const destination = this.destinations.find((item) => item.id === setup.destination.id) || { ...setup.destination, conditions: [setup.condition].filter(Boolean), dangers: setup.dangers };
|
||
const entry = { condition: setup.condition, dangers: setup.dangers };
|
||
const durationIndex = Math.max(0, settings.durations.hours.indexOf(setup.hours));
|
||
const cohesion = cohesionPct(playerSlots, settings);
|
||
// Le nombre de places est celui de l'ouverture du groupe (un rôle par place), même si le réglage a changé depuis.
|
||
const evaluation = evaluateTeam({ destination, entry, stars: setup.stars, durationIndex, slots: groupSlots(playerSlots, settings, setup.roles.length), synergyPct: cohesion }, settings);
|
||
return { evaluation, cohesion };
|
||
},
|
||
|
||
// Rôles d'un groupe : un par place, dans l'ordre des stats de la destination.
|
||
groupRoles(destination, settings) {
|
||
return destination.stats.slice(0, settings.group.slots);
|
||
},
|
||
|
||
// Validation de l'ouverture d'un groupe (et de son aperçu) : destination, étoiles et durée du groupe, carte et rôle du créateur.
|
||
prepareGroup(playerId, body, settings, today) {
|
||
if (!settings.enabled) fail(409, "EXPEDITIONS_CLOSED", "Les Expéditions sont fermées pour le moment.");
|
||
const { day, resolved, stars, durationIndex, hours } = this.validateChoice(body, settings, today, settings.group);
|
||
const roles = this.groupRoles(resolved.destination, settings);
|
||
if (!roles.includes(body.role)) fail(400, "EXPEDITION_INVALID", "Choisissez le rôle de votre carte.");
|
||
const card = this.ownedCard(playerId, body.editionId, settings);
|
||
const slot = { ...card, role: body.role, position: 0 };
|
||
const setup = this.groupSetup(resolved, stars, hours, settings);
|
||
const { evaluation, cohesion } = this.evaluateGroup(setup, [slot], settings);
|
||
const expected = expectedLoot({ hours, stars, tier: evaluation.tier, fortune: evaluation.stats.fortune, slotCount: settings.group.slots, multiplierPct: groupLootPct(1, settings) }, settings);
|
||
return { day, resolved, stars, durationIndex, hours, slot, setup, evaluation, cohesion, expected };
|
||
},
|
||
|
||
groupSetup({ destination, entry }, stars, hours, settings) {
|
||
return {
|
||
destination: { id: destination.id, name: destination.name, description: destination.description, coverCardId: destination.coverCardId ?? null, stats: destination.stats },
|
||
condition: hasCondition(stars) ? entry.condition : null,
|
||
dangers: entry.dangers.slice(0, dangerCount(stars)),
|
||
stars,
|
||
hours,
|
||
bonusSlot: null,
|
||
roles: this.groupRoles(destination, settings),
|
||
recruitUntil: this.now() + settings.group.recruitHours * HOUR_MS
|
||
};
|
||
},
|
||
|
||
createGroup(playerId, body, requestKey) {
|
||
if (!requestKey || requestKey.length > 100) fail(400, "IDEMPOTENCY_REQUIRED", "Une clé d'idempotence est requise.");
|
||
const settings = this.settings;
|
||
let expeditionId;
|
||
this.cards.database.transaction(() => {
|
||
const previous = this.db.prepare("SELECT response_json FROM idempotency WHERE player_id = ? AND scope = 'expedition-group' AND request_key = ?").get(playerId, requestKey);
|
||
if (previous) {
|
||
expeditionId = JSON.parse(previous.response_json).expeditionId;
|
||
return;
|
||
}
|
||
this.settleFormingInTx(settings);
|
||
if (!settings.enabled) fail(409, "EXPEDITIONS_CLOSED", "Les Expéditions sont fermées pour le moment.");
|
||
const day = dailyDayKey(this.now());
|
||
const plan = this.prepareGroup(playerId, body, settings, { day, entries: this.ensureDay(day, settings) });
|
||
if (plan.slot.busy) fail(409, "EXPEDITION_CARD_BUSY", "Cette carte est déjà en expédition.");
|
||
if (this.activeCount(playerId, "group") >= settings.group.maxConcurrent) fail(409, "EXPEDITION_LIMIT", "Vous participez déjà au nombre maximal d’expéditions de groupe.");
|
||
const now = this.now();
|
||
expeditionId = randomUUID();
|
||
this.db.prepare(`INSERT INTO expeditions(id, mode, day, destination_id, difficulty, duration_ms, creator_id, status, setup_json, created_at)
|
||
VALUES (?, 'group', ?, ?, ?, ?, ?, 'forming', ?, ?)`).run(expeditionId, plan.day, plan.setup.destination.id, plan.stars, plan.hours * HOUR_MS, playerId, JSON.stringify(plan.setup), now);
|
||
this.insertMember(expeditionId, playerId, plan.slot, 0, now);
|
||
this.db.prepare("INSERT INTO idempotency(player_id, scope, request_key, response_json, created_at) VALUES (?, 'expedition-group', ?, ?, ?)")
|
||
.run(playerId, requestKey, JSON.stringify({ expeditionId }), now);
|
||
});
|
||
return { expeditions: this.getExpeditions(playerId), state: this.cards.getState(playerId) };
|
||
},
|
||
|
||
insertMember(expeditionId, playerId, slot, position, now) {
|
||
this.db.prepare("INSERT INTO expedition_members(expedition_id, player_id, joined_at) VALUES (?, ?, ?)").run(expeditionId, playerId, now);
|
||
this.db.prepare("INSERT INTO expedition_slots(expedition_id, position, role, player_id, edition_id, card_id, level, stats_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
|
||
.run(expeditionId, position, ROLE_BY_STAT[slot.role], playerId, slot.editionId, slot.cardId, slot.level, JSON.stringify(slot.stats));
|
||
},
|
||
|
||
formingRow(expeditionId) {
|
||
const row = this.db.prepare("SELECT * FROM expeditions WHERE id = ? AND mode = 'group'").get(expeditionId);
|
||
if (!row || row.status === "cancelled") fail(404, "EXPEDITION_NOT_FOUND", "Ce groupe n’existe plus.");
|
||
if (row.status !== "forming") fail(409, "EXPEDITION_GROUP_DEPARTED", "Ce groupe est déjà parti.");
|
||
return row;
|
||
},
|
||
|
||
joinGroup(playerId, expeditionId, body) {
|
||
const settings = this.settings;
|
||
this.cards.database.transaction(() => {
|
||
this.settleFormingInTx(settings);
|
||
if (!settings.enabled) fail(409, "EXPEDITIONS_CLOSED", "Les Expéditions sont fermées pour le moment.");
|
||
const row = this.formingRow(expeditionId);
|
||
const setup = JSON.parse(row.setup_json);
|
||
const members = this.memberSlots(row.id);
|
||
if (members.some((slot) => slot.playerId === playerId)) fail(409, "EXPEDITION_ALREADY_JOINED", "Vous faites déjà partie de ce groupe.");
|
||
if (members.length >= setup.roles.length) fail(409, "EXPEDITION_GROUP_FULL", "Ce groupe est complet.");
|
||
if (!setup.roles.includes(body?.role)) fail(400, "EXPEDITION_INVALID", "Choisissez le rôle de votre carte.");
|
||
if (members.some((slot) => slot.role === body.role)) fail(409, "EXPEDITION_ROLE_TAKEN", "Ce rôle est déjà pris.");
|
||
const card = this.ownedCard(playerId, body.editionId, settings);
|
||
if (card.busy) fail(409, "EXPEDITION_CARD_BUSY", "Cette carte est déjà en expédition.");
|
||
if (this.activeCount(playerId, "group") >= settings.group.maxConcurrent) fail(409, "EXPEDITION_LIMIT", "Vous participez déjà au nombre maximal d’expéditions de groupe.");
|
||
const taken = new Set(members.map((slot) => slot.position));
|
||
const position = [0, 1, 2, 3].find((index) => !taken.has(index));
|
||
this.insertMember(row.id, playerId, { ...card, role: body.role }, position, this.now());
|
||
});
|
||
return { expeditions: this.getExpeditions(playerId), state: this.cards.getState(playerId) };
|
||
},
|
||
|
||
// Quitter un groupe en formation ; s'il s'agit du créateur, le groupe est dissous.
|
||
leaveGroup(playerId, expeditionId) {
|
||
this.cards.database.transaction(() => {
|
||
this.settleFormingInTx(this.settings);
|
||
const row = this.formingRow(expeditionId);
|
||
if (!this.db.prepare("SELECT 1 FROM expedition_members WHERE expedition_id = ? AND player_id = ?").get(row.id, playerId)) fail(404, "EXPEDITION_NOT_FOUND", "Vous ne faites pas partie de ce groupe.");
|
||
this.leaveGroupInTx(row, playerId);
|
||
});
|
||
return { expeditions: this.getExpeditions(playerId), state: this.cards.getState(playerId) };
|
||
},
|
||
|
||
leaveGroupInTx(row, playerId) {
|
||
if (row.creator_id === playerId) return this.dissolveInTx(row, "creator_left", playerId);
|
||
this.db.prepare("DELETE FROM expedition_slots WHERE expedition_id = ? AND player_id = ?").run(row.id, playerId);
|
||
this.db.prepare("DELETE FROM expedition_members WHERE expedition_id = ? AND player_id = ?").run(row.id, playerId);
|
||
return null;
|
||
},
|
||
|
||
// Dissolution : les cartes sont libérées et les autres joueurs en sont prévenus dans leur historique.
|
||
dissolveInTx(row, reason, exceptPlayerId = null) {
|
||
this.db.prepare("UPDATE expeditions SET status = 'cancelled', completed_at = ? WHERE id = ?").run(this.now(), row.id);
|
||
const setup = JSON.parse(row.setup_json);
|
||
for (const member of this.db.prepare("SELECT player_id FROM expedition_members WHERE expedition_id = ?").all(row.id)) {
|
||
if (member.player_id === exceptPlayerId) continue;
|
||
this.cards.audit(member.player_id, "expedition_dissolved", row.id, { destinationId: setup.destination.id, destinationName: setup.destination.name, reason });
|
||
}
|
||
},
|
||
|
||
// Renonce au butin d'une expédition de groupe en route (compte supprimé) : les autres le gardent.
|
||
forfeitInTx(row, playerId) {
|
||
const now = this.now();
|
||
this.db.prepare("UPDATE expedition_members SET claimed_at = ?, reward_json = ? WHERE expedition_id = ? AND player_id = ?").run(now, JSON.stringify({ eclats: 0, stardust: 0, packs: [] }), row.id, playerId);
|
||
if (!this.db.prepare("SELECT COUNT(*) AS count FROM expedition_members WHERE expedition_id = ? AND claimed_at IS NULL").get(row.id).count) {
|
||
this.db.prepare("UPDATE expeditions SET status = 'completed', completed_at = ? WHERE id = ?").run(now, row.id);
|
||
}
|
||
},
|
||
|
||
departGroup(playerId, expeditionId) {
|
||
const settings = this.settings;
|
||
this.cards.database.transaction(() => {
|
||
this.settleFormingInTx(settings);
|
||
const row = this.formingRow(expeditionId);
|
||
if (row.creator_id !== playerId) fail(403, "EXPEDITION_NOT_CREATOR", "Seul le joueur qui a ouvert le groupe peut le lancer.");
|
||
if (this.memberSlots(row.id).length < settings.group.minPlayers) fail(409, "EXPEDITION_GROUP_TOO_SMALL", `Il faut au moins ${settings.group.minPlayers} joueurs pour partir.`);
|
||
this.launchInTx(row, this.now(), settings);
|
||
});
|
||
return { expeditions: this.getExpeditions(playerId), state: this.cards.getState(playerId) };
|
||
},
|
||
|
||
// Départ d'un groupe : le Veilleur de la Guilde occupe les places vides (sans rôle), le résultat et le butin de chacun sont tirés.
|
||
launchInTx(row, at, settings) {
|
||
const setup = JSON.parse(row.setup_json);
|
||
const members = this.memberSlots(row.id);
|
||
const { evaluation, cohesion } = this.evaluateGroup(setup, members, settings);
|
||
const keeper = guildKeeperSlot(settings);
|
||
const taken = new Set(members.map((slot) => slot.position));
|
||
const free = [0, 1, 2, 3].filter((index) => !taken.has(index)).slice(0, Math.max(0, setup.roles.length - members.length));
|
||
const insertKeeper = this.db.prepare("INSERT INTO expedition_slots(expedition_id, position, role, player_id, edition_id, card_id, level, stats_json) VALUES (?, ?, NULL, NULL, NULL, NULL, 0, ?)");
|
||
for (const position of free) insertKeeper.run(row.id, position, JSON.stringify(keeper.stats));
|
||
const multiplierPct = groupLootPct(members.length, settings);
|
||
const expected = expectedLoot({ hours: setup.hours, stars: setup.stars, tier: evaluation.tier, fortune: evaluation.stats.fortune, slotCount: setup.roles.length, multiplierPct }, settings);
|
||
const updateReward = this.db.prepare("UPDATE expedition_members SET reward_json = ? WHERE expedition_id = ? AND player_id = ?");
|
||
for (const member of members) updateReward.run(JSON.stringify(this.rollReward(expected, settings)), row.id, member.playerId);
|
||
const result = this.resultView(evaluation, { players: members.length, cohesionPct: cohesion, lootPct: multiplierPct });
|
||
this.db.prepare("UPDATE expeditions SET status = 'running', departs_at = ?, returns_at = ?, result_json = ? WHERE id = ?")
|
||
.run(at, at + setup.hours * HOUR_MS, JSON.stringify(result), row.id);
|
||
},
|
||
|
||
// Garde-fou : à la fin de la période d'inscription, un groupe part seul s'il a assez de joueurs, sinon il est dissous.
|
||
settleFormingInTx(settings) {
|
||
const now = this.now();
|
||
for (const row of this.db.prepare("SELECT * FROM expeditions WHERE status = 'forming'").all()) {
|
||
const setup = JSON.parse(row.setup_json);
|
||
if (setup.recruitUntil > now) continue;
|
||
if (this.memberSlots(row.id).length >= settings.group.minPlayers) this.launchInTx(row, setup.recruitUntil, settings);
|
||
else this.dissolveInTx(row, "too_few_players");
|
||
}
|
||
},
|
||
|
||
settleForming() {
|
||
const due = this.db.prepare("SELECT setup_json FROM expeditions WHERE status = 'forming'").all().some((row) => JSON.parse(row.setup_json).recruitUntil <= this.now());
|
||
if (due) this.cards.database.transaction(() => this.settleFormingInTx(this.settings));
|
||
},
|
||
|
||
// Tableau de la Guilde : chaque groupe en formation, ses membres, les rôles libres et le résultat attendu s'il partait maintenant.
|
||
boardView(playerId, settings) {
|
||
return this.db.prepare("SELECT e.*, p.display_name AS creator_name FROM expeditions e JOIN players p ON p.id = e.creator_id WHERE e.status = 'forming' ORDER BY e.created_at").all().map((row) => {
|
||
const setup = JSON.parse(row.setup_json);
|
||
const members = this.memberSlots(row.id);
|
||
const { evaluation, cohesion } = this.evaluateGroup(setup, members, settings);
|
||
const isMember = members.some((slot) => slot.playerId === playerId);
|
||
const freeRoles = setup.roles.filter((role) => !members.some((slot) => slot.role === role));
|
||
return {
|
||
id: row.id, day: row.day, destination: setup.destination, condition: setup.condition, dangers: setup.dangers, stars: setup.stars, hours: setup.hours,
|
||
creatorName: row.creator_name, isCreator: row.creator_id === playerId, isMember, recruitUntil: setup.recruitUntil, roles: setup.roles, freeRoles,
|
||
members: members.map((slot) => ({ playerName: slot.playerName, own: slot.playerId === playerId, role: slot.role, editionId: slot.editionId, cardId: slot.cardId })),
|
||
canJoin: settings.enabled && !isMember && freeRoles.length > 0,
|
||
canDepart: row.creator_id === playerId && members.length >= settings.group.minPlayers,
|
||
requirements: requirementsFor({ stats: setup.destination.stats }, setup.stars, setup.roles, settings),
|
||
projected: this.resultView(evaluation, { players: members.length, cohesionPct: cohesion, lootPct: groupLootPct(members.length, settings) })
|
||
};
|
||
});
|
||
},
|
||
|
||
// Groupes que le joueur pourrait rejoindre maintenant (rôle libre, une carte jouable non occupée, sous sa limite de groupes).
|
||
joinableGroupCount(playerId, settings, busy) {
|
||
if (this.activeCount(playerId, "group") >= settings.group.maxConcurrent) return 0;
|
||
const free = this.cards.collectionOf(playerId).some((entry) => !busy.has(entry.editionId) && editionExpeditionData(this.cards.catalog, entry.editionId, 0, settings));
|
||
if (!free) return 0;
|
||
return this.db.prepare("SELECT e.setup_json, (SELECT COUNT(*) FROM expedition_members m WHERE m.expedition_id = e.id) AS members FROM expeditions e WHERE e.status = 'forming' AND NOT EXISTS (SELECT 1 FROM expedition_members m WHERE m.expedition_id = e.id AND m.player_id = ?)")
|
||
.all(playerId).filter((row) => row.members < JSON.parse(row.setup_json).roles.length).length;
|
||
}
|
||
};
|