import { useCallback, useEffect, useRef, useState } from "react"; import type { GameEvent, PileEntry, PvpResolveResult, Tag, DraftTier, ClassType } from "@wcg/battle-core"; export type Side = "A" | "B"; export interface PvpView { turnNo: number; isOvertime: boolean; you: { classType: ClassType; hp: number; maxHp: number; tempMaxHp: number; atk: number; def: number; coin: number; maxCoin: number; combo: number; nextReq: Tag; n: number; mana: number; maxMana: number; castQueue: { cardId: number; remaining: number }[]; // 魔法師:魔力與詠唱序列 useA: boolean; useB: boolean; locked: boolean; forcedEnd: boolean; hand: number[]; handCost: (number | null)[]; // 野蠻人:每張手牌現在打出的真實 HP 自傷代價(伺服器權威算);非野蠻人為 null pending: { count: number; keep: boolean; scry?: number[] } | null; deckCount: number; deckView: PileEntry[]; discardCount: number; discardView: PileEntry[]; burnCount: number; burnView: PileEntry[]; }; opponent: { hp: number; maxHp: number; tempMaxHp: number; locked: boolean }; } type ServerMsg = | { type: "ROOM_CREATED"; code: string } | { type: "QUEUED" } | { type: "PICK_CLASS" } | { 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: "PHASE_START"; turnNo: number; isOvertime: boolean; view: PvpView; durationMs: number } | { type: "PLAY_RESULT"; events: GameEvent[]; view: PvpView } | { type: "LOCKED"; view: PvpView } | { type: "OPP_LOCKED" } | { type: "RESOLVE_RESULT"; turnNo: number; result: PvpResolveResult } | { type: "GAME_END"; outcome: "WIN" | "LOSE" | "DRAW"; reason: string; canRematch: boolean } | { type: "OPP_WANTS_REMATCH" } | { type: "ROOM_CLOSED" } | { type: "OPP_DISCONNECTED" } | { type: "RECONNECT_TOKEN"; side: Side; token: string } | { type: "OPP_RECONNECTED" } | { type: "ERROR"; message: string }; export type PvpStatus = "lobby" | "queueing" | "waiting" | "picking" | "drafting" | "draftWait" | "playing" | "ended"; export interface PvpState { status: PvpStatus; connected: boolean; code?: string; you?: Side; oppName?: string; // 對手登入顯示名(MATCH_FOUND 時收到;訪客為 undefined → UI 退回「對手」) playMsg?: string; // 出牌被引擎拒絕時的原因(CARD_PLAY_FAILED.reason);顯示在頂部訊息列,下次出牌/換相清除 view?: PvpView; deadlineTs?: number; draft?: { pickIndex: number; total: number; tier: DraftTier; choices: number[] }; draftDeadlineTs?: number; oppLocked: boolean; lastResolve?: PvpResolveResult; outcome?: "WIN" | "LOSE" | "DRAW"; reason?: string; canRematch?: boolean; // 本局可再戰(HP分勝負/平手且雙方在線) oppWantsRematch?: boolean; // 對手已按再來一局 oppGone?: boolean; reconnecting?: boolean; // 對局中斷線、自動重連中 error?: string; } export interface PvpApi { state: PvpState; createRoom: () => void; quickMatch: () => void; cancelQueue: () => void; join: (code: string) => void; setClass: (classType: ClassType) => void; draftPick: (choiceIndex: number, pickIndex: number) => void; play: (handIndex: number) => void; choose: (indices: number[]) => void; lock: () => void; surrender: () => void; rematch: () => void; } export function usePvp(heroName?: string): PvpApi { const wsRef = useRef(null); const heroNameRef = useRef(heroName); // 勇者名(連線訊息帶給 server → 下發給對手當「對手名」) heroNameRef.current = heroName; const tokenRef = useRef(null); // 重連 token(對局中存著;斷線用它重綁) const statusRef = useRef("lobby"); // 鏡像 status,供 onclose 閉包判斷是否該重連 const attemptsRef = useRef(0); // 重連退避計數 const [state, setState] = useState({ status: "lobby", connected: false, oppLocked: false }); useEffect(() => { const proto = location.protocol === "https:" ? "wss" : "ws"; let cancelled = false; let retryTimer: ReturnType | undefined; const connect = (): void => { const ws = new WebSocket(`${proto}://${location.host}/ws/pvp`); wsRef.current = ws; ws.onopen = () => { setState((s) => ({ ...s, connected: true })); // 對局中重連:帶 token 要求伺服器把這條新連線重綁回原本的對局 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 })); // 自動重連(指數退避,上限 10 次);對局中額外顯示「重連中」 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 === "PHASE_START") attemptsRef.current = 0; // 連上且收到對局狀態 → 重置退避 if (m.type === "ROOM_CLOSED") 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]), setClass: useCallback((classType: ClassType) => send({ type: "SET_CLASS", classType }), [send]), draftPick: useCallback((choiceIndex: number, pickIndex: number) => send({ type: "DRAFT_PICK", choiceIndex, pickIndex }), [send]), play: useCallback((handIndex: number) => send({ type: "PLAY_CARD", handIndex }), [send]), choose: useCallback((indices: number[]) => send({ type: "CHOOSE_CARDS", indices }), [send]), lock: useCallback(() => send({ type: "LOCK" }), [send]), surrender: useCallback(() => send({ type: "SURRENDER" }), [send]), rematch: useCallback(() => send({ type: "REMATCH" }), [send]), }; } function reduce(s: PvpState, m: ServerMsg): PvpState { switch (m.type) { case "ROOM_CREATED": return { ...s, status: "waiting", code: m.code, error: undefined }; case "QUEUED": return { ...s, status: "queueing", error: undefined }; // 快速配對中,等對手 case "PICK_CLASS": return { ...s, status: "picking", error: undefined }; // 配對成功 → 房內選職業 case "MATCH_FOUND": return { ...s, you: m.you, oppName: m.oppName, error: undefined }; // 之後接 DRAFT_CHOICE(draft)或 PHASE_START(無 draft) 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 }; case "PHASE_START": { // 用客戶端自己的時鐘換算截止點(伺服器只給時長),避免時鐘偏差導致倒數錯誤。 // turnNo===1 = 新的一局(含再戰)→ 清掉上一局的結束/結算殘留。 const fresh = m.turnNo === 1 ? { lastResolve: undefined, outcome: undefined, reason: undefined, oppWantsRematch: false, oppGone: false, canRematch: undefined } : {}; return { ...s, status: "playing", view: m.view, deadlineTs: Date.now() + m.durationMs, oppLocked: false, draft: undefined, reconnecting: false, oppGone: false, playMsg: undefined, ...fresh }; } case "PLAY_RESULT": { // 出牌失敗(標籤鎖/無硬幣/詠唱滿/條件不符…)→ 引擎已在 events 給出原因;撈出來顯示,成功則清除。 const failed = m.events.find((e): e is Extract => e.type === "CARD_PLAY_FAILED"); return { ...s, view: m.view, playMsg: failed ? failed.reason : undefined }; } case "LOCKED": return { ...s, view: m.view }; // you.locked=true → 按鈕變「已鎖定」 case "OPP_LOCKED": return { ...s, oppLocked: true }; case "RESOLVE_RESULT": // 不從 RESOLVE_RESULT 更新 view(會與 result.turnNo 錯位);view 由隨後的 PHASE_START 提供。 return { ...s, lastResolve: m.result, oppLocked: false }; case "GAME_END": return { ...s, status: "ended", outcome: m.outcome, reason: m.reason, canRematch: m.canRematch, oppWantsRematch: false }; case "OPP_WANTS_REMATCH": return { ...s, oppWantsRematch: true }; case "ROOM_CLOSED": return { ...s, status: "ended", canRematch: false, oppGone: true, reason: s.reason ?? "房間已關閉" }; case "OPP_DISCONNECTED": // 對局中:隨後伺服器會送 GAME_END(不動 status);draft/等待中:伺服器已清房,自行轉終局避免卡死。 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 "ERROR": return { ...s, error: m.message }; default: return s; } }