worst-card-game / packages /web /src /coopClient.ts
freeguy2006's picture
Claude Opus 4.8 (1M context)
fix(online): PvP對手/合作隊友顯示勇者名,不再用 Google 帳號名
ba79b8e
Raw History Blame Contribute Delete
12.4 kB
import { useCallback, useEffect, useRef, useState } from "react";
import type { GameEvent, PileEntry, Tag, DraftTier, ClassType, BossDef } from "@wcg/battle-core";
export type Side = "A" | "B";
/** 選 boss 地圖用的圖鑑項(server 送的序列化版本,無 create)。 */
export type BossCatalogEntry = Omit<BossDef, "create">;
/** 與 server coopMatch.ts 的 CoopView 對應(淨化視圖:無 seed、無有序牌庫)。 */
export interface CoopView {
phase: "ORDER" | "TURN" | "BOSS" | "ENDED";
round: number;
order: Side[];
active: Side | "BOSS" | null;
result?: { kind: "win" } | { kind: "defeat"; cause: "boss" | "disconnect" };
boss: { name: string; hp: number; maxHp: number; def: number; rage: number; intent: string[]; isAlive: boolean; imageKey: string };
you: {
side: Side;
classType: ClassType;
hp: number; maxHp: number; tempMaxHp: number; atk: number; def: number;
coin: number; maxCoin: number; combo: number; nextReq: Tag; n: number;
useA: boolean; useB: boolean; down: boolean;
ghost: boolean; lastStand: boolean; // 鬼助:已化鬼魂 / 絕境反擊
mana: number; maxMana: number; castQueue: { cardId: number; remaining: number }[]; // 魔法師:魔力與詠唱序列
isMyTurn: boolean;
hand: number[];
handCost: (number | null)[];
pending: { count: number; keep: boolean; scry?: number[] } | null;
deckCount: number; deckView: PileEntry[];
discardCount: number; discardView: PileEntry[];
burnCount: number; burnView: PileEntry[];
};
ally: { side: Side; classType: ClassType; hp: number; maxHp: number; tempMaxHp: number; atk: number; def: number; down: boolean; ghost: boolean; lastStand: boolean; connected: boolean; handCount: number };
proposedFirst?: Side | null;
allyProposed?: Side | null; // ORDER:隊友提議的先手(讓你看到對方選了先手/後手)
}
type ServerMsg =
| { type: "ROOM_CREATED"; code: string }
| { type: "QUEUED" }
| { type: "BOSS_SELECT"; bosses: BossCatalogEntry[]; selections: { A: string | null; B: string | null } }
| { type: "PICK_CLASS"; youClass: ClassType | null; youConfirmed: boolean; allyClass: ClassType | null; allyConfirmed: boolean }
| { type: "MATCH_FOUND"; matchId: string; you: Side; oppName?: string }
| { type: "DRAFT_CHOICE"; pickIndex: number; total: number; tier: DraftTier; choices: number[]; durationMs: number }
| { type: "DRAFT_WAIT" }
| { type: "COOP_PHASE"; view: CoopView; events: GameEvent[]; durationMs: number }
| { type: "GAME_END"; outcome: "WIN" | "LOSE"; reason: string; canRematch: boolean }
| { type: "OPP_WANTS_REMATCH" }
| { type: "OPP_WANTS_SURRENDER" }
| { type: "OPP_DISCONNECTED" }
| { type: "RECONNECT_TOKEN"; side: Side; token: string }
| { type: "OPP_RECONNECTED" }
| { type: "ROOM_CLOSED" }
| { type: "ERROR"; message: string };
export type CoopStatus = "lobby" | "queueing" | "waiting" | "selectingBoss" | "picking" | "drafting" | "draftWait" | "playing" | "ended";
export interface CoopState {
status: CoopStatus;
connected: boolean;
code?: string;
you?: Side;
oppName?: string; // 隊友勇者名(MATCH_FOUND 收到;訪客 undefined → UI 退回「隊友」)
bossCatalog?: BossCatalogEntry[]; // 選 boss 地圖:可選/即將推出的全部 Boss
bossSelections?: { A: string | null; B: string | null }; // 雙方目前的選擇
chosenBossId?: string; // 雙方共識鎖定的 Boss(供選職業前的介紹頁顯示)
youClass?: ClassType | null; // 我目前選的職業(暫定,可重選)
youConfirmed?: boolean; // 我是否已按「確定」鎖定
allyClass?: ClassType | null; // 隊友目前選的職業(即時可見)
allyConfirmed?: boolean; // 隊友是否已按「確定」鎖定
view?: CoopView;
events?: GameEvent[];
eventSeq?: number; // 每收一次 COOP_PHASE +1 → 戰鬥畫面用來觸發傷害飄字/受擊抖動
deadlineTs?: number;
draft?: { pickIndex: number; total: number; tier: DraftTier; choices: number[] };
draftDeadlineTs?: number;
outcome?: "WIN" | "LOSE";
reason?: string;
canRematch?: boolean; // 對局結束後可同房再戰(雙方仍在線)
rematchRequested?: boolean; // 你已按「再來一局」,等待隊友
oppWantsRematch?: boolean; // 隊友已按「再來一局」
surrenderRequested?: boolean; // 你已按「投降」,等待隊友同意(合作投降需所有人同意)
oppWantsSurrender?: boolean; // 隊友已按「投降」
oppGone?: boolean;
reconnecting?: boolean; // 對局中斷線、自動重連中
error?: string;
}
export interface CoopApi {
state: CoopState;
createRoom: () => void;
quickMatch: () => void;
cancelQueue: () => void;
join: (code: string) => void;
selectBoss: (bossId: string) => void;
backToBoss: () => void;
setClass: (classType: ClassType) => void;
confirmClass: () => void;
draftPick: (choiceIndex: number, pickIndex: number) => void;
propose: (first: Side) => void;
play: (handIndex: number) => void;
choose: (indices: number[]) => void;
endTurn: () => void;
surrender: () => void;
rematch: () => void;
}
export function useCoop(heroName?: string): CoopApi {
const wsRef = useRef<WebSocket | null>(null);
const heroNameRef = useRef<string | undefined>(heroName); // 勇者名(連線訊息帶給 server → 下發給隊友當「隊友名」)
heroNameRef.current = heroName;
const tokenRef = useRef<string | null>(null); // 重連 token(對局中存著;斷線用它重綁)
const statusRef = useRef<CoopStatus>("lobby"); // 鏡像 status,供 onclose 閉包判斷是否該重連
const attemptsRef = useRef(0);
const [state, setState] = useState<CoopState>({ status: "lobby", connected: false });
useEffect(() => {
const proto = location.protocol === "https:" ? "wss" : "ws";
let cancelled = false;
let retryTimer: ReturnType<typeof setTimeout> | undefined;
const connect = (): void => {
const ws = new WebSocket(`${proto}://${location.host}/ws/coop`);
wsRef.current = ws;
ws.onopen = () => {
setState((s) => ({ ...s, connected: true }));
if (tokenRef.current && statusRef.current === "playing") {
ws.send(JSON.stringify({ type: "RECONNECT", token: tokenRef.current })); // 對局中重連 → 重綁回原對局
}
};
ws.onclose = () => {
if (cancelled) return;
setState((s) => ({ ...s, connected: false }));
if (attemptsRef.current < 10) {
if (statusRef.current === "playing") setState((s) => ({ ...s, reconnecting: true }));
const delay = Math.min(500 * 2 ** attemptsRef.current, 5000);
attemptsRef.current += 1;
retryTimer = setTimeout(connect, delay);
}
};
ws.onmessage = (ev) => {
let m: ServerMsg;
try { m = JSON.parse(ev.data as string); } catch { return; }
if (m.type === "RECONNECT_TOKEN") tokenRef.current = m.token;
if (m.type === "COOP_PHASE") attemptsRef.current = 0;
if (m.type === "ROOM_CLOSED" || m.type === "GAME_END") tokenRef.current = null; // 房關/對局結束 → 不再重連
setState((s) => { const ns = reduce(s, m); statusRef.current = ns.status; return ns; });
};
};
connect();
return () => { cancelled = true; if (retryTimer) clearTimeout(retryTimer); wsRef.current?.close(); };
}, []);
const send = useCallback((m: unknown) => {
const ws = wsRef.current;
if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(m));
}, []);
return {
state,
createRoom: useCallback(() => send({ type: "CREATE_ROOM", heroName: heroNameRef.current }), [send]),
quickMatch: useCallback(() => send({ type: "QUICK_MATCH", heroName: heroNameRef.current }), [send]),
cancelQueue: useCallback(() => send({ type: "CANCEL_QUEUE" }), [send]),
join: useCallback((code: string) => send({ type: "JOIN", code, heroName: heroNameRef.current }), [send]),
selectBoss: useCallback((bossId: string) => send({ type: "SELECT_BOSS", bossId }), [send]),
backToBoss: useCallback(() => send({ type: "BACK_TO_BOSS" }), [send]),
// 樂觀更新:點選即時高亮+改選即取消自己的確定(server 一定接受合法職業,回傳 PICK_CLASS 會再校正)
setClass: useCallback((classType: ClassType) => { setState((s) => ({ ...s, youClass: classType, youConfirmed: false })); send({ type: "SET_CLASS", classType }); }, [send]),
confirmClass: useCallback(() => send({ type: "CONFIRM_CLASS" }), [send]),
draftPick: useCallback((choiceIndex: number, pickIndex: number) => send({ type: "DRAFT_PICK", choiceIndex, pickIndex }), [send]),
propose: useCallback((first: Side) => send({ type: "PROPOSE_ORDER", first }), [send]),
play: useCallback((handIndex: number) => send({ type: "PLAY_CARD", handIndex }), [send]),
choose: useCallback((indices: number[]) => send({ type: "CHOOSE_CARDS", indices }), [send]),
endTurn: useCallback(() => send({ type: "END_TURN" }), [send]),
surrender: useCallback(() => { send({ type: "SURRENDER" }); setState((s) => ({ ...s, surrenderRequested: true })); }, [send]),
rematch: useCallback(() => { send({ type: "REMATCH" }); setState((s) => ({ ...s, rematchRequested: true })); }, [send]),
};
}
function reduce(s: CoopState, m: ServerMsg): CoopState {
switch (m.type) {
case "ROOM_CREATED": return { ...s, status: "waiting", code: m.code, error: undefined };
case "QUEUED": return { ...s, status: "queueing", error: undefined };
case "BOSS_SELECT": {
const matched = m.selections.A && m.selections.A === m.selections.B ? m.selections.A : undefined;
const cleared = !m.selections.A && !m.selections.B; // 雙方皆未選=回到選 Boss(從 BossIntro 退回 / 再來一局重置)
const inGame = s.status === "drafting" || s.status === "draftWait" || s.status === "playing";
// 共識鎖定後 server 會補送一次「皆已選定」的 BOSS_SELECT → 已在 picking 別退回;但「清空」要回到選 Boss 地圖。
const status = inGame ? s.status : (!cleared && s.status === "picking") ? "picking" : "selectingBoss";
// 清掉上一局/退回時的結果與旗標,重新一輪選 Boss/職業/draft。
return { ...s, status, bossCatalog: m.bosses, bossSelections: m.selections, chosenBossId: matched ?? s.chosenBossId, outcome: undefined, canRematch: undefined, rematchRequested: false, oppWantsRematch: false, error: undefined };
}
case "PICK_CLASS": return { ...s, status: "picking", youClass: m.youClass, youConfirmed: m.youConfirmed, allyClass: m.allyClass, allyConfirmed: m.allyConfirmed, error: undefined };
case "MATCH_FOUND": return { ...s, you: m.you, oppName: m.oppName, error: undefined };
case "DRAFT_CHOICE":
return { ...s, status: "drafting", draft: { pickIndex: m.pickIndex, total: m.total, tier: m.tier, choices: m.choices }, draftDeadlineTs: Date.now() + m.durationMs };
case "DRAFT_WAIT": return { ...s, status: "draftWait", draft: undefined, draftDeadlineTs: undefined };
case "COOP_PHASE":
// 進戰鬥(含再戰開新局):清掉上一局的結束/再戰旗標
return { ...s, status: "playing", view: m.view, events: m.events, eventSeq: (s.eventSeq ?? 0) + 1, deadlineTs: Date.now() + m.durationMs, draft: undefined, draftDeadlineTs: undefined, oppGone: false, reconnecting: false, outcome: undefined, canRematch: undefined, rematchRequested: false, oppWantsRematch: false };
case "GAME_END": return { ...s, status: "ended", outcome: m.outcome, reason: m.reason, canRematch: m.canRematch, rematchRequested: false, oppWantsRematch: false, surrenderRequested: false, oppWantsSurrender: false, reconnecting: false };
case "OPP_WANTS_REMATCH": return { ...s, oppWantsRematch: true };
case "OPP_WANTS_SURRENDER": return { ...s, oppWantsSurrender: true };
case "OPP_DISCONNECTED":
return s.status === "playing" ? { ...s, oppGone: true } : { ...s, oppGone: true, status: "ended", reason: "隊友已離開" };
case "RECONNECT_TOKEN": return { ...s, you: m.side, reconnecting: false };
case "OPP_RECONNECTED": return { ...s, oppGone: false };
case "ROOM_CLOSED": return { ...s, status: "ended", oppGone: true, canRematch: undefined, reason: s.reason ?? "房間已關閉" };
case "ERROR": return { ...s, error: m.message };
default: return s;
}
}