Spaces:
Sleeping
Sleeping
Download sim/lib.ts from WorstCardGame/worst-card-game: direct link, hf CLI and curl.
- Browser
- Download file 16.1 kB
-
https://huggingface.co/spaces/WorstCardGame/worst-card-game/resolve/main/sim/lib.ts
- Command line
-
hf download hf://spaces/WorstCardGame/worst-card-game/sim/lib.ts
-
curl -L -o lib.ts https://huggingface.co/spaces/WorstCardGame/worst-card-game/resolve/main/sim/lib.ts
16.1 kB
| /** | |
| * 平衡模擬器核心庫(一次性分析工具,不屬於遊戲三層架構)。 | |
| * 直接 import battle-core 原始碼,用 tsx 跑。決定性:自帶種子,所有亂數走 battle-core 的 makeRng。 | |
| * | |
| * 設計:貪婪一步前瞻 AI。每個決策點實際用引擎模擬「打這張的結果狀態」,再用價值函數評估挑最佳, | |
| * 讓引擎自動處理戰士硬幣/連擊、魔法師詠唱序列、野蠻人自傷等閘門(遠強於靜態看卡面 atk)。 | |
| * 「腦袋」=不同權重向量(攻擊型重 atk、防禦型重 def/hp、節奏型重連擊/序列…)+ 隨機基準線。 | |
| * | |
| * 重要限制(core 層、非本工具能改):advanceCastQueue 只在單人 engine END_TURN 呼叫; | |
| * PvP(resolveSimultaneous)/合作(coop) 都不推進詠唱序列 → 魔法師在 PvP/Boss 永遠不釋放法術。 | |
| */ | |
| import { | |
| createGame, step, | |
| getCard, | |
| createPvpPlayer, planTurn, resolveSimultaneous, DEFAULT_PVP_CONFIG, PVP_MAX_TURNS, | |
| createCoopPlayer, coopCommitPlayerTurn, coopBossTurn, coopEndRound, coopOutcome, | |
| createHellgateBoss, | |
| makeRng, nextInt, | |
| STARTING_DECK as WARRIOR_DECK, | |
| buildPvpDeck, draftChoices, coopDraftChoices, PVP_DRAFT_PICKS, COOP_DRAFT_PICKS, | |
| } from "../packages/battle-core/src/index.js"; | |
| import { MAGE_STARTING_DECK, BARBARIAN_STARTING_DECK } from "../packages/battle-core/src/cards.js"; | |
| import type { | |
| GameState, Action, PlayerState, CardData, ClassType, Campaign, RngState, GameEvent, | |
| } from "../packages/battle-core/src/index.js"; | |
| // ===================== 價值函數特徵 ===================== | |
| interface Weights { | |
| atk: number; trueDmg: number; def: number; hp: number; combo: number; | |
| temp: number; mana: number; queue: number; coin: number; hand: number; charge: number; | |
| } | |
| /** 由玩家狀態算各特徵的線性加權分。代表「此刻收手的話這回合大概多好」。 */ | |
| function evalPlayer(p: PlayerState, w: Weights): number { | |
| const effM = p.maxHp + (p.tempMaxHp ?? 0); | |
| return ( | |
| w.atk * (p.atk ?? 0) + | |
| w.trueDmg * (p.trueDamage ?? 0) + | |
| w.def * (p.def ?? 0) + | |
| w.hp * (p.hp ?? 0) + | |
| w.combo * (p.combo ?? 0) + | |
| w.temp * (p.tempMaxHp ?? 0) + | |
| w.mana * (p.mana ?? 0) + | |
| w.queue * (p.castQueue?.length ?? 0) + | |
| w.coin * (p.coin ?? 0) + | |
| w.hand * (p.hand?.length ?? 0) + | |
| w.charge * (p.chargePlayed ?? 0) + | |
| // HP 跌破 25% 線額外懲罰(鼓勵留安全血量) | |
| (p.hp < effM * 0.25 ? -(effM * 0.25 - p.hp) * (w.hp * 2) : 0) | |
| ); | |
| } | |
| // ===================== 腦袋(Brain,OOP 類別階層) ===================== | |
| const EPS = 1e-6; | |
| function rar(c: CardData): number { return c.rarity === "legend" ? 3 : c.rarity === "epic" ? 1.6 : 0; } | |
| function rewardVal(c: CardData): number { | |
| // 估獎勵卡長期價值:稀有度 + 攻防 + 魔法師法術/法杖加成 | |
| let v = rar(c) * 3 + (c.atk ?? 0) * 0.8 + (c.def ?? 0) * 0.6; | |
| if (c.cardType === "spell") v += 3; | |
| if (c.cardType === "staff") v += 4; | |
| return v; | |
| } | |
| /** 模擬「打第 idx 張」的結果(driver 注入:單人用 step、PvP/coop 用 planTurn)。 */ | |
| export type SimulatePlay = (idx: number) => { player: PlayerState; failed: boolean; specialWin: boolean } | null; | |
| /** | |
| * AI 腦袋抽象基底:封裝「出牌決策、過關回血偏好、選棄保留評分、獎勵估值」。 | |
| * 子類別以多型覆寫 pick()/評分;driver 只呼叫方法,不需知道是貪婪還是隨機。 | |
| */ | |
| export abstract class Brain { | |
| constructor(readonly id: string, readonly label: string) {} | |
| /** 過關獎勵:回血 vs 抽卡,true=回血。 */ | |
| abstract preferHeal(p: PlayerState): boolean; | |
| /** 從手牌挑要打的 index(null=收手)。 */ | |
| abstract pick(p: PlayerState, simulate: SimulatePlay): number | null; | |
| /** 選棄/保留評分(越高越想留);預設看攻防+稀有度。 */ | |
| keepScore(c: CardData, _p: PlayerState): number { return (c.atk ?? 0) + (c.def ?? 0) * 0.6 + rar(c) * 2; } | |
| /** 獎勵三選一估值(越高越想要);預設看稀有度+攻防+法術/法杖。 */ | |
| rewardScore(c: CardData, _p: PlayerState): number { return rewardVal(c); } | |
| } | |
| /** 貪婪一步前瞻腦袋:以權重評估「打這張的結果狀態」挑最佳;個性=權重向量 + 回血門檻。 */ | |
| export class GreedyBrain extends Brain { | |
| constructor(id: string, label: string, private readonly w: Weights, private readonly healAt: number) { super(id, label); } | |
| preferHeal(p: PlayerState): boolean { return p.hp / (p.maxHp + (p.tempMaxHp ?? 0)) < this.healAt; } | |
| pick(p: PlayerState, simulate: SimulatePlay): number | null { | |
| let best = evalPlayer(p, this.w); // 現在收手的價值 | |
| let bestIdx: number | null = null; | |
| for (let i = 0; i < p.hand.length; i++) { | |
| const sim = simulate(i); | |
| if (!sim || sim.failed) continue; | |
| if (sim.player.hp <= 0 && !sim.specialWin) continue; // 不打會當場致死的牌(野蠻人生存護欄) | |
| const v = sim.specialWin ? 1e9 : evalPlayer(sim.player, this.w); // 特殊勝利最優先 | |
| if (v > best + EPS) { best = v; bestIdx = i; } | |
| } | |
| return bestIdx; | |
| } | |
| } | |
| /** 隨機基準線腦袋:均勻挑可打出的牌、~10% 收手;獎勵/選棄也隨機。揭示「技巧 vs 運氣」下界。 */ | |
| export class RandomBrain extends Brain { | |
| private rngRef: { r: RngState }; | |
| constructor(seed: number) { super("rand", "隨機"); this.rngRef = { r: makeRng(seed) }; } | |
| private roll(n: number): number { const [v, r2] = nextInt(this.rngRef.r, n); this.rngRef.r = r2; return v; } | |
| preferHeal(): boolean { return this.roll(1000) < 500; } | |
| override keepScore(): number { return this.roll(1000); } | |
| override rewardScore(): number { return this.roll(1000); } | |
| pick(p: PlayerState, simulate: SimulatePlay): number | null { | |
| if (this.roll(100) < 10) return null; // ~10% 直接收手 | |
| const playable: number[] = []; | |
| for (let i = 0; i < p.hand.length; i++) { | |
| const sim = simulate(i); | |
| if (sim && !sim.failed && (sim.player.hp > 0 || sim.specialWin)) playable.push(i); | |
| } | |
| if (playable.length === 0) return null; | |
| return playable[this.roll(playable.length)]!; | |
| } | |
| } | |
| export const BRAINS_FIXED: Brain[] = [ | |
| new GreedyBrain("aggro", "攻擊型", { atk: 1.0, trueDmg: 1.0, def: 0.15, hp: 0.12, combo: 0.4, temp: 0.35, mana: 0.02, queue: 6, coin: 0.2, hand: 0.05, charge: 4 }, 0.25), | |
| new GreedyBrain("defen", "防禦型", { atk: 0.6, trueDmg: 0.6, def: 1.0, hp: 0.7, combo: 0.3, temp: 0.7, mana: 0.04, queue: 5, coin: 0.15, hand: 0.1, charge: 2 }, 0.6), | |
| new GreedyBrain("tempo", "節奏型", { atk: 0.95, trueDmg: 0.95, def: 0.45, hp: 0.3, combo: 0.7, temp: 0.45, mana: 0.05, queue: 7, coin: 0.35, hand: 0.2, charge: 3 }, 0.45), | |
| ]; | |
| export function makeRandomBrain(seed: number): Brain { return new RandomBrain(seed); } | |
| // ===================== 單人 driver ===================== | |
| export interface SingleResult { | |
| won: boolean; levelReached: number; maxLevel: number; | |
| turns: number; hpLeft: number; effMaxEnd: number; spellCasts: number; aborted: boolean; | |
| } | |
| function choosePendingIndices(hand: number[], scry: number[] | undefined, count: number, keep: boolean, brain: Brain, p: PlayerState): number[] { | |
| if (scry) { | |
| return scry.map((id, i) => ({ i, s: brain.keepScore(getCard(id), p) })) | |
| .sort((a, b) => b.s - a.s).slice(0, count).map((x) => x.i); | |
| } | |
| const ranked = hand.map((id, i) => ({ i, s: brain.keepScore(getCard(id), p) })) | |
| .sort((a, b) => (keep ? b.s - a.s : a.s - b.s)); | |
| return ranked.slice(0, Math.min(count, hand.length)).map((x) => x.i); | |
| } | |
| export function runSingle(opts: { | |
| classType: ClassType; campaign: Campaign; seed: number; brain: Brain; hardMode?: boolean; | |
| }): SingleResult { | |
| let st = createGame({ classType: opts.classType, seed: opts.seed, campaign: opts.campaign, hardMode: opts.hardMode }); | |
| let turns = 0, casts = 0, safety = 0; | |
| const CAP = 6000; | |
| while (st.phase !== "VICTORY" && st.phase !== "GAME_OVER") { | |
| if (++safety > CAP) return mkSingle(st, turns, casts, true); | |
| const ph = st.phase; | |
| let action: Action; | |
| if (ph === "PLAYER_TURN") { | |
| const idx = opts.brain.pick(st.player, (i) => { | |
| const r = step(st, { type: "PLAY_CARD", handIndex: i }); | |
| if (r.events.some((e: GameEvent) => e.type === "CARD_PLAY_FAILED")) return { player: r.state.player, failed: true, specialWin: false }; | |
| return { player: r.state.player, failed: false, specialWin: r.state.phase === "VICTORY" }; | |
| }); | |
| action = idx === null ? { type: "END_TURN" } : { type: "PLAY_CARD", handIndex: idx }; | |
| } else if (ph === "PENDING_CHOICE") { | |
| const pc: any = st.pendingChoice; | |
| const indices = choosePendingIndices(st.player.hand, pc?.scry, pc?.count ?? 0, pc?.keep === true, opts.brain, st.player); | |
| action = { type: "CHOOSE_CARDS", indices }; | |
| } else if (ph === "REWARD_SELECT") { | |
| if (st.rewardChoices && st.rewardChoices.length > 0) { | |
| const ranked = st.rewardChoices.map((id, i) => ({ i, s: opts.brain.rewardScore(getCard(id), st.player) })) | |
| .sort((a, b) => b.s - a.s); | |
| action = { type: "PICK_REWARD", choiceIndex: ranked[0]!.i }; | |
| } else { | |
| action = opts.brain.preferHeal(st.player) ? { type: "REWARD_HEAL" } : { type: "REWARD_DRAFT" }; | |
| } | |
| } else break; | |
| const r = step(st, action); | |
| st = r.state; | |
| casts += r.events.filter((e: GameEvent) => e.type === "SPELL_SUCCESS").length; | |
| if (action.type === "END_TURN") turns++; | |
| } | |
| return mkSingle(st, turns, casts, false); | |
| } | |
| function mkSingle(st: GameState, turns: number, casts: number, aborted: boolean): SingleResult { | |
| return { | |
| won: st.phase === "VICTORY", levelReached: st.level, maxLevel: st.maxLevel, | |
| turns, hpLeft: st.player.hp, effMaxEnd: st.player.maxHp + (st.player.tempMaxHp ?? 0), | |
| spellCasts: casts, aborted, | |
| }; | |
| } | |
| // ===================== PvP / coop 回合規劃(planTurn 版) ===================== | |
| /** 規劃某玩家一整回合(貪婪逐張套用 planTurn)。回傳 plan 完的 {state, rng, spellCasts}。 */ | |
| export function planPlayerTurn( | |
| state0: PlayerState, rng0: RngState, brain: Brain, mode: "single" | "pvp", | |
| ): { state: PlayerState; rng: RngState; spellCasts: number } { | |
| let cur = state0, rng = rng0, casts = 0, guard = 0; | |
| while (guard++ < 300) { | |
| const idx = brain.pick(cur, (i) => { | |
| const r = planTurn(cur, rng, [{ type: "PLAY_CARD", handIndex: i }], mode); | |
| if (r.events.some((e: GameEvent) => e.type === "CARD_PLAY_FAILED")) return { player: r.state, failed: true, specialWin: false }; | |
| return { player: r.state, failed: false, specialWin: r.state.specialWin === true }; | |
| }); | |
| if (idx === null) break; | |
| const r = planTurn(cur, rng, [{ type: "PLAY_CARD", handIndex: idx }], mode); | |
| casts += r.events.filter((e: GameEvent) => e.type === "SPELL_SUCCESS").length; | |
| if (r.pending) { | |
| const pc: any = r.pending; | |
| const indices = choosePendingIndices(r.state.hand, pc.scry, pc.count ?? 0, pc.keep === true, brain, r.state); | |
| const r2 = planTurn(cur, rng, [{ type: "PLAY_CARD", handIndex: idx }, { type: "CHOOSE_CARDS", indices }], mode); | |
| casts += r2.events.filter((e: GameEvent) => e.type === "SPELL_SUCCESS").length; | |
| cur = r2.state; rng = r2.rng; | |
| if (r2.forcedEnd) break; | |
| continue; | |
| } | |
| cur = r.state; rng = r.rng; | |
| if (r.forcedEnd) break; | |
| } | |
| return { state: cur, rng, spellCasts: casts }; | |
| } | |
| // ===================== PvP driver ===================== | |
| export interface PvpResult { winner: "A" | "B" | "draw"; turns: number; castsA: number; castsB: number; } | |
| const DUMMY_P = {} as PlayerState; // rewardScore 不讀 p(卡面估值) | |
| /** 戰前 draft:依職業跑 PvP(10)/coop(8) 三選一,腦袋挑最佳,回 base+picks 牌組。魔法師無 draft 池 → 用起始牌組。 */ | |
| function draftDeck(classType: ClassType, seed: number, brain: Brain, mode: "pvp" | "coop"): readonly number[] { | |
| if (classType === "MAGE") return MAGE_STARTING_DECK; // 魔法師無 PvP/coop draft 池 | |
| let rng = makeRng(seed); | |
| const picks: number[] = []; | |
| const total = mode === "pvp" ? PVP_DRAFT_PICKS : COOP_DRAFT_PICKS; | |
| for (let k = 0; k < total; k++) { | |
| const dc = mode === "pvp" ? draftChoices(rng, k, picks, classType) : coopDraftChoices(rng, k, picks, classType); | |
| rng = dc.rng; | |
| const best = dc.choices | |
| .map((id, i) => ({ i, s: brain.rewardScore(getCard(id), DUMMY_P) })) | |
| .sort((a, b) => b.s - a.s)[0]!; | |
| picks.push(dc.choices[best.i]!); | |
| } | |
| return buildPvpDeck(picks, classType); | |
| } | |
| export function runPvp(opts: { | |
| classA: ClassType; classB: ClassType; seedA: number; seedB: number; brainA: Brain; brainB: Brain; | |
| }): PvpResult { | |
| let A = createPvpPlayer(opts.seedA, opts.classA, draftDeck(opts.classA, opts.seedA ^ 0xabcd, opts.brainA, "pvp")); | |
| let B = createPvpPlayer(opts.seedB, opts.classB, draftDeck(opts.classB, opts.seedB ^ 0xabcd, opts.brainB, "pvp")); | |
| let castsA = 0, castsB = 0, isOvertime = false, turnNo = 1, guard = 0; | |
| while (guard++ < PVP_MAX_TURNS + 5) { | |
| const pa = planPlayerTurn(A.state, A.rng, opts.brainA, "pvp"); | |
| const pb = planPlayerTurn(B.state, B.rng, opts.brainB, "pvp"); | |
| castsA += pa.spellCasts; castsB += pb.spellCasts; | |
| const tr = resolveSimultaneous({ state: pa.state, rng: pa.rng }, { state: pb.state, rng: pb.rng }, turnNo, DEFAULT_PVP_CONFIG, isOvertime); | |
| A = tr.a; B = tr.b; | |
| const oc = tr.result.outcome; | |
| if (oc.kind === "win") return { winner: oc.winner, turns: turnNo, castsA, castsB }; | |
| if (oc.kind === "draw") return { winner: "draw", turns: turnNo, castsA, castsB }; | |
| isOvertime = oc.kind === "suddenDeath"; | |
| turnNo++; | |
| } | |
| return { winner: "draw", turns: turnNo, castsA, castsB }; | |
| } | |
| // ===================== 合作 Boss driver ===================== | |
| export interface CoopResult { win: boolean; rounds: number; bossHpLeft: number; casts: number; aborted: boolean; } | |
| const STARTING_DECKS: Record<ClassType, readonly number[]> = { | |
| WARRIOR: WARRIOR_DECK, BARBARIAN: BARBARIAN_STARTING_DECK, MAGE: MAGE_STARTING_DECK, | |
| }; | |
| export function runCoop(opts: { | |
| classA: ClassType; classB: ClassType; seedA: number; seedB: number; seedBoss: number; brainA: Brain; brainB: Brain; | |
| }): CoopResult { | |
| const boss = createHellgateBoss(2); | |
| let players = [ | |
| createCoopPlayer(opts.seedA, opts.classA, draftDeck(opts.classA, opts.seedA ^ 0xc007, opts.brainA, "coop")), | |
| createCoopPlayer(opts.seedB, opts.classB, draftDeck(opts.classB, opts.seedB ^ 0xc007, opts.brainB, "coop")), | |
| ]; | |
| const brains = [opts.brainA, opts.brainB]; | |
| let bossRng = makeRng(opts.seedBoss); | |
| let casts = 0, rounds = 0, guard = 0; | |
| while (guard++ < 150) { | |
| rounds++; | |
| const downFlags = [false, false]; | |
| for (let i = 0; i < 2; i++) { | |
| if (players[i]!.state.hp <= 0) { downFlags[i] = true; continue; } | |
| const plan = planPlayerTurn(players[i]!.state, players[i]!.rng, brains[i]!, "single"); | |
| casts += plan.spellCasts; | |
| const commit = coopCommitPlayerTurn(boss, plan.state, i); | |
| players[i] = { state: commit.state, rng: plan.rng }; | |
| downFlags[i] = commit.down; | |
| } | |
| let oc = coopOutcome(boss, players.map((p) => p.state)); | |
| if (oc.kind !== "continue") return mkCoop(oc.kind === "win", rounds, boss.hp, casts, false); | |
| const bt = coopBossTurn(boss, players.map((p) => p.state), bossRng); | |
| bossRng = bt.rng; | |
| oc = coopOutcome(boss, players.map((p) => p.state)); | |
| if (oc.kind !== "continue") return mkCoop(oc.kind === "win", rounds, boss.hp, casts, false); | |
| const er = coopEndRound(players as any, downFlags); | |
| players = er.slots as any; | |
| } | |
| return mkCoop(false, rounds, boss.hp, casts, true); | |
| } | |
| function mkCoop(win: boolean, rounds: number, bossHp: number, casts: number, aborted: boolean): CoopResult { | |
| return { win, rounds, bossHpLeft: bossHp, casts, aborted }; | |
| } | |
| // ===================== 統計 ===================== | |
| export function pct(n: number, d: number): string { return d === 0 ? "0.0%" : ((n / d) * 100).toFixed(1) + "%"; } | |
| export function mean(xs: number[]): number { return xs.length === 0 ? 0 : xs.reduce((a, b) => a + b, 0) / xs.length; } | |