Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/CODEMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,11 @@ export されている関数・定数・型の置き場。名前で引いて、
- `moveKey`(fn):アクションを一意の文字列にする。ランナーが「サーバーに弾かれた手」を覚えて避けるのに使う
- `decideAiAction`(fn):AI が次に打つ手を決める。null は「今は AI の手番ではない」(相手の入力待ち)。

## server/src/ai/keepGuard.ts

- `isStopFlash`(const)
- `keepGuardPick`(fn)

## server/src/ai/legalMoves.ts

- `AiMove`(型):1手の候補。reason は対戦ログとテストのために持つ(AIがなぜその手を選んだかを後から追えるように)
Expand Down Expand Up @@ -463,6 +468,7 @@ export されている関数・定数・型の置き場。名前で引いて、
- `BURST_POLICY`(const):バーストをセットし、意味のない発動は断る。場のコアも消滅させない範囲で支払いに使う。ライフ2の局面で旧の約2倍(2026-11-20)
- `PLAN_POLICY`(const):アタックの計画(attackPlan.ts):取り切れる盤面だけ全員で行き、それ以外は BP で勝てて守り手が残る個体だけで行く。
- `BLOCK_POLICY`(const):ブロックかライフかを、アタッカーのシンボル数と残りのアタックで決める(blockPlan.ts)+守っても負けるなら全員で行く。
- `KEEP_GUARD_POLICY`(const):無駄撃ちのマジックを撃たない(keepGuard.ts・spellFilter.ts):守りのマジックを自分のターンに撃たない+的のいない除去・自分だけ失うお互いの破壊を撃たない。
- `DEFAULT_POLICY`(const):本番の既定。ai:bench --vs-old の旧側(基準)もこれ(BS_AI_OLD=stage1 で段階1の OLD_POLICY)
- `CANDIDATE_POLICY`(const):ai:bench --vs-old の新側(試す案)。基準を動かさないため、案は既存の pick 関数を書き換えず、新しい関数で手を足し引きしてここに差す

Expand All @@ -473,6 +479,10 @@ export されている関数・定数・型の置き場。名前で引いて、
- `pumpAi`(fn):AI が打てる手が無くなるまで1手ずつ進める。すでに走っていれば何もしない
- `pumpAiSync`(fn):テスト用:間隔を空けずに、AI が打てなくなるまでその場で進める。

## server/src/ai/spellFilter.ts

- `wastedSpell`(fn)

## server/src/assetVersions.ts

- `IMMUTABLE_CACHE`(const)
Expand Down
8 changes: 4 additions & 4 deletions scripts/ai-bench.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { runTurnStart } from "../server/src/logic/PhaseManager"
import type { Color, DeckSpec, GameState, PlayerId } from "../server/src/type"
import { pumpAiSync } from "../server/src/ai/runner"
import { magicTags } from "../server/src/ai/moveTags"
import { CANDIDATE_POLICY, DEFAULT_POLICY, OLD_POLICY, type AiPolicy } from "../server/src/ai/policy"
import { BLOCK_POLICY, CANDIDATE_POLICY, DEFAULT_POLICY, OLD_POLICY, type AiPolicy } from "../server/src/ai/policy"
import { LOOKAHEAD_KINDS, LOOKAHEAD_MARGIN, LOOKAHEAD_BUDGET_MS, setLookaheadTrace, type OverrideTrace } from "../server/src/ai/lookahead"
import { appendFileSync, writeFileSync } from "node:fs"
import { enumerateLegalMoves } from "../server/src/ai/legalMoves"
Expand Down Expand Up @@ -51,8 +51,8 @@ function matchups(): Matchup[] {
}
const MATCHUPS = matchups()

// 旧側(基準)は本番の既定 DEFAULT_POLICY。BS_AI_OLD=stage1 で段階1の OLD_POLICY と比べる
const OLD_SIDE: AiPolicy = process.env.BS_AI_OLD === "stage1" ? OLD_POLICY : DEFAULT_POLICY
// 旧側(基準)は本番の既定 DEFAULT_POLICY。BS_AI_OLD=stage1 で段階1の OLD_POLICY、=block で BLOCK_POLICY(既定を替える PR を、替える前と比べる)
const OLD_SIDE: AiPolicy = process.env.BS_AI_OLD === "stage1" ? OLD_POLICY : process.env.BS_AI_OLD === "block" ? BLOCK_POLICY : DEFAULT_POLICY
// 新(CANDIDATE_POLICY)対 旧(基準)。先後を入れ替えて同数回し、色の偏りと先手有利を消す。
// 引き分け=手数上限・詰まり・例外で決着しなかった局
function vsOld(): void {
Expand Down Expand Up @@ -95,7 +95,7 @@ function vsOld(): void {
writeFileSync(tracePath, "")
setLookaheadTrace((t) => overrides.push(t))
}
console.log(`新側: CANDIDATE_POLICY / 旧側: ${OLD_SIDE === OLD_POLICY ? "OLD_POLICY(段階1)" : "DEFAULT_POLICY(基準)"} / KINDS=${[...LOOKAHEAD_KINDS].join(",")} / MARGIN=${LOOKAHEAD_MARGIN} / BUDGET_MS=${LOOKAHEAD_BUDGET_MS} / 組=${MATCHUPS.length} × N=${N}`)
console.log(`新側: CANDIDATE_POLICY / 旧側: ${OLD_SIDE === OLD_POLICY ? "OLD_POLICY(段階1)" : OLD_SIDE === BLOCK_POLICY ? "BLOCK_POLICY" : "DEFAULT_POLICY(基準)"} / KINDS=${[...LOOKAHEAD_KINDS].join(",")} / MARGIN=${LOOKAHEAD_MARGIN} / BUDGET_MS=${LOOKAHEAD_BUDGET_MS} / 組=${MATCHUPS.length} × N=${N}`)
for (let i = 0; i < MATCHUPS.length; i++) {
{
for (let n = 0; n < N; n++) {
Expand Down
60 changes: 60 additions & 0 deletions scripts/smoke/part1040.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// smoke パート1040(AI が無駄撃ちのマジックを撃たない。server/src/ai/keepGuard.ts・spellFilter.ts)
import { assert, createGame, createInstance, getCard, refreshLevelAsOverrides, runTurnStart } from "./helpers"
import type { GameState } from "./helpers"
import { decideAiAction } from "../../server/src/ai/index"
import { BLOCK_POLICY, DEFAULT_POLICY } from "../../server/src/ai/policy"

const WALL = "SD11-014" // ウィンドウォール(コスト4。フラッシュ:このバトルが終了したとき、アタックステップを終了する+【連鎖】)
const LEAP = "SD13-008" // ソウルリープ(フラッシュ:疲労状態のコスト4以下の相手1体を破壊+対象を取らない【連鎖】。的がいなくても使える)
const DEADLY = "BS01-125" // デッドリィバランス(コスト3。フラッシュ:お互い、それぞれのスピリット1体を破壊する)
const ROKU = "BS01-002" // ロクケラトプス
const HERA = "BS01-058" // ヘラクレス・ジオ(3コア=BP6000)
const BEET = "BS01-050" // ビートビートル(1コア=BP1000)
assert(
getCard(WALL).name === "ウィンドウォール" && getCard(LEAP).name === "ソウルリープ" && getCard(DEADLY).name === "デッドリィバランス" &&
getCard(ROKU).name === "ロクケラトプス" && getCard(HERA).name === "ヘラクレス・ジオ" && getCard(BEET).name === "ビートビートル",
"cardId の機械確認",
)

// p1 のメインステップ。p1 の個体は最高レベルを超えるコアを乗せ、コアを置く手(点75)を消す。残る手はマジック・アタックステップへ・ターン終了
function scene(card: string, opp: [string, number, boolean?][]): GameState {
const s = createGame("waste", { p1: "A", p2: "B" }, { p1: "red", p2: "purple" })
runTurnStart(s)
// 実際の対戦と同じ設定。これが無いと、的のいない除去はサーバーの検証で弾かれて合法手に出ない
s.interactiveTargets = true
s.turn = 5
s.turnPlayer = "p1"
s.phase = "main"
for (const pid of ["p1", "p2"] as const) {
const p = s.players[pid]
p.deck = Array.from({ length: 40 }, () => ROKU)
p.hand = []
p.burst = null
}
s.players.p1.field.spirits = [createInstance(ROKU, 1, 5)]
s.players.p2.field.spirits = opp.map(([id, cores, rested]) => {
const inst = createInstance(id, 1, cores)
inst.isRested = !!rested
return inst
})
s.players.p1.hand = [card]
s.players.p1.reserve = 6
refreshLevelAsOverrides(s)
return s
}
const casts = (s: GameState, policy: typeof DEFAULT_POLICY) => decideAiAction(s, "p1", new Set(), policy)?.action.type === "castMagic"

console.log("=== 1. 守りのマジックを自分のメインステップで撃たない ===")
assert(casts(scene(WALL, [[HERA, 3]]), BLOCK_POLICY), "変更前の方針は撃つ(このテストが変更を検出できることの確認)")
assert(!casts(scene(WALL, [[HERA, 3]]), DEFAULT_POLICY), "既定は撃たずに相手のアタックまで持つ")

console.log("=== 2. 的のいない除去を撃たない ===")
assert(casts(scene(LEAP, [[BEET, 1]]), BLOCK_POLICY), "変更前の方針は、疲労状態の相手がいなくても撃つ(【連鎖】があるのでルール上は使える)")
assert(!casts(scene(LEAP, [[BEET, 1]]), DEFAULT_POLICY), "既定は、破壊の的(疲労状態のコスト4以下)がいなければ撃たない")
assert(casts(scene(LEAP, [[BEET, 1, true]]), DEFAULT_POLICY), "疲労状態の的がいれば撃つ")

console.log("=== 3. 自分の個体だけが壊れるお互いの破壊を撃たない ===")
assert(casts(scene(DEADLY, []), BLOCK_POLICY), "変更前の方針は相手の場が空でも撃つ")
assert(!casts(scene(DEADLY, []), DEFAULT_POLICY), "既定は撃たない")

console.log("すべてのチェックに合格しました 🎉(part1040)")
20 changes: 20 additions & 0 deletions server/src/ai/keepGuard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// 無駄撃ちのマジックを候補から落とす(2026-11-20)。(1) アタックステップ・バトルを終わらせる守りのマジックを自分のターンに撃たない。
// 既定同士 400局で、ウィンドウォールを自分のメインステップで 23回(相手のアタック中は 15回)、絶甲氷盾を 6回(同 7回)撃っていた。
// メインステップで他に打つ手が無いと、タグが unknown のマジックの点 25 がアタックステップへ(20)より上になるため。(2) wastedSpell(spellFilter.ts)
import type { GameView, PlayerId } from "../type"
import { getCard } from "../logic/GameState"
import type { AiMove } from "./legalMoves"
import { anyNode } from "./moveTags"
import { blockPick } from "./blockPlan"
import { wastedSpell } from "./spellFilter"

const STOPS = new Set(["endAttackStepAfterBattle", "endAttackStep", "endBattle"])
export const isStopFlash = (cardId: string): boolean =>
getCard(cardId).type === "magic" && getCard(cardId).effects.some((e) => e.kind === "magic" && e.timing === "flash" && anyNode((e as { action: unknown }).action, (x) => STOPS.has(x.type)))

export function keepGuardPick(view: GameView, me: PlayerId, moves: AiMove[]): AiMove | null {
const hand = view.players[me].hand ?? []
const mine = view.turnPlayer === me
const kept = moves.filter((m) => m.action.type !== "castMagic" || !(wastedSpell(view, me, m) || (mine && isStopFlash(hand[m.action.handIndex]!))))
return blockPick(view, me, kept.length > 0 ? kept : moves)
}
9 changes: 7 additions & 2 deletions server/src/ai/policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { pickBestMove } from "./evaluate"
import { lookaheadPick } from "./lookahead"
import { planPick } from "./attackPlan"
import { blockPick } from "./blockPlan"
import { keepGuardPick } from "./keepGuard"

// pickState は先読み用(GameState を要る)。手を返したらそれを使い、null なら pick に任せる。
// pick の入力は GameView のまま(評価に GameState を渡さない原則)
Expand Down Expand Up @@ -38,8 +39,12 @@ export const PLAN_POLICY: AiPolicy = { pick: planPick }
// PLAN_POLICY に構築済み 4800局 50.8%(49.4〜52.2)・2400局 52.1%、色デッキ 52.0%。勝率の差は小さいが、受けると負けるのにライフで受ける手が消える(2026-11-20 ユーザー指示で採用)
export const BLOCK_POLICY: AiPolicy = { pick: blockPick }

// 無駄撃ちのマジックを撃たない(keepGuard.ts・spellFilter.ts):守りのマジックを自分のターンに撃たない+的のいない除去・自分だけ失うお互いの破壊を撃たない。
// BLOCK_POLICY に構築済み 4800局 49.5%(48.0〜50.9)で勝率の差は見えない。手が変わった局は 400局中 53局で、その局の勝率は約 64%(2026-11-20)
export const KEEP_GUARD_POLICY: AiPolicy = { pick: keepGuardPick }

// 本番の既定。ai:bench --vs-old の旧側(基準)もこれ(BS_AI_OLD=stage1 で段階1の OLD_POLICY)
export const DEFAULT_POLICY: AiPolicy = BLOCK_POLICY
export const DEFAULT_POLICY: AiPolicy = KEEP_GUARD_POLICY

// ai:bench --vs-old の新側(試す案)。基準を動かさないため、案は既存の pick 関数を書き換えず、新しい関数で手を足し引きしてここに差す
export const CANDIDATE_POLICY: AiPolicy = BLOCK_POLICY
export const CANDIDATE_POLICY: AiPolicy = KEEP_GUARD_POLICY
38 changes: 38 additions & 0 deletions server/src/ai/spellFilter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// 撃っても相手に当たらない・自分も同じだけ失うマジックを候補から落とす(2026-11-20)。pruneMoves(moveTags.ts)は「相手の場が空」しか見ない。
// 既定同士 400局で、相手の場に BP2000 以下がいないのにツインフレイムを撃つ・1ターン目に自分の1体だけが壊れるデッドリィバランスを撃つ、などが 167回あった
import type { EffectAction, GameView, PlayerId, ResolvedTargetFilter } from "../type"
import { getCard } from "../logic/GameState"
import { matchesTarget } from "../../../shared/rules/targetFilter"
import type { AiMove } from "./legalMoves"

const other = (pid: PlayerId): PlayerId => (pid === "p1" ? "p2" : "p1")
function leaves(a: EffectAction, out: Record<string, any>[]): void {
const x = a as Record<string, any>
if (x.type === "sequence") for (const s of x.actions) leaves(s, out)
else if (x.type === "if") { leaves(x.then, out); if (x.else) leaves(x.else, out) }
else if (x.type === "chooseActionMode") for (const m of x.modes) for (const s of m.actions) leaves(s, out)
else out.push(x)
}
const mutual = (x: Record<string, any>) => x.type === "mutualDestroyChoice" || (x.type === "destroy" && x.side === "both")
const plainDestroy = (x: Record<string, any>) =>
x.type === "destroy" && !x.side && !x.anySide && !x.target && !x.nexus && !x.asCost && !JSON.stringify(x.filter ?? {}).includes("self")

export function wastedSpell(view: GameView, me: PlayerId, move: AiMove): boolean {
if (move.action.type !== "castMagic") return false
const cardId = view.players[me].hand?.[move.action.handIndex]
if (!cardId) return false
const effects = getCard(cardId).effects.filter((e) => e.kind === "magic")
if (effects.length === 0) return false
const opp = other(me)
const mySpirits = view.players[me].field.spirits.length
const theirSpirits = view.players[opp].field.spirits
return effects.every((e) => {
const ls: Record<string, any>[] = []
leaves((e as { action: EffectAction }).action, ls)
const head = ls[0]
if (!head) return false
if (mutual(head)) return mySpirits > 0 || theirSpirits.length === 0
if (plainDestroy(head)) return !theirSpirits.some((s) => matchesTarget(view, opp, s, head.filter as ResolvedTargetFilter | undefined))
return false
})
}