Compare commits

..
Author SHA1 Message Date
KoalaTrapLord d31b8467d0 New HTML battlefield to test features before Unity 2026-04-03 04:39:01 -04:00
28 changed files with 1168 additions and 4561 deletions

No files matched your search

-4
View File
@@ -18,9 +18,5 @@ FORGE_WORKING_DIR=D:/ForgeCommander/forge-repo/forge-gui
# ── Deck Paths ────────────────────────────────────────────────────
# Directory containing your precon .dck files.
# Forge reads deck files directly from this folder.
#
# IMPORTANT: lab_api.py reads PRECON_DIR (not PRECON_DECKS_DIR).
# PRECON_DECKS_DIR is kept below for backwards compat but is NOT used by the server.
PRECON_DIR=D:\ForgeCommander\commander-ai-lab\precon-decks
PRECON_DECKS_DIR=D:\ForgeCommander\commander-ai-lab\precon-decks
FORGE_DECKS_DIR=D:\ForgeCommander\commander-ai-lab\precon-decks
+89 -343
View File
@@ -1,179 +1,46 @@
# Commander AI Lab
A full-stack Magic: The Gathering Commander research platform. Run thousands of simulated games, train neural networks on the outcomes, build decks with AI that learns from simulation data, get LLM-powered coaching, and play live 4-player battles — all from a single unified system.
A full-stack MTG Commander AI research platform. Simulate hundreds of games overnight, train ML models on the results, and let simulation data automatically shape the AI deck builder — all from a web UI or CLI.
---
## What It Does
## Overview
Commander AI Lab connects a rules-complete Forge engine, a fast Monte Carlo simulator, an LLM deck builder, an ML training pipeline, and multiple game clients (web, LAN, Unity) into one closed-loop platform. Simulation results feed back into deck building and AI decision-making, so the system improves the more it plays.
### Key Capabilities
- **Batch Simulation** — Run hundreds or thousands of Commander games unattended using Forge (rules-complete) or a headless Python Monte Carlo engine
- **ML Training Pipeline** — Reinforcement learning (PPO) trains a neural net on game decision logs; outcome-weighted scoring nudges card weights automatically
- **AI Deck Builder** — 7-step LLM pipeline (EDHrec → Scryfall → Ollama) with simulation-learned insights injected into prompts
- **LLM Coach** — Streaming coaching sessions powered by Anthropic Claude or local Ollama models, enriched with RAG-retrieved card knowledge
- **RAG Card Knowledge** — ChromaDB vector store over 30,000+ Scryfall cards with semantic search and auto-staleness monitoring
- **LAN Battlefield** — Browser-based 4-player Commander game client with ML-powered AI opponents and precon deck support
- **Unity Client** — Full Unity application with battleground scene, lobby system, WebSocket game state sync, and cross-platform builds
- **Card Scanner** — OCR pipeline for physical card recognition via Ximilar API
- **163 Precon Decks** — Complete preconstructed deck library in `.dck` format
---
| Layer | What it is |
|---|---|
| **Monte Carlo Engine** | Pure-Python headless sim — runs thousands of games in minutes, no JVM needed |
| **Forge Engine** | Java/Forge rules-complete sim for ground-truth validation |
| **Overnight Runner** | Unattended batch runner — runs sims, updates sim weights, trains neural net |
| **ML Pipeline** | Outcome-weighted RL nudges card scoring weights; neural net trains on decision logs |
| **Deck Builder** | 7-step LLM pipeline (EDHrec → Scryfall → Ollama) now injected with sim-learned insights |
| **AI Coach** | LLM-powered coaching sessions (Anthropic/Ollama) with streaming support |
| **Web UI** | React + FastAPI dashboard for decks, sims, training, and deck building |
## Architecture
```
┌─────────────────────────────────────────────────────────────────────┐
│ Clients │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────────────┐ │
│ │ Web UI │ │ LAN Client │ │ Unity Client │ │
│ │ (React/TS) │ │ (HTML/JS) │ │ (C# / URP) │ │
│ │ /ui │ │ /lan │ │ /unity-client │ │
│ └──────┬───────┘ └──────┬───────┘ └──────┬───────────────────────┘ │
│ └────────────────┼────────────────┘ │
│ │ HTTP/REST + WebSocket │
│ ┌───────────────────────┴─────────────────────────────────────────┐│
│ │ FastAPI Backend (lab_api.py — port 8080) ││
│ │ ││
│ │ /api/lab/* Batch simulation (Forge + Monte Carlo) ││
│ │ /api/deck-builder/* 7-step LLM deck construction ││
│ │ /api/coach/* Streaming LLM coaching sessions ││
│ │ /api/ml/* Neural net training + policy server ││
│ │ /api/rag/* ChromaDB vector search ││
│ │ /api/game/* Live game sessions (Forge IPC) ││
│ │ /api/policy/* ML policy decisions for AI players ││
│ │ /ws/game/{id} WebSocket game state streaming ││
│ └───────┬──────────────┬──────────────┬──────────────┬────────────┘│
│ │ │ │ │ │
│ ┌──────┴──────┐ ┌────┴─────┐ ┌──────┴──────┐ ┌────┴──────┐ │
│ │ Forge │ │ Monte │ │ Ollama │ │ ChromaDB │ │
│ │ Engine │ │ Carlo │ │ (local LLM) │ │ (vector │ │
│ │ (Java/JVM) │ │ Engine │ │ qwen2.5:7b │ │ store) │ │
│ └─────────────┘ │ (Python) │ └─────────────┘ └───────────┘ │
│ └──────────┘ │
│ ┌──────────────────────────────────────────────────────────────────┐│
│ │ ML Pipeline ││
│ │ decisions_*.jsonl → update_weights.py → learned_weights.json ││
│ │ → /api/ml/train → neural net checkpoints ││
│ └──────────────────────────────────────────────────────────────────┘│
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Web UI (React/TypeScript — frontend/) │
│ Deck Builder · Sim Dashboard · Training · Coach │
└────────────────────────┬────────────────────────────────────────┘
│ HTTP/REST + WebSocket
┌────────────────────────┴────────────────────────────────────────┐
│ FastAPI Server (lab_api.py / routes/ — port 8080) │
│ /api/lab/* /api/ml/* /api/coach/* /api/deck-builder/* │
└────────┬──────────────────┬──────────────────┬──────────────────┘
│ │ │
Java subprocess Python sim engine Ollama (local LLM)
(Forge rules) (Monte Carlo) qwen2.5:7b + others
│ │
┌────────┴───────┐ ┌───────┴────────────────────────────────────┐
│ Forge Engine │ │ src/commander_ai_lab/ │
│ (rules- │ │ sim/ — engine, models, rules │
│ complete) │ │ deck_builder/ — 7-step LLM pipeline │
└────────────────┘ │ coach/ — streaming LLM coach │
└────────────────────────────────────────────┘
```
---
## Quick Start (Windows)
## Features
### Simulation Engines
| Engine | Description | Speed |
|---|---|---|
| **Forge** | Rules-complete Java engine — handles the stack, instants, triggered abilities, and all Commander rules. Each game spawns a JVM subprocess. | ~0.04 sims/sec (single-threaded) |
| **Monte Carlo** | Headless Python engine — models combat keywords (flying, trample, deathtouch, lifelink, menace, reach, haste), summoning sickness, tapped state, commander zone, multiplayer targeting, and board wipes. No JVM required. | Thousands of games in minutes |
Both engines feed structured results into the same ML pipeline.
### Deck Builder
The `POST /api/deck-builder/build` endpoint runs a 7-step pipeline:
1. Resolve commander via Scryfall
2. Fetch EDHrec recommendations
3. Fetch Scryfall candidates by category (ramp, removal, draw, lands)
4. Ollama suggests synergy/protection/wincon cards — **simulation insights injected here**
5. Filter by color identity, collection, and ban list
6. Ollama enforces ratios (trim/expand to 99) — **simulation insights injected here**
7. Assemble final deck with smart substitution (guarantees 99-card output)
### AI Coach
LLM-powered coaching with two modes:
- **Full Session** — Deep analysis including removal coverage, ramp quality, draw engine profiling, win conditions, anti-synergy detection, pod meta evaluation, and tempo assessment
- **Quick Digest** — Fast ~5-second summary for rapid feedback
Coaching prompts are enriched with semantically relevant cards from the ChromaDB RAG store (15 cards for full sessions, 8 for quick digests). Supports both Anthropic Claude and local Ollama models with streaming responses.
### RAG Card Knowledge
- **SQLite FTS5** bulk card database from Scryfall data
- **ChromaDB** vector index with natural-language card embeddings
- Automatic staleness monitoring (checks every 6 hours, auto-rebuilds if >14 days old)
- Graceful fallback — RAG failures never block coaching or deck building
### ML Training Pipeline
```
Overnight sims → decisions_*.jsonl
↓
update_weights.py → learned_weights.json (feeds deck builder)
↓
/api/ml/train → neural net training on decision dataset
↓
/api/policy/decide → ML policy serves AI decisions in live games
```
- **Outcome-weighted RL** nudges card scoring weights from game results
- **Neural net** trains on the full decision log dataset
- **Distillation loop** — self-play → collect data → retrain → repeat
- **ELO tracking** and model tournaments for comparing AI versions
- Weights clamped to `[-20.0, 20.0]`, stored in `learned_weights.json`
### Win Condition Tracking
Games are classified by win type — not just "Combat" vs "Other":
- **Combat** — standard creature damage wins
- **Combo** — Approach of the Second Sun, Felidar Sovereign, Happily Ever After, and 30+ known alternate-win cards
- **Drain** — life drain effects
- **Mill** — library depletion
- **Poison** — infect/poison counter wins
Draw games (timeout) are analyzed separately with per-player life-at-timeout snapshots and likely cause identification.
### LAN Battlefield Client
Browser-based 4-player Commander game at `/lan`:
- **AI Bridge** — REST + WebSocket connectivity with ML policy decisions as Priority 1 (falls back to local heuristic AI)
- **Deck System** — 3-tab selector: Precons (163 decks, grouped by set), EDHREC search, and custom deck import
- **Player Panels** — Life counters, commander damage bars, poison/energy/experience/rad counters, emblem management
- **Backend Detection** — Auto-detects the Commander AI Lab backend; works offline with local precon data
### Unity Client
Full Unity application (URP, .NET Standard 2.1) with:
- **Battleground Scene** — 4-seat layout with rotated perspectives, life/poison/commander damage widgets, phase tracker, turn order bar
- **Card System** — Hand, battlefield, graveyard, exile zones with card art, tapped rotation, face-down state, summoning sickness indicators
- **Stack & Mana** — LIFO stack display and 6-pip mana pool
- **Lobby System** — Configure 4 seats (human/AI), POST to backend, WebSocket game state sync
- **Elimination** — Grayscale shader overlay on eliminated players
- **Token System** — Create, tap, add counters, delete tokens
- **Cross-Platform** — Windows, WebGL, Android, iOS build targets
- **Scenes** — MainMenu, Collection, DeckBuilder, DeckGenerator, Simulator, Coach, Scanner, Training, Precon, Battleground
### Card Scanner
OCR pipeline for physical Magic cards using the Ximilar API. Scan cards from photos and match them to the Scryfall database.
---
## Quick Start
### Prerequisites
| Tool | Version |
|---|---|
| Python | 3.10+ |
| Java | 17+ |
| Maven | 3.8+ |
| Node.js | 18+ (for LAN client scripts) |
| Ollama | Latest (for local LLM inference) |
| [Forge](https://github.com/Card-Forge/forge) | Built at `D:\ForgeCommander\forge-repo` |
### Setup (Windows)
**Prerequisites:** Java 17+, Python 3.10+, Maven 3.8+, [Forge](https://github.com/Card-Forge/forge) built at `D:\ForgeCommander\forge-repo`
```powershell
# 1. Build Forge (one-time)
@@ -184,29 +51,17 @@ mvn package -pl forge-gui-desktop "-DskipTests" "-Drevision=2.0.12-SNAPSHOT" -am
cd D:\ForgeCommander\commander-ai-lab
mvn package "-DskipTests"
# 3. Install Python dependencies
pip install -e ".[rag,dev]"
# 3. Install Python deps
pip install -e .
# 4. Pull an Ollama model for the deck builder
ollama pull qwen2.5:7b
# 5. Launch
# 4. Launch
.\start-lab.bat
# → Web UI: http://localhost:8080
# → LAN Client: http://localhost:8080/lan/
# → open http://localhost:8080
```
Or use the automated installer:
```powershell
.\install-commander-ai-lab.ps1
```
---
## Overnight AFK Runner
Run batch simulations unattended, then automatically update card weights and train the neural net:
Runs batch sims unattended, then updates card weights and trains the neural net:
```powershell
python overnight-run.py # default: 11.5h DeepSeek sims
@@ -219,9 +74,9 @@ python overnight-run.py --no-train # skip neural net training
1. `update_weights.py` — nudges `learned_weights.json` from decision logs (feeds deck builder)
2. `/api/ml/train` — trains the neural net on the full decision dataset
---
## Sim → Deck Builder Feedback Loop
## Simulation → Deck Builder Feedback Loop
Simulation outcomes automatically improve deck recommendations:
```
Overnight sims → decisions_*.jsonl
@@ -235,63 +90,24 @@ Ollama prompts (suggest_cards + enforce_deck_ratios)
Better card recommendations
```
When active, `BuildResult.sources_consulted` includes `"sim_weights"`. The loop is a no-op until real sim data exists.
When active, `BuildResult.sources_consulted` includes `"sim_weights"`. No-op until real sim data exists.
---
## Deck Builder Pipeline
## API Reference
The `POST /api/deck-builder/build` endpoint runs 7 steps:
### Simulation
1. Resolve commander via Scryfall
2. Fetch EDHrec recommendations
3. Fetch Scryfall candidates by category (ramp, removal, draw, lands)
4. Ollama suggests synergy/protection/wincon cards ← **sim insights injected here**
5. Filter by color identity, collection, ban list
6. Ollama enforces ratios (trim/expand to 99) ← **sim insights injected here**
7. Assemble final deck
| Endpoint | Method | Description |
|---|---|---|
| `/api/lab/decks` | GET | List available Commander decks |
| `/api/lab/start` | POST | Start Forge batch (returns batchId) |
| `/api/lab/start-deepseek` | POST | Start Python/DeepSeek batch |
| `/api/lab/status?batchId=X` | GET | Poll batch progress |
| `/api/lab/result?batchId=X` | GET | Get completed batch JSON |
| `/api/lab/history` | GET | List past batch runs |
| `/api/lab/precons/deck` | GET | Fetch precon `.dck` file content |
### Deck Builder & Coach
| Endpoint | Method | Description |
|---|---|---|
| `/api/deck-builder/build` | POST | Build a 99-card Commander deck |
| `/api/coach/chat` | POST | Full coaching session (streaming) |
| `/api/coach/quick-digest` | POST | Fast ~5s coaching summary |
### ML & Policy
| Endpoint | Method | Description |
|---|---|---|
| `/api/ml/train` | POST | Start neural net training |
| `/api/ml/train/status` | GET | Poll training progress |
| `/api/policy/decide` | POST | Get ML policy decision for game state |
### RAG
| Endpoint | Method | Description |
|---|---|---|
| `/api/rag/build` | POST | Build/rebuild ChromaDB index |
| `/api/rag/search` | POST | Semantic card search |
| `/api/rag/status` | GET | Index health and staleness |
### Live Game
| Endpoint | Method | Description |
|---|---|---|
| `/api/game/start` | POST | Create a live game session |
| `/api/game/action` | POST | Submit a player action |
| `/api/game/{id}/actions` | GET | Poll Forge IPC actions |
| `/ws/game/{game_id}` | WS | Real-time game state streaming |
---
## ML Scripts
## ML Pipeline
```powershell
# Update card weights from decision logs
# Update sim card weights from decision logs (runs automatically in overnight-run.py)
python -m ml.scripts.update_weights --min-games 10 --lr 0.05 --dry-run
# Reset weights to defaults
@@ -301,7 +117,7 @@ python -m ml.scripts.update_weights --reset
python ml/scripts/generate_synthetic_data.py
```
---
Learned weights are clamped to `[-20.0, 20.0]` and stored in `src/commander_ai_lab/sim/learned_weights.json`.
## Python Simulator API
@@ -313,122 +129,52 @@ stats = run_simulation(deck, num_games=100, name_a="My Deck")
print(f"Win rate: {stats['win_rate']:.1%}, Avg turns: {stats['avg_turns']:.1f}")
```
---
The Monte Carlo engine models: combat keywords (flying, trample, deathtouch, lifelink, menace, reach, haste), summoning sickness, tapped/untap state, commander zone, multiplayer attack targeting, and board wipes. It does **not** model the stack, instants, or continuous type-changing effects.
## API Reference
| Endpoint | Method | Description |
|---|---|---|
| `/api/lab/decks` | GET | List available Commander decks |
| `/api/lab/start` | POST | Start Forge batch (returns batchId) |
| `/api/lab/start-deepseek` | POST | Start Python/DeepSeek batch |
| `/api/lab/status?batchId=X` | GET | Poll batch progress |
| `/api/lab/result?batchId=X` | GET | Get completed batch JSON |
| `/api/lab/history` | GET | List past batch runs |
| `/api/ml/train` | POST | Start neural net training |
| `/api/ml/train/status` | GET | Poll training progress |
| `/api/coach/chat` | POST | LLM coaching session (streaming) |
| `/api/deck-builder/build` | POST | Build a 99-card Commander deck |
## Project Structure
```
commander-ai-lab/
├── lab_api.py # FastAPI server entry point
├── overnight-run.py # AFK batch runner
├── start-lab.bat # Windows one-click launcher
├── install-commander-ai-lab.ps1 # Automated setup script
├── pom.xml # Maven build (Java/Forge components)
├── pyproject.toml # Python package config
│
├── routes/ # FastAPI route modules
│ ├── lab.py # Batch simulation
│ ├── deckbuilder.py # Deck builder pipeline
│ ├── coach.py # LLM coaching
│ ├── ml.py # ML training
│ ├── rag.py # ChromaDB vector search
│ ├── game.py # Live game sessions
│ ├── policy.py # ML policy server
│ ├── precon.py # Precon deck serving
│ ├── scanner.py # Card OCR
│ └── ws_game.py # WebSocket game state
│
├── services/ # Core service layer
│ ├── forge_runner.py # Forge subprocess management
│ ├── draw_game_analyzer.py # Draw/timeout analysis
│ ├── rag_store.py # ChromaDB vector store
│ └── card_text.py # Shared card text builder
│
├── lab_api.py # FastAPI server entry point
├── frontend/ # React + TypeScript web UI
├── ui/ # Legacy static HTML UI
├── src/commander_ai_lab/
│ ├── sim/ # Monte Carlo engine
│ │ ├── engine.py # Game loop
│ │ ├── models.py # GameResult, Card, Player
│ │ ├── rules.py # Combat, keywords, commander rules
│ │ ├── win_condition_parser.py # Alternate win detection
│ │ └── learned_weights.json # ML-learned card weights
│ ├── deck_builder/ # 7-step LLM pipeline
│ │ ├── api/ # Scryfall, EDHrec, Ollama, sim_insights
│ │ ├── core/ # Models, rules engine, assembler
│ │ └── pipeline/ # build_deck.py orchestrator
│ └── coach/ # LLM coaching
│ ├── coach_service.py # Session + quick digest
│ ├── prompt_template.py # System/user prompts
│ └── embeddings.py # Card embedding utilities
│
├── ml/ # ML training pipeline
│ ├── scripts/ # update_weights.py, ml_cli.py
│ ├── training/ # Neural net trainer
│ ├── encoder/ # Feature encoding
│ └── models/ # Saved checkpoints
│
├── lan-client/ # Browser-based LAN battlefield
│ ├── index.html # Entry point
│ ├── engine.js # Game engine + ML AI turns
│ ├── ai-bridge.js # Backend connector + policy bridge
│ ├── player-panels.js # Enhanced player panels
│ ├── ui.js # 3-tab deck selector + setup
│ └── precons.js # 163 precon deck data
│
├── unity-client/ # Unity game client
│ └── Assets/
│ ├── Scenes/ # 11 scenes (MainMenu → Battleground)
│ ├── Scripts/ # C# controllers, models, services
│ ├── Prefabs/ # Card, deck slot, chat bubble
│ └── Materials/ # URP materials + grayscale shader
│
├── scanner/ # Card OCR pipeline (Ximilar)
├── precon-decks/ # 163 preconstructed decks (.dck)
├── sample-decks/ # Sample deck files
├── data/ # Runtime data (ChromaDB, bulk DB)
├── logs/ # Simulation + decision logs
├── docs/ # Architecture docs + schemas
├── tests/ # Test suite
├── scripts/ # Utility scripts
├── .github/workflows/ # CI + Unity build automation
└── src/main/java/ # Java/Forge batch runner
└── commanderailab/
│ ├── sim/ # Monte Carlo engine (engine, models, rules)
│ ├── deck_builder/ # LLM deck builder pipeline
│ │ ├── api/ # Scryfall, EDHrec, Ollama, sim_insights
│ │ ├── core/ # Models, rules engine, assembler
│ │ └── pipeline/ # build_deck.py (7-step orchestrator)
│ └── coach/ # LLM coaching (Anthropic + Ollama)
├── ml/
│ ├── scripts/ # update_weights.py, ml_cli.py
│ ├── training/ # Neural net trainer
│ ├── encoder/ # Feature encoding
│ └── models/ # Saved model checkpoints
├── scanner/ # Card OCR pipeline
├── logs/decisions/ # ML decision logs (gitignored)
└── src/main/java/commanderailab/ # Java/Forge batch runner
```
---
## Tech Stack
| Layer | Technology |
|---|---|
| Backend | Python 3.10+, FastAPI, Uvicorn |
| Simulation (rules-complete) | Java 17, Maven, Forge |
| Simulation (fast) | Python Monte Carlo engine |
| LLM Inference | Ollama (qwen2.5:7b), Anthropic Claude |
| Vector Store | ChromaDB with all-MiniLM-L6-v2 embeddings |
| Card Database | SQLite FTS5 (Scryfall bulk data) |
| ML Training | PyTorch, PPO reinforcement learning |
| Web Client | HTML/CSS/JS |
| Unity Client | Unity 2022 LTS, URP, C# |
| CI/CD | GitHub Actions |
---
## Known Limitations
- **Monte Carlo engine** — no stack, no instants, no continuous type-changing effects (animated lands don't attack)
- **Forge engine** — each game spawns a new JVM (~2–3s overhead); ~0.04 sims/sec single-threaded
- **Forge** — winner life total not captured in quiet mode (only reports losers)
- **Deck builder** — Ollama suggestions depend on the local model quality; `qwen2.5:7b` works well
- **LAN client** — EDHREC commander search is a stub (backend-powered, not yet fully wired)
---
## Contributing
Commander AI Lab is an active research project. Check the [open issues](https://github.com/KoalaTrapLord/commander-ai-lab/issues) for areas where contributions are welcome.
---
## License
See repository for license details.
- **Monte Carlo engine** — no stack, no instants, no continuous type changes (animated lands don't attack)
- **Forge engine** — each game spawns a new JVM (~2-3s overhead), ~0.04 sims/sec single-threaded
- **Forge winner life total** not captured (quiet mode only reports losers)
- **Deck builder** — Ollama suggestions are only as good as the local model; `qwen2.5:7b` works well
-257
View File
@@ -1,257 +0,0 @@
<#
.SYNOPSIS
Smoke-tests the Commander AI Lab policy server from PowerShell.
Checks: server reachable -> /api/policy/health -> /api/policy/decide.
Prints a plain-English pass/fail for every step.
.USAGE
# From repo root (server already running in another window):
.\Test-PolicyServer.ps1
# Custom host/port:
.\Test-PolicyServer.ps1 -BaseUrl http://localhost:9000
# Pretty-print the full decide response:
.\Test-PolicyServer.ps1 -Verbose
#>
param(
[string]$BaseUrl = "http://localhost:8080",
[switch]$Verbose
)
$ErrorActionPreference = "Stop"
# ---- helpers ----------------------------------------------------------------
function Write-Pass { param([string]$msg) Write-Host " [PASS] $msg" -ForegroundColor Green }
function Write-Fail { param([string]$msg) Write-Host " [FAIL] $msg" -ForegroundColor Red }
function Write-Info { param([string]$msg) Write-Host " [INFO] $msg" -ForegroundColor Cyan }
function Write-Warn { param([string]$msg) Write-Host " [WARN] $msg" -ForegroundColor Yellow }
function Write-Step { param([string]$msg) Write-Host "`n-- $msg" -ForegroundColor White }
$allPassed = $true
function Invoke-Step {
param(
[string] $Name,
[scriptblock] $Block
)
Write-Step $Name
try { & $Block }
catch {
Write-Fail $_.Exception.Message
$script:allPassed = $false
}
}
# ---- Step 1: server reachable -----------------------------------------------
Invoke-Step "Step 1 -- Server reachable at $BaseUrl" {
$r1 = $null
try { $r1 = Invoke-WebRequest -Uri "$BaseUrl/docs" -UseBasicParsing -TimeoutSec 5 } catch {}
if ($r1 -and $r1.StatusCode -eq 200) {
Write-Pass "FastAPI server is up (GET /docs -> 200)"
return
}
$r2 = $null
try { $r2 = Invoke-WebRequest -Uri "$BaseUrl/" -UseBasicParsing -TimeoutSec 5 } catch {}
if ($r2 -and $r2.StatusCode -lt 500) {
Write-Pass "FastAPI server is up (GET / -> $($r2.StatusCode))"
return
}
throw "Cannot reach $BaseUrl -- is lab_api.py / uvicorn running?"
}
# ---- Step 2: /api/policy/health ---------------------------------------------
$modelLoaded = $false
Invoke-Step "Step 2 -- GET $BaseUrl/api/policy/health" {
$resp = Invoke-RestMethod -Uri "$BaseUrl/api/policy/health" -Method Get -TimeoutSec 10
if ($Verbose) { $resp | ConvertTo-Json -Depth 5 | Write-Host }
if ($resp.ready -eq $true) {
Write-Pass "Model is loaded and ready (ready=true)"
$script:modelLoaded = $true
} elseif ($resp.status -eq "degraded") {
Write-Fail "Health returned status=degraded / ready=false"
Write-Warn " -> Policy model is NOT loaded."
Write-Warn " -> Start the server with --load-policy, or call POST /api/ml/load_model first."
Write-Warn " -> Confirm models/ contains a valid .pt checkpoint."
$script:allPassed = $false
} else {
Write-Warn "Unexpected health response -- dumping:"
$resp | ConvertTo-Json -Depth 5 | Write-Host
$script:allPassed = $false
}
}
# ---- Step 3: /api/policy/decide (synthetic snapshot) ------------------------
Invoke-Step "Step 3 -- POST $BaseUrl/api/policy/decide (synthetic 4-player snapshot)" {
if (-not $script:modelLoaded) {
Write-Warn "Skipping /decide -- model not loaded (Step 2 failed)."
Write-Warn "Fix Step 2 first, then re-run."
return
}
$body = [ordered]@{
game_id = "ps1-smoke-test"
turn = 3
phase = "MAIN1"
active_player = 0
playstyle = "midrange"
temperature = 1.0
greedy = $false
players = @(
[ordered]@{
seat = 0
name = "TestPlayer0"
life = 40
manaAvailable = 3
landCount = 3
creaturesOnField = 1
totalPowerOnBoard = 2
hand = @("Cultivate", "Solemn Simulacrum", "Sol Ring")
battlefield = @("Forest", "Forest", "Forest", "Birds of Paradise")
graveyard = @()
commandZone = @("Atraxa, Praetors Voice")
},
[ordered]@{
seat = 1
name = "TestPlayer1"
life = 38
manaAvailable = 2
landCount = 2
creaturesOnField = 0
totalPowerOnBoard = 0
handCount = 4
hand = @()
battlefield = @("Island", "Swamp")
graveyard = @()
commandZone = @("Ur-Dragon")
},
[ordered]@{
seat = 2
name = "TestPlayer2"
life = 35
manaAvailable = 4
landCount = 4
creaturesOnField = 2
totalPowerOnBoard = 5
handCount = 3
hand = @()
battlefield = @("Mountain", "Mountain", "Mountain", "Mountain", "Goblin Guide", "Monastery Swiftspear")
graveyard = @()
commandZone = @("Krenko, Mob Boss")
},
[ordered]@{
seat = 3
name = "TestPlayer3"
life = 40
manaAvailable = 0
landCount = 0
creaturesOnField = 0
totalPowerOnBoard = 0
handCount = 7
hand = @()
battlefield = @()
graveyard = @()
commandZone = @("Prossh, Skyraider of Kher")
}
)
} | ConvertTo-Json -Depth 10
$resp = Invoke-RestMethod `
-Uri "$BaseUrl/api/policy/decide" `
-Method Post `
-Body $body `
-ContentType "application/json" `
-TimeoutSec 30
if ($Verbose) {
Write-Host ""
Write-Host " Full /decide response:" -ForegroundColor White
$resp | ConvertTo-Json -Depth 6 | Write-Host
}
$ok = $true
if ([string]::IsNullOrEmpty($resp.action)) {
Write-Fail "response.action is empty"
$ok = $false
}
if ($null -eq $resp.confidence) {
Write-Fail "response.confidence is missing"
$ok = $false
}
if ($resp.PSObject.Properties["error"] -and -not [string]::IsNullOrEmpty($resp.error)) {
Write-Fail "Server returned error: $($resp.error)"
$ok = $false
}
if ($ok) {
$confPct = [math]::Round($resp.confidence * 100, 1)
Write-Pass "Decision received -> action='$($resp.action)' conf=$($confPct)% latency=$($resp.inference_ms)ms src=$($resp.vector_source)"
if ($resp.probabilities) {
$top3 = $resp.probabilities.PSObject.Properties |
Sort-Object { $_.Value } -Descending |
Select-Object -First 3
Write-Info "Top-3 action probabilities:"
foreach ($p in $top3) {
$pct = [math]::Round($p.Value * 100, 1)
Write-Info (" " + $p.Name.PadRight(22) + "$pct%")
}
}
} else {
$script:allPassed = $false
}
}
# ---- Step 4: log line guidance ----------------------------------------------
Invoke-Step "Step 4 -- Confirm [routes.policy.decide] log line in server console" {
Write-Info "After Step 3 you should see in the uvicorn window:"
Write-Info " [decide] turn=3 phase=main_1 -> cast_ramp (conf=0.810) | top5=[...] | src=encoder"
Write-Info ""
Write-Info "If that line is MISSING:"
Write-Info " 1. Confirm uvicorn started with --log-level info (the default)"
Write-Info " 2. Confirm lab_api.py calls register_policy_routes(app, policy_svc)"
Write-Info " 3. Confirm routes/policy.py is included via routes/__init__.py"
Write-Info " 4. Logger name is [routes.policy.decide] -- check no filter silences it"
Write-Pass "Guidance printed"
}
# ---- Step 5: why Forge ignores the policy server ----------------------------
Invoke-Step "Step 5 -- Forge IPC status (informational)" {
Write-Warn "Forge does NOT call /api/policy/decide on its own."
Write-Warn "routes/game.py POST /api/game/start has a TODO: wire Forge engine launch."
Write-Warn ""
Write-Warn "Until wired, /decide is only hit by:"
Write-Warn " - This script"
Write-Warn " - overnight-run.py (batch sim path)"
Write-Warn " - Manual Invoke-RestMethod / curl calls"
Write-Warn ""
Write-Warn "Forge launches its built-in AI and plays lands because it has"
Write-Warn "no HTTP client pointed at localhost:8080."
Write-Warn ""
Write-Warn "Next step: wire GameSession inside POST /api/game/start,"
Write-Warn "or add a PolicyClient hook in Forge AiController.java."
Write-Pass "Status explained"
}
# ---- Summary ----------------------------------------------------------------
Write-Host ""
if ($allPassed) {
Write-Host "==========================================" -ForegroundColor Green
Write-Host " ALL STEPS PASSED -- policy server live" -ForegroundColor Green
Write-Host "==========================================" -ForegroundColor Green
} else {
Write-Host "==========================================" -ForegroundColor Red
Write-Host " ONE OR MORE STEPS FAILED -- see above" -ForegroundColor Red
Write-Host "==========================================" -ForegroundColor Red
exit 1
}
+71 -219
View File
@@ -248,9 +248,6 @@ function createInitialState(playerCount, playerNames, startingLife) {
startingLife,
poison: 0,
energy: 0,
experience: 0,
rad: 0,
emblems: [],
eliminated: false,
commanderDamage: {}, // keyed by opponent player id
zones: {
@@ -5144,6 +5141,25 @@ function createPlayerPanel(player, isActive) {
<button class="life-btn" onclick="adjustLife(${player.id}, 1)" oncontextmenu="event.preventDefault();adjustLife(${player.id}, 5)" title="Left: +1 | Right: +5">+</button>
</div>
<div class="mana-pool-section">
<div class="mana-pool-label">
<span>Mana Pool</span>
<span class="mana-total-badge" id="mana-total-${player.id}">0</span>
<button class="mana-pool-clear-btn" onclick="clearManaPool(${player.id})" title="Empty mana pool">Clear</button>
</div>
<div class="mana-pool-display" id="mana-pool-${player.id}">
<span class="mana-empty">Empty</span>
</div>
<div class="mana-pool-add-row">
<button class="mana-add-btn mana-add-w" onclick="addMana(${player.id},'W',1)" title="Add White">W</button>
<button class="mana-add-btn mana-add-u" onclick="addMana(${player.id},'U',1)" title="Add Blue">U</button>
<button class="mana-add-btn mana-add-b" onclick="addMana(${player.id},'B',1)" title="Add Black">B</button>
<button class="mana-add-btn mana-add-r" onclick="addMana(${player.id},'R',1)" title="Add Red">R</button>
<button class="mana-add-btn mana-add-g" onclick="addMana(${player.id},'G',1)" title="Add Green">G</button>
<button class="mana-add-btn mana-add-c" onclick="addMana(${player.id},'C',1)" title="Add Colorless">C</button>
</div>
</div>
<div class="cmd-damage-section">
<div class="cmd-damage-label">
<span>CMD Damage</span>
@@ -5290,8 +5306,6 @@ function setLife(playerId, newLife) {
eliminatePlayer(playerId, 'life total reached 0');
}
checkStateBasedActions();
// Sync enhanced player panels
if (typeof renderEnhancedPanels === 'function') renderEnhancedPanels();
}
// ============================================================
@@ -5326,8 +5340,6 @@ function adjustCommanderDamage(targetPlayerId, sourcePlayerId, amount) {
panelContainer.replaceWith(newPanel);
}
checkStateBasedActions();
// Sync enhanced player panels
if (typeof renderEnhancedPanels === 'function') renderEnhancedPanels();
}
// ============================================================
@@ -5360,8 +5372,6 @@ function adjustPoison(playerId, amount) {
panelContainer.replaceWith(newPanel);
}
if (gameState.rulesEngine && gameState.rulesEngine.sbaChecks) checkStateBasedActions();
// Sync enhanced player panels
if (typeof renderEnhancedPanels === 'function') renderEnhancedPanels();
}
// ============================================================
@@ -10877,20 +10887,16 @@ function parseDeckList(text) {
let line = raw.trim();
if (!line) continue;
// Section headers — supports "// Commander", "Commander:", "[Commander]", "[Main]", "[metadata]"
if (/^\/\/\s*/i.test(line) || /^\[?(COMMANDER|COMPANION|SIDEBOARD|MAYBEBOARD|MAINBOARD|MAIN|DECK|LAND|METADATA)\]?[:\s]*$/i.test(line)) {
const cleaned = line.replace(/^\/\/\s*/, '').replace(/[\[\]:]/g, '').trim().toLowerCase();
// Section headers
if (/^\/\/\s*/i.test(line) || /^(COMMANDER|COMPANION|SIDEBOARD|MAYBEBOARD|MAINBOARD|DECK|LAND)[:\s]*$/i.test(line)) {
const cleaned = line.replace(/^\/\/\s*/, '').replace(/:$/, '').trim().toLowerCase();
if (/commander/i.test(cleaned)) currentSection = 'commander';
else if (/companion/i.test(cleaned)) currentSection = 'companion';
else if (/sideboard/i.test(cleaned)) currentSection = 'sideboard';
else if (/metadata/i.test(cleaned)) currentSection = 'metadata';
else currentSection = 'mainboard';
continue;
}
// Skip metadata lines like "Name=Elven Empire"
if (currentSection === 'metadata') continue;
// Skip comment lines
if (/^#/.test(line) || /^\*/.test(line)) continue;
@@ -12301,12 +12307,6 @@ function toggleManaAutoClear() {
}
function renderManaPool() {
// Mana pool display removed — internal tracking only.
// No visual update needed.
}
// Legacy renderManaPool body preserved for reference (removed from UI)
function _renderManaPoolLegacy() {
if (!gameState) return;
const pid = getSelectedManaPlayerId();
const player = gameState.players[pid];
@@ -12348,7 +12348,12 @@ function populateManaPlayerSelect() {
}
function showManaPool() {
// Mana pool display removed.
const widget = document.getElementById('mana-pool-widget');
if (widget) {
widget.classList.add('visible');
populateManaPlayerSelect();
renderManaPool();
}
}
function toggleManaPoolCollapse() {
@@ -12361,7 +12366,42 @@ function toggleManaPoolCollapse() {
}
function setupManaPoolDrag() {
// Mana pool display removed — no drag setup needed.
const handle = document.getElementById('mana-pool-drag-handle');
const widget = document.getElementById('mana-pool-widget');
if (!handle || !widget) return;
let isDragging = false;
let startX, startY, startLeft, startTop;
handle.addEventListener('mousedown', e => {
// Don't drag when clicking buttons or select
if (e.target.tagName === 'BUTTON' || e.target.tagName === 'SELECT' || e.target.tagName === 'OPTION') return;
isDragging = true;
const rect = widget.getBoundingClientRect();
startX = e.clientX;
startY = e.clientY;
startLeft = rect.left;
startTop = rect.top;
widget.style.transition = 'none';
e.preventDefault();
});
document.addEventListener('mousemove', e => {
if (!isDragging) return;
const dx = e.clientX - startX;
const dy = e.clientY - startY;
widget.style.left = (startLeft + dx) + 'px';
widget.style.top = (startTop + dy) + 'px';
widget.style.right = 'auto';
widget.style.bottom = 'auto';
});
document.addEventListener('mouseup', () => {
if (isDragging) {
isDragging = false;
widget.style.transition = '';
}
});
}
// ============================================================
@@ -12723,31 +12763,7 @@ async function loadPreconForPlayer(playerIdx, preconId) {
var player = gameState.players[playerIdx];
if (!player) return;
// Try to get decklist text: embedded first, then fetch .dck from server
var decklistText = precon.decklist || '';
if (!decklistText && precon.fileName) {
// 1. Try the API endpoint (returns JSON with decklist field)
try {
var apiResp = await fetch('/api/lab/precons/deck?fileName=' + encodeURIComponent(precon.fileName));
if (apiResp.ok) {
var deckData = await apiResp.json();
if (deckData && deckData.decklist) decklistText = deckData.decklist;
}
} catch (e) {
console.warn('[loadPreconForPlayer] API deck fetch failed:', e);
}
// 2. Fallback: fetch .dck file directly from static mount
if (!decklistText) {
try {
var staticResp = await fetch('/precon-decks/' + encodeURIComponent(precon.fileName));
if (staticResp.ok) decklistText = await staticResp.text();
} catch (e2) {
console.warn('[loadPreconForPlayer] Static .dck fetch failed:', precon.fileName);
}
}
}
var parsedCards = parseDeckList(decklistText);
var parsedCards = parseDeckList(precon.decklist);
if (!parsedCards.length) return;
var allCardNames = [];
@@ -12961,20 +12977,6 @@ function startGame() {
});
gameState.aiDifficulty = setupAiDifficulty;
// ========================================
// Commander-AI-Lab: Initialize backend session
// ========================================
if (typeof AIBridge !== 'undefined' && AIBridge.connector.connected) {
AIBridge.gameState.initSession(gameState).then(function(session) {
if (session) {
addLogEntry('\u{1F9E0} Connected to Commander-AI-Lab (session: ' +
session.game_id.substring(0, 8) + '...)');
}
}).catch(function(err) {
console.warn('[startGame] AI Bridge session init failed:', err);
});
}
// Forge Engine: If enabled, start a Forge game session
if (typeof ForgeBridge !== 'undefined' && ForgeBridge.enabled && ForgeBridge.connected) {
gameState.forgeEnabled = true;
@@ -13012,7 +13014,7 @@ function startGame() {
if (zp) zp.classList.remove('hidden');
initGameBoard();
// showManaPool() removed — mana pool display removed
showManaPool();
// Set commanderCardName for each player from their command zone
gameState.players.forEach(function(p) {
if (p.zones.command && p.zones.command.length > 0) {
@@ -16699,36 +16701,9 @@ function runAiTurn() {
if (!player || !player.isAI) return;
// ========================================
// PRIORITY 1: Commander-AI-Lab ML Pipeline
// FORGE ENGINE HYBRID: If Forge is connected & enabled, delegate AI turn
// ========================================
if (typeof AIBridge !== 'undefined' &&
AIBridge.connector.connected &&
AIBridge.connector.modelLoaded) {
aiTurnActive = true;
player.aiLandPlayedThisTurn = false;
addLogEntry('\u{1F9E0} <strong>' + player.name + '</strong> is thinking... [ML Policy]');
aiAddThought(playerIdx, 'ML pipeline mode \u2014 consulting neural network...');
_runMlAiTurn(playerIdx).then(function(success) {
if (!success) {
addLogEntry('\u{1F916} [ML] Falling back to local AI for ' + player.name);
aiTurnActive = false;
_runLocalAiTurn();
}
}).catch(function(err) {
console.error('[runAiTurn] ML pipeline error:', err);
aiTurnActive = false;
_runLocalAiTurn();
});
return;
}
// ========================================
// PRIORITY 2: Forge Engine Hybrid
// ========================================
if (typeof ForgeBridge !== 'undefined' && ForgeBridge.enabled &&
ForgeBridge.connected && ForgeBridge.gameActive) {
if (typeof ForgeBridge !== 'undefined' && ForgeBridge.enabled && ForgeBridge.connected && ForgeBridge.gameActive) {
aiTurnActive = true;
player.aiLandPlayedThisTurn = false;
addLogEntry('\u{1F916} <strong>' + player.name + '</strong> is thinking... [Forge AI]');
@@ -16736,12 +16711,14 @@ function runAiTurn() {
forgeRunAiTurn(playerIdx, function(success) {
if (success) {
// Forge handled the turn successfully
addLogEntry('\u{1F916} <strong>' + player.name + '</strong> passes the turn [Forge AI]');
aiTurnActive = false;
renderPlayerPanels();
renderHandArea();
nextTurn();
} else {
// Forge failed — fall back to local AI
addLogEntry('\u{1F916} [Forge] Falling back to local AI for ' + player.name);
aiTurnActive = false;
_runLocalAiTurn();
@@ -16751,136 +16728,11 @@ function runAiTurn() {
}
// ========================================
// PRIORITY 3: Local Heuristic AI
// LOCAL AI: Standard heuristic-based AI turn
// ========================================
_runLocalAiTurn();
}
/**
* Run an AI turn using the Commander-AI-Lab ML policy pipeline.
* Makes multiple decision requests per turn (one per phase).
* Returns true if the ML pipeline completed the turn successfully.
*/
async function _runMlAiTurn(playerIdx) {
if (!gameState) return false;
var player = gameState.players[playerIdx];
if (!player || !player.isAI) return false;
aiTurnActive = true;
player.aiLandPlayedThisTurn = false;
var difficulty = gameState.aiDifficulty || 'easy';
var turnDelay = gameState.aiSettings?.turnDelay || 800;
try {
// ── PHASE 1: Play a land (local, immediate) ──────────
var landInHand = player.zones.hand.findIndex(function(c) {
return typeof aiIsLand === 'function' && aiIsLand(c);
});
if (landInHand !== -1) {
var landCard = player.zones.hand[landInHand];
if (landCard && !landCard.imageUrl && typeof generateAiCardSVG === 'function') {
landCard.imageUrl = generateAiCardSVG(landCard);
}
playCardFromHand(playerIdx, landInHand);
player.aiLandPlayedThisTurn = true;
addLogEntry('\u{1F9E0} <strong>' + player.name + '</strong> played a land [ML]');
await _mlDelay(turnDelay * 0.5);
}
// ── PHASE 2: Main Phase 1 decisions ──────────────────
var maxActions = difficulty === 'easy' ? 1 : difficulty === 'normal' ? 3 : 5;
var actionsPlayed = 0;
for (var i = 0; i < maxActions; i++) {
var decision = await AIBridge.gameState.requestAiDecision(gameState, playerIdx);
if (!decision) break;
aiAddThought(playerIdx,
'ML decision: ' + decision.action +
' (' + Math.round(decision.confidence * 100) + '% conf, ' +
decision.inference_ms.toFixed(1) + 'ms)');
// Display probability distribution
if (decision.probabilities) {
var topActions = Object.entries(decision.probabilities)
.sort(function(a, b) { return b[1] - a[1]; })
.slice(0, 3)
.map(function(e) { return e[0] + ':' + Math.round(e[1] * 100) + '%'; })
.join(', ');
aiAddThought(playerIdx, 'Top actions: ' + topActions);
}
// Skip if action is pass/hold
if (decision.action === 'pass' || decision.action === 'hold_mana') {
aiAddThought(playerIdx, 'ML chose to ' +
(decision.action === 'pass' ? 'pass' : 'hold mana open'));
break;
}
// Skip combat action in main phase — save for combat
if (decision.action === 'attack_opponent') {
aiAddThought(playerIdx, 'ML wants to attack \u2014 saving for combat phase');
break;
}
var executed = AIBridge.MacroActionMapper.execute(
decision.action, playerIdx, gameState, decision
);
if (executed) {
actionsPlayed++;
// Push state update to backend
AIBridge.gameState.pushState(gameState);
AIBridge.gameState.pushDecision(decision);
await _mlDelay(turnDelay);
} else {
// Action couldn't execute — likely no valid targets
aiAddThought(playerIdx,
'Could not execute ' + decision.action + ' \u2014 moving on');
break;
}
}
// ── PHASE 3: Combat ──────────────────────────────────
var combatDecision = await AIBridge.gameState.requestAiDecision(gameState, playerIdx);
if (combatDecision && combatDecision.action === 'attack_opponent') {
AIBridge.MacroActionMapper.execute(
'attack_opponent', playerIdx, gameState, combatDecision
);
await _mlDelay(turnDelay);
}
// ── PHASE 4: Post-combat main phase 2 ────────────────
var postDecision = await AIBridge.gameState.requestAiDecision(gameState, playerIdx);
if (postDecision &&
postDecision.action !== 'pass' &&
postDecision.action !== 'hold_mana' &&
postDecision.action !== 'attack_opponent') {
AIBridge.MacroActionMapper.execute(
postDecision.action, playerIdx, gameState, postDecision
);
await _mlDelay(turnDelay * 0.5);
}
// ── PHASE 5: End turn ────────────────────────────────
addLogEntry('\u{1F9E0} <strong>' + player.name + '</strong> ends their turn [ML]');
aiTurnActive = false;
renderPlayerPanels();
renderHandArea();
nextTurn();
return true;
} catch (err) {
console.error('[_runMlAiTurn] Error:', err);
aiTurnActive = false;
return false;
}
}
function _mlDelay(ms) {
return new Promise(function(resolve) { setTimeout(resolve, ms); });
}
function _runLocalAiTurn() {
if (!gameState) return;
var playerIdx = gameState.currentPlayerIndex;
+7 -24
View File
@@ -299,6 +299,12 @@
<g id="combat-arrows-svg"></g>
</svg>
<!-- MANA POOL DISPLAY (floating, bottom center) -->
<div id="mana-pool-display" style="display:none;">
<span class="mana-pool-label">MANA:</span>
<span class="mana-empty">Empty</span>
</div>
<!-- FLOATING LOG -->
<div id="floating-log" class="floating-log"></div>
@@ -489,6 +495,7 @@
<button class="btn btn-primary" onclick="openDiceModal()">&#x1F3B2; Dice</button>
<button class="btn btn-gold" onclick="openCmdDmgMatrix()">CMD Damage Matrix</button>
<button class="btn btn-cancel" onclick="checkStateBasedActions()">Check SBA</button>
<button class="btn btn-cancel" onclick="clearAllManaPools()">Clear All Mana</button>
<button class="btn btn-cancel" onclick="autoArrangeBattlefield()">Auto-Arrange</button>
</div>
</div>
@@ -524,19 +531,9 @@
<!-- ====================================================
SCRIPTS
Load order matters:
1. precons.js — static PRECON_DATA fallback
2. engine.js — game state & core logic
3. ai-bridge.js — backend connector & DeckSourceClient
4. precon-loader.js — startGameWithDecks() + loadPreconDeckFromDck()
5. player-panels.js — player panel rendering
6. ui.js — setup screen, deck picker, UI wiring
==================================================== -->
<script src="precons.js?v=20260403_0300"></script>
<script src="engine.js?v=20260403_0300"></script>
<script src="ai-bridge.js?v=20260403_0300"></script>
<script src="precon-loader.js?v=20260403_0300"></script>
<script src="player-panels.js?v=20260403_0300"></script>
<script src="ui.js?v=20260403_0300"></script>
<script>
@@ -630,20 +627,6 @@ document.addEventListener('DOMContentLoaded', function() {
// Life counter right-click on quadrant buttons too
// (already handled via inline onclick in HTML)
// Auto-detect Commander-AI-Lab backend on page load
if (typeof AIBridge !== 'undefined') {
AIBridge.init().then(function(status) {
var indicator = document.getElementById('backend-status-indicator');
if (indicator) {
indicator.textContent = status.connected
? (status.modelLoaded ? '\u{1F9E0} ML Backend Connected' : '\u26a1 Backend Connected (no ML model)')
: '\u{1F4E1} Local Mode (no backend)';
indicator.className = 'backend-status ' +
(status.connected ? (status.modelLoaded ? 'connected-ml' : 'connected') : 'disconnected');
}
});
}
});
</script>
+14 -40
View File
@@ -50,9 +50,6 @@ _DEFAULT_ORIGINS = "http://localhost:5173,http://localhost:3000,http://localhost
_allowed = os.environ.get("ALLOWED_ORIGINS", _DEFAULT_ORIGINS)
allowed_origins = [o.strip() for o in _allowed.split(",") if o.strip()]
# Module-level handle so lifespan can call .load() after routes are registered.
_POLICY_SVC = None
# ── Lifespan (replaces deprecated @app.on_event) ────────────────────────────────────────────────────────
@asynccontextmanager
@@ -80,6 +77,7 @@ async def _lifespan(application: FastAPI):
# RAG Phase 3: background staleness monitor (rebuilds if >14 days old)
async def _rag_staleness_monitor():
"""Periodically check if the RAG index needs rebuilding."""
import time as _time
while True:
await asyncio.sleep(6 * 3600) # check every 6 hours
try:
@@ -94,17 +92,20 @@ async def _lifespan(application: FastAPI):
log.warning("RAG staleness monitor failed: %s", exc)
asyncio.ensure_future(_rag_staleness_monitor())
# Policy model load — routes were already registered at module scope (before
# any app.mount() calls) so /api/policy/* is reachable regardless of the
# StaticFiles root mount. Only the heavyweight model load happens here.
# Policy routes: register if ML policy model is available
try:
if _POLICY_SVC is not None:
if _POLICY_SVC.load():
log.info("Policy model loaded successfully")
else:
log.warning("Policy model not loaded — /api/policy/health will report degraded")
from ml.serving.policy_server import PolicyInferenceService
from routes.policy import register_policy_routes
_policy_svc = PolicyInferenceService()
if _policy_svc.load():
register_policy_routes(application, _policy_svc)
log.info("Policy routes registered (/api/policy/*)")
else:
log.warning("Policy model not loaded — /api/policy/* routes inactive")
except ImportError:
log.info("Policy service not available (ml.serving not installed)")
except Exception as e:
log.warning("Policy model load failed (non-fatal): %s", e)
log.warning("Policy route registration failed (non-fatal): %s", e)
yield # ← server is running
@@ -137,23 +138,6 @@ app.include_router(ws_game_router)
app.include_router(ml_router)
app.include_router(game_router) # live game session routes
# ── Policy routes — MUST be registered here, before any app.mount() calls ────────────────────
# StaticFiles mounted at "/" acts as a sub-application and returns its own 404 for
# paths it doesn't serve, rather than falling through to later-registered routes.
# Any include_router() called after app.mount("/", ...) will be unreachable.
# Registering here (module scope) guarantees the /api/policy/* endpoints exist in
# the route list before the root static mount is added below.
try:
from ml.serving.policy_server import PolicyInferenceService
from routes.policy import register_policy_routes
_POLICY_SVC = PolicyInferenceService()
register_policy_routes(app, _POLICY_SVC)
log.info("Policy routes registered (/api/policy/*)")
except ImportError:
log.info("Policy service not available (ml.serving not installed)")
except Exception as e:
log.warning("Policy route registration failed (non-fatal): %s", e)
# ── API endpoints ─────────────────────────────────────────────────────────────────────────────
# NOTE: all @app.get routes MUST be registered before app.mount() calls.
@@ -165,21 +149,11 @@ async def health_check():
"""Health check endpoint for load balancers and Unity client polling."""
return {"status": "ok"}
# ── Static UI (MUST come after all @app.get / include_router calls) ──────────────────────────
# ── Static UI (MUST come after all @app.get routes) ──────────────────────────────────────────
from pathlib import Path as _Path
_legacy_ui_dir = _Path(__file__).parent / "ui"
_lan_client_dir = _Path(__file__).parent / "lan-client"
_precon_decks_dir = _Path(__file__).parent / "precon-decks"
_spa_dir = _Path(__file__).parent / "frontend" / "commander-ai-lab-ui" / "dist"
# Mount LAN client at /lan (served before the root catch-all)
if _lan_client_dir.exists():
app.mount("/lan", StaticFiles(directory=str(_lan_client_dir), html=True), name="lan-client")
# Mount precon-decks/ so .dck files are fetchable at /precon-decks/{file}.dck
if _precon_decks_dir.exists():
app.mount("/precon-decks", StaticFiles(directory=str(_precon_decks_dir)), name="precon-decks")
if _legacy_ui_dir.exists():
app.mount("/", StaticFiles(directory=str(_legacy_ui_dir), html=True), name="ui")
elif _spa_dir.exists():
File diff suppressed because it is too large. Load diff
-270
View File
@@ -1,270 +0,0 @@
// player-panels.js — Enhanced Player Panel Component
// Provides collapsible panels with life, commander damage, counters, and emblems.
'use strict';
/**
* Create an enhanced player panel widget for a quadrant.
* Replaces the basic life counter with a full tracking panel.
*
* @param {object} player - Player object from gameState
* @param {number} quadrant - 1-4 (matches CSS class p1-p4)
* @param {boolean} isActive - Whether this is the active player
*/
function createEnhancedPlayerPanel(player, quadrant, isActive) {
var panel = document.createElement('div');
panel.className = 'enhanced-player-panel' +
(isActive ? ' active-turn' : '') +
(player.eliminated ? ' eliminated' : '');
panel.id = 'enhanced-panel-' + player.id;
panel.setAttribute('data-player-id', player.id);
// Track collapse state
var collapseKey = 'panel-collapsed-' + player.id;
var isCollapsed = localStorage.getItem(collapseKey) === 'true';
// ── Header Row ──────────────────────────────────────────
var headerHtml =
'<div class="epp-header" onclick="togglePlayerPanel(' + player.id + ')">' +
'<span class="epp-collapse-arrow">' + (isCollapsed ? '\u25b8' : '\u25be') + '</span>' +
'<div class="epp-name-dot" style="background:' + player.color + '"></div>' +
'<span class="epp-name">' + player.name + '</span>' +
(player.isAI ? '<span class="epp-ai-badge">AI</span>' : '') +
'<span class="epp-life-badge">' +
'\u2665 ' + player.life +
(player.life < player.startingLife
? ' / ' + player.startingLife
: '') +
'</span>' +
'</div>';
// ── Life Counter Row ────────────────────────────────────
var lifeHtml =
'<div class="epp-life-row">' +
'<button class="epp-life-btn minus" onclick="adjustLife(' + player.id + ',-1)" ' +
'oncontextmenu="event.preventDefault();adjustLife(' + player.id + ',-5)" ' +
'title="Left: -1 | Right: -5">\u2212</button>' +
'<div class="epp-life-value" id="epp-life-' + player.id + '" ' +
'onclick="showSetLifeDialog(' + player.id + ')">' +
player.life +
'</div>' +
'<button class="epp-life-btn plus" onclick="adjustLife(' + player.id + ',1)" ' +
'oncontextmenu="event.preventDefault();adjustLife(' + player.id + ',5)" ' +
'title="Left: +1 | Right: +5">+</button>' +
'</div>';
// ── Commander Damage Section ────────────────────────────
var otherPlayers = gameState.players.filter(function(p) {
return p.id !== player.id && !p.eliminated;
});
var cmdDmgHtml =
'<div class="epp-section">' +
'<div class="epp-section-label">Commander Damage</div>' +
'<div class="epp-cmd-dmg-grid">';
otherPlayers.forEach(function(op) {
var dmg = player.commanderDamage[op.id] || 0;
var pct = Math.round((dmg / 21) * 100);
var dangerClass = dmg >= 18 ? 'critical' : dmg >= 10 ? 'warning' : '';
cmdDmgHtml +=
'<div class="epp-cmd-dmg-item ' + dangerClass + '">' +
'<div class="epp-cmd-dmg-bar" style="width:' + pct + '%"></div>' +
'<div class="epp-cmd-dmg-dot" style="background:' + op.color + '"></div>' +
'<span class="epp-cmd-dmg-name">' + op.name + '</span>' +
'<span class="epp-cmd-dmg-value">' + dmg + '/21</span>' +
'<button class="epp-counter-btn" ' +
'onclick="event.stopPropagation();adjustCommanderDamage(' + player.id + ',' + op.id + ',1)" ' +
'title="Add commander damage">+</button>' +
'<button class="epp-counter-btn" ' +
'onclick="event.stopPropagation();adjustCommanderDamage(' + player.id + ',' + op.id + ',-1)" ' +
'title="Remove commander damage">\u2212</button>' +
'</div>';
});
cmdDmgHtml += '</div></div>';
// ── Counters Section ────────────────────────────────────
var poison = player.poison || 0;
var energy = player.energy || 0;
var experience = player.experience || 0;
var rad = player.rad || 0;
var countersHtml =
'<div class="epp-section">' +
'<div class="epp-section-label">Counters</div>' +
'<div class="epp-counters-grid">' +
_buildCounterWidget('Poison', '\u2620', poison, 10,
'adjustPoison(' + player.id + ',1)',
'adjustPoison(' + player.id + ',-1)',
poison >= 8 ? 'critical' : poison >= 5 ? 'warning' : '') +
_buildCounterWidget('Energy', '\u269b', energy, 0,
'adjustEnergy(' + player.id + ',1)',
'adjustEnergy(' + player.id + ',-1)', '') +
_buildCounterWidget('Experience', '\u2605', experience, 0,
'adjustExperience(' + player.id + ',1)',
'adjustExperience(' + player.id + ',-1)', '') +
_buildCounterWidget('Rad', '\u2622', rad, 0,
'adjustRad(' + player.id + ',1)',
'adjustRad(' + player.id + ',-1)', '') +
'</div>' +
'</div>';
// ── Emblems Section ─────────────────────────────────────
var emblems = player.emblems || [];
var emblemsHtml =
'<div class="epp-section">' +
'<div class="epp-section-label">Emblems</div>' +
'<div class="epp-emblems">';
if (emblems.length === 0) {
emblemsHtml += '<span class="epp-no-emblems">None</span>';
} else {
emblems.forEach(function(emb, idx) {
emblemsHtml +=
'<div class="epp-emblem-chip" title="' + emb.name + '">' +
'<span class="epp-emblem-name">' + emb.name + '</span>' +
'<button class="epp-emblem-remove" ' +
'onclick="event.stopPropagation();removeEmblem(' + player.id + ',' + idx + ')">\u00d7</button>' +
'</div>';
});
}
emblemsHtml +=
'<button class="epp-add-emblem-btn" ' +
'onclick="event.stopPropagation();showAddEmblemDialog(' + player.id + ')" ' +
'title="Add an emblem">+ Emblem</button>' +
'</div>' +
'</div>';
// ── Assemble Panel ──────────────────────────────────────
var bodyHtml =
'<div class="epp-body" id="epp-body-' + player.id + '" ' +
'style="' + (isCollapsed ? 'display:none;' : '') + '">' +
lifeHtml + cmdDmgHtml + countersHtml + emblemsHtml +
'</div>';
panel.innerHTML = headerHtml + bodyHtml;
return panel;
}
function _buildCounterWidget(label, icon, value, threshold, onInc, onDec, dangerClass) {
return '<div class="epp-counter ' + dangerClass + '">' +
'<div class="epp-counter-icon">' + icon + '</div>' +
'<div class="epp-counter-info">' +
'<span class="epp-counter-value">' + value + '</span>' +
'<span class="epp-counter-label">' + label + '</span>' +
'</div>' +
'<div class="epp-counter-btns">' +
'<button class="epp-counter-btn" onclick="event.stopPropagation();' + onInc + '">+</button>' +
'<button class="epp-counter-btn" onclick="event.stopPropagation();' + onDec + '">\u2212</button>' +
'</div>' +
'</div>';
}
function togglePlayerPanel(playerId) {
var body = document.getElementById('epp-body-' + playerId);
var panel = document.getElementById('enhanced-panel-' + playerId);
if (!body || !panel) return;
var isCollapsed = body.style.display === 'none';
body.style.display = isCollapsed ? '' : 'none';
var arrow = panel.querySelector('.epp-collapse-arrow');
if (arrow) arrow.textContent = isCollapsed ? '\u25be' : '\u25b8';
localStorage.setItem('panel-collapsed-' + playerId, !isCollapsed);
}
// Counter adjustment functions
function adjustEnergy(playerId, amount) {
if (!gameState) return;
var player = gameState.players[playerId];
if (!player) return;
player.energy = Math.max(0, (player.energy || 0) + amount);
addLogEntry('<strong>' + player.name + '</strong> energy: ' + player.energy);
renderEnhancedPanels();
}
function adjustExperience(playerId, amount) {
if (!gameState) return;
var player = gameState.players[playerId];
if (!player) return;
player.experience = Math.max(0, (player.experience || 0) + amount);
addLogEntry('<strong>' + player.name + '</strong> experience: ' + player.experience);
renderEnhancedPanels();
}
function adjustRad(playerId, amount) {
if (!gameState) return;
var player = gameState.players[playerId];
if (!player) return;
player.rad = Math.max(0, (player.rad || 0) + amount);
addLogEntry('<strong>' + player.name + '</strong> rad counters: ' + player.rad);
renderEnhancedPanels();
}
function showAddEmblemDialog(playerId) {
var name = prompt('Enter emblem name (e.g., "Sorin, Vengeful Bloodlord"):');
if (!name || !name.trim()) return;
if (!gameState) return;
var player = gameState.players[playerId];
if (!player) return;
if (!player.emblems) player.emblems = [];
player.emblems.push({ name: name.trim() });
addLogEntry('<strong>' + player.name + '</strong> gained emblem: ' + name.trim());
renderEnhancedPanels();
}
function removeEmblem(playerId, idx) {
if (!gameState) return;
var player = gameState.players[playerId];
if (!player || !player.emblems) return;
var removed = player.emblems.splice(idx, 1);
if (removed.length > 0) {
addLogEntry('<strong>' + player.name + '</strong> lost emblem: ' + removed[0].name);
}
renderEnhancedPanels();
}
/**
* Re-render all enhanced player panels in their quadrant positions.
*/
function renderEnhancedPanels() {
if (!gameState) return;
for (var i = 0; i < gameState.players.length; i++) {
var player = gameState.players[i];
var quadrant = i + 1;
var areaEl = document.getElementById('player-area-' + quadrant);
if (!areaEl) continue;
// Find or create the enhanced panel container
var container = areaEl.querySelector('.epp-container');
if (!container) {
container = document.createElement('div');
container.className = 'epp-container';
// Insert before the zone row
var zoneRow = areaEl.querySelector('.zone-row');
if (zoneRow) {
areaEl.insertBefore(container, zoneRow);
} else {
areaEl.appendChild(container);
}
}
var isActive = gameState.currentPlayerIndex === i;
var panel = createEnhancedPlayerPanel(player, quadrant, isActive);
container.innerHTML = '';
container.appendChild(panel);
// Hide the old life counter (we have our own now)
var oldLifeCounter = areaEl.querySelector('.life-counter');
if (oldLifeCounter) oldLifeCounter.style.display = 'none';
// Hide old poison badge (we have counters section)
var oldPoison = areaEl.querySelector('.poison-badge');
if (oldPoison) oldPoison.style.display = 'none';
}
}
-299
View File
@@ -1,299 +0,0 @@
/**
* precon-loader.js
* Handles loading precon .dck files from the backend into the lan-client simulator.
* Depends on: engine.js (gameState, initGame, addLogEntry, renderPlayerPanels)
* ai-bridge.js (AIBridge.deckSource.fetchPreconDeck)
* ui.js (setupDeckChoices, setupPlayerCount, setupStartingLife)
*/
'use strict';
// In-memory Scryfall image cache: cardName -> { imageUrl, typeLine, oracleText, manaCost, power, toughness }
const _scryfallCache = {};
// Scryfall collection endpoint — accepts up to 75 card identifiers per call
const SCRYFALL_COLLECTION_URL = 'https://api.scryfall.com/cards/collection';
// ============================================================
// startGameWithDecks
// Called by ui.js startGame() when players have selected precon decks.
// ============================================================
async function startGameWithDecks() {
const playerNames = [];
for (let i = 0; i < (setupPlayerCount || 4); i++) {
const inp = document.getElementById('player-name-' + i);
playerNames.push(inp && inp.value.trim() ? inp.value.trim() : 'Player ' + (i + 1));
}
initGame(setupPlayerCount || 4, playerNames, setupStartingLife || 40);
const choices = typeof setupDeckChoices !== 'undefined' ? setupDeckChoices : {};
const loadPromises = Object.entries(choices).map(async ([idxStr, choice]) => {
const playerIdx = parseInt(idxStr, 10);
if (choice.type !== 'precon' || !choice.preconId) return;
try {
const fileName = choice.preconId.endsWith('.dck') ? choice.preconId : choice.preconId + '.dck';
const data = await AIBridge.deckSource.fetchPreconDeck(fileName);
if (!data || !data.decklist) {
addLogEntry('\u26A0 Could not load deck for Player ' + (playerIdx + 1) + ' (no decklist returned)');
return;
}
loadPreconDeckFromDck(playerIdx, data.decklist, choice.preconId);
} catch (e) {
console.warn('[precon-loader] Failed to load deck for player', playerIdx, e);
addLogEntry('\u26A0 Deck load failed for Player ' + (playerIdx + 1) + ': ' + e.message);
}
});
await Promise.all(loadPromises);
if (typeof renderPlayerPanels === 'function') renderPlayerPanels();
if (typeof updateActivePlayerHighlight === 'function') updateActivePlayerHighlight();
// Kick off image enrichment for all players in the background (non-blocking)
enrichAllZonesWithScryfall();
}
// ============================================================
// loadPreconDeckFromDck
// Parses a Forge-format .dck file string and populates a player's zones.
// ============================================================
function loadPreconDeckFromDck(playerIdx, dckContent, deckLabel) {
if (!gameState) return;
const player = gameState.players[playerIdx];
if (!player) return;
let commander = '';
let section = '';
const mainCards = [];
for (const rawLine of dckContent.split('\n')) {
const line = rawLine.trim();
if (!line || line.startsWith('//')) continue;
if (line.startsWith('[') && line.endsWith(']')) {
section = line.slice(1, -1);
continue;
}
if (line.includes('=') && !line.match(/^\d/)) continue;
const m = line.match(/^(\d+)\s+(.+?)(?:\|.*)?$/);
if (!m) continue;
const qty = parseInt(m[1], 10);
const name = m[2].trim();
if (section === 'Commander') {
commander = name;
} else if (section === 'Main') {
for (let q = 0; q < qty; q++) mainCards.push(name);
}
}
player.zones.command = [];
player.zones.library = [];
player.zones.hand = [];
player.zones.graveyard = [];
player.zones.exile = [];
if (commander) {
player.zones.command.push({
id: 'cmd-' + playerIdx + '-' + Date.now(),
name: commander,
imageUrl: '',
typeLine: 'Legendary Creature',
oracleText: '',
manaCost: '',
});
player.commanderCardName = commander;
}
for (const cardName of mainCards) {
player.zones.library.push({
id: 'lib-' + playerIdx + '-' + cardName + '-' + Math.random().toString(36).slice(2, 6),
name: cardName,
imageUrl: '',
typeLine: '',
oracleText: '',
manaCost: '',
});
}
// Fisher-Yates shuffle
const lib = player.zones.library;
for (let i = lib.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[lib[i], lib[j]] = [lib[j], lib[i]];
}
// Draw opening hand
for (let d = 0; d < 7 && lib.length > 0; d++) {
player.zones.hand.push(lib.shift());
}
if (typeof updateZoneCountsForPlayer === 'function') updateZoneCountsForPlayer(playerIdx);
if (typeof renderCommanderZone === 'function') renderCommanderZone(playerIdx);
if (typeof renderHandZone === 'function') renderHandZone(playerIdx);
const label = deckLabel ? deckLabel.replace('.dck', '') : 'Unknown Deck';
addLogEntry(
'\uD83C\uDCCF <strong>' + player.name + '</strong> loaded: <em>' + label + '</em>' +
(commander ? ' \u2014 Commander: <strong>' + commander + '</strong>' : '') +
' (' + lib.length + ' in library, 7 in hand)'
);
}
// ============================================================
// SCRYFALL IMAGE ENRICHMENT
// After zones are populated with card names, batch-fetch card
// data from Scryfall and backfill imageUrl on every card object.
// Uses the /cards/collection endpoint (75 cards per request).
// Results are cached in _scryfallCache so re-renders are instant.
// ============================================================
async function enrichAllZonesWithScryfall() {
if (!gameState) return;
// Gather all unique card names across all players and all zones
const nameSet = new Set();
for (const player of gameState.players) {
for (const zone of Object.values(player.zones)) {
for (const card of zone) {
if (card.name && !_scryfallCache[card.name]) nameSet.add(card.name);
}
}
}
if (nameSet.size === 0) return;
const names = Array.from(nameSet);
addLogEntry('\uD83C\uDF0D Fetching card images from Scryfall (' + names.length + ' unique cards)...');
// Split into batches of 75 (Scryfall max)
const BATCH = 75;
for (let i = 0; i < names.length; i += BATCH) {
const batch = names.slice(i, i + BATCH);
try {
await _fetchScryfallBatch(batch);
} catch (e) {
console.warn('[precon-loader] Scryfall batch failed', e);
}
// Polite delay between batches to respect Scryfall rate limit (50-100ms)
if (i + BATCH < names.length) await _sleep(100);
}
// Apply cached data to every card object in every zone
_applyScryfallDataToAllCards();
addLogEntry('\u2705 Card images loaded.');
}
async function _fetchScryfallBatch(names) {
const identifiers = names.map(name => ({ name }));
const resp = await fetch(SCRYFALL_COLLECTION_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ identifiers }),
});
if (!resp.ok) throw new Error('Scryfall HTTP ' + resp.status);
const json = await resp.json();
for (const card of (json.data || [])) {
const name = card.name;
// Pick the best image: normal > large > small, handle double-faced
let imageUrl = '';
if (card.image_uris) {
imageUrl = card.image_uris.normal || card.image_uris.large || card.image_uris.small || '';
} else if (card.card_faces && card.card_faces[0] && card.card_faces[0].image_uris) {
imageUrl = card.card_faces[0].image_uris.normal || card.card_faces[0].image_uris.large || '';
}
_scryfallCache[name] = {
imageUrl,
typeLine: card.type_line || '',
oracleText: card.oracle_text || (card.card_faces && card.card_faces[0] ? card.card_faces[0].oracle_text : '') || '',
manaCost: card.mana_cost || (card.card_faces && card.card_faces[0] ? card.card_faces[0].mana_cost : '') || '',
power: card.power || '',
toughness: card.toughness || '',
};
}
// Mark not-found cards so we don't re-fetch them on next enrichment
for (const name of names) {
if (!_scryfallCache[name]) _scryfallCache[name] = { imageUrl: '', typeLine: '', oracleText: '', manaCost: '', power: '', toughness: '' };
}
}
function _applyScryfallDataToAllCards() {
if (!gameState) return;
for (const player of gameState.players) {
for (const zone of Object.values(player.zones)) {
for (const card of zone) {
const data = _scryfallCache[card.name];
if (data) {
card.imageUrl = data.imageUrl || card.imageUrl;
card.typeLine = data.typeLine || card.typeLine;
card.oracleText = data.oracleText || card.oracleText;
card.manaCost = data.manaCost || card.manaCost;
if (data.power) card.power = data.power;
if (data.toughness) card.toughness = data.toughness;
}
}
}
// Also enrich battlefield cards owned by this player
if (gameState.battlefieldCards) {
for (const card of gameState.battlefieldCards) {
if (card.ownerIndex !== player.id) continue;
const data = _scryfallCache[card.name];
if (data && !card.imageUrl) {
card.imageUrl = data.imageUrl || '';
card.typeLine = data.typeLine || card.typeLine;
card.oracleText = data.oracleText || card.oracleText;
card.manaCost = data.manaCost || card.manaCost;
}
}
}
}
// Trigger UI refresh so images appear without a full reload
if (typeof renderPlayerPanels === 'function') renderPlayerPanels();
if (typeof renderCommanderZone === 'function') {
for (let i = 0; i < gameState.players.length; i++) renderCommanderZone(i);
}
if (typeof renderHandZone === 'function') {
for (let i = 0; i < gameState.players.length; i++) renderHandZone(i);
}
if (typeof updateZoneCounts === 'function') updateZoneCounts();
}
/**
* Enrich a single card object on-demand (useful for cards drawn or played after initial load).
* Returns a Promise that resolves when the card's imageUrl is set.
*/
async function enrichCardWithScryfall(card) {
if (!card || !card.name) return;
if (card.imageUrl) return; // already has image
const cached = _scryfallCache[card.name];
if (cached) {
card.imageUrl = cached.imageUrl || '';
card.typeLine = cached.typeLine || card.typeLine;
card.oracleText = cached.oracleText || card.oracleText;
card.manaCost = cached.manaCost || card.manaCost;
return;
}
await _fetchScryfallBatch([card.name]);
const data = _scryfallCache[card.name];
if (data) {
card.imageUrl = data.imageUrl || '';
card.typeLine = data.typeLine || card.typeLine;
card.oracleText = data.oracleText || card.oracleText;
card.manaCost = data.manaCost || card.manaCost;
}
}
function _sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
-167
View File
@@ -1,167 +0,0 @@
// Auto-generated from precon-decks/precon-index.json
// Run: node scripts/generate-precons-js.js to regenerate
var PRECON_DATA = [
{"id":"Counterpunch","name":"Counterpunch","commander":"Ghave, Guru of Spores","set":"Commander 2011","fileName":"Counterpunch.dck","colors":[],"year":2011},
{"id":"Devour_for_Power_CMD","name":"Devour for Power","commander":"The Mimeoplasm","set":"Commander 2011","fileName":"Devour_for_Power_CMD.dck","colors":[],"year":2011},
{"id":"Heavenly_Inferno_CMD","name":"Heavenly Inferno","commander":"Kaalia of the Vast","set":"Commander 2011","fileName":"Heavenly_Inferno_CMD.dck","colors":[],"year":2011},
{"id":"Mirror_Mastery","name":"Mirror Mastery","commander":"Riku of Two Reflections","set":"Commander 2011","fileName":"Mirror_Mastery.dck","colors":[],"year":2011},
{"id":"Political_Puppets","name":"Political Puppets","commander":"Zedruu the Greathearted","set":"Commander 2011","fileName":"Political_Puppets.dck","colors":[],"year":2011},
{"id":"Eternal_Bargain","name":"Eternal Bargain","commander":"Oloro, Ageless Ascetic","set":"Commander 2013","fileName":"Eternal_Bargain.dck","colors":[],"year":2013},
{"id":"Evasive_Maneuvers_C13","name":"Evasive Maneuvers","commander":"Derevi, Empyrial Tactician","set":"Commander 2013","fileName":"Evasive_Maneuvers_C13.dck","colors":[],"year":2013},
{"id":"Mind_Seize","name":"Mind Seize","commander":"Jeleva, Nephalia's Scourge","set":"Commander 2013","fileName":"Mind_Seize.dck","colors":[],"year":2013},
{"id":"Nature_of_the_Beast","name":"Nature of the Beast","commander":"Marath, Will of the Wild","set":"Commander 2013","fileName":"Nature_of_the_Beast.dck","colors":[],"year":2013},
{"id":"Power_Hungry","name":"Power Hungry","commander":"Prossh, Skyraider of Kher","set":"Commander 2013","fileName":"Power_Hungry.dck","colors":[],"year":2013},
{"id":"Built_From_Scratch_C14","name":"Built From Scratch","commander":"Daretti, Scrap Savant","set":"Commander 2014","fileName":"Built_From_Scratch_C14.dck","colors":[],"year":2014},
{"id":"Forged_In_Stone","name":"Forged In Stone","commander":"Nahiri, the Lithomancer","set":"Commander 2014","fileName":"Forged_In_Stone.dck","colors":[],"year":2014},
{"id":"Guided_By_Nature","name":"Guided By Nature","commander":"Freyalise, Llanowar's Fury","set":"Commander 2014","fileName":"Guided_By_Nature.dck","colors":[],"year":2014},
{"id":"Peer_Through_Time","name":"Peer Through Time","commander":"Teferi, Temporal Archmage","set":"Commander 2014","fileName":"Peer_Through_Time.dck","colors":[],"year":2014},
{"id":"Sworn_To_Darkness","name":"Sworn To Darkness","commander":"Ob Nixilis of the Black Oath","set":"Commander 2014","fileName":"Sworn_To_Darkness.dck","colors":[],"year":2014},
{"id":"Call_the_Spirits","name":"Call the Spirits","commander":"Daxos the Returned","set":"Commander 2015","fileName":"Call_the_Spirits.dck","colors":[],"year":2015},
{"id":"Plunder_the_Graves_C15","name":"Plunder the Graves","commander":"Meren of Clan Nel Toth","set":"Commander 2015","fileName":"Plunder_the_Graves_C15.dck","colors":[],"year":2015},
{"id":"Seize_Control","name":"Seize Control","commander":"Mizzix of the Izmagnus","set":"Commander 2015","fileName":"Seize_Control.dck","colors":[],"year":2015},
{"id":"Swell_the_Host","name":"Swell the Host","commander":"Ezuri, Claw of Progress","set":"Commander 2015","fileName":"Swell_the_Host.dck","colors":[],"year":2015},
{"id":"Wade_into_Battle_C15","name":"Wade into Battle","commander":"Kalemne, Disciple of Iroas","set":"Commander 2015","fileName":"Wade_into_Battle_C15.dck","colors":[],"year":2015},
{"id":"Breed_Lethality_C16","name":"Breed Lethality","commander":"Atraxa, Praetors' Voice","set":"Commander 2016","fileName":"Breed_Lethality_C16.dck","colors":[],"year":2016},
{"id":"Entropic_Uprising","name":"Entropic Uprising","commander":"Yidris, Maelstrom Wielder","set":"Commander 2016","fileName":"Entropic_Uprising.dck","colors":[],"year":2016},
{"id":"Invent_Superiority","name":"Invent Superiority","commander":"Breya, Etherium Shaper","set":"Commander 2016","fileName":"Invent_Superiority.dck","colors":[],"year":2016},
{"id":"Open_Hostility","name":"Open Hostility","commander":"Saskia the Unyielding","set":"Commander 2016","fileName":"Open_Hostility.dck","colors":[],"year":2016},
{"id":"Stalwart_Unity","name":"Stalwart Unity","commander":"Kynaios and Tiro of Meletis","set":"Commander 2016","fileName":"Stalwart_Unity.dck","colors":[],"year":2016},
{"id":"Evasive_Maneuvers_CMA","name":"Evasive Maneuvers","commander":"Derevi, Empyrial Tactician","set":"Commander Anthology","fileName":"Evasive_Maneuvers_CMA.dck","colors":[],"year":2017},
{"id":"Guided_by_Nature","name":"Guided by Nature","commander":"Freyalise, Llanowar's Fury","set":"Commander Anthology","fileName":"Guided_by_Nature.dck","colors":[],"year":2017},
{"id":"Heavenly_Inferno_CMA","name":"Heavenly Inferno","commander":"Kaalia of the Vast","set":"Commander Anthology","fileName":"Heavenly_Inferno_CMA.dck","colors":[],"year":2017},
{"id":"Plunder_the_Graves_CMA","name":"Plunder the Graves","commander":"Meren of Clan Nel Toth","set":"Commander Anthology","fileName":"Plunder_the_Graves_CMA.dck","colors":[],"year":2017},
{"id":"Arcane_Wizardry","name":"Arcane Wizardry","commander":"Inalla, Archmage Ritualist","set":"Commander 2017","fileName":"Arcane_Wizardry.dck","colors":[],"year":2017},
{"id":"Draconic_Domination","name":"Draconic Domination","commander":"The Ur-Dragon","set":"Commander 2017","fileName":"Draconic_Domination.dck","colors":[],"year":2017},
{"id":"Feline_Ferocity","name":"Feline Ferocity","commander":"Arahbo, Roar of the World","set":"Commander 2017","fileName":"Feline_Ferocity.dck","colors":[],"year":2017},
{"id":"Vampiric_Bloodlust","name":"Vampiric Bloodlust","commander":"Edgar Markov","set":"Commander 2017","fileName":"Vampiric_Bloodlust.dck","colors":[],"year":2017},
{"id":"Breed_Lethality_CM2","name":"Breed Lethality","commander":"Atraxa, Praetors' Voice","set":"Commander Anthology Volume II","fileName":"Breed_Lethality_CM2.dck","colors":[],"year":2018},
{"id":"Built_From_Scratch_CM2","name":"Built From Scratch","commander":"Daretti, Scrap Savant","set":"Commander Anthology Volume II","fileName":"Built_From_Scratch_CM2.dck","colors":[],"year":2018},
{"id":"Devour_for_Power_CM2","name":"Devour for Power","commander":"The Mimeoplasm","set":"Commander Anthology Volume II","fileName":"Devour_for_Power_CM2.dck","colors":[],"year":2018},
{"id":"Wade_into_Battle_CM2","name":"Wade into Battle","commander":"Kalemne, Disciple of Iroas","set":"Commander Anthology Volume II","fileName":"Wade_into_Battle_CM2.dck","colors":[],"year":2018},
{"id":"Adaptive_Enchantment","name":"Adaptive Enchantment","commander":"Estrid, the Masked","set":"Commander 2018","fileName":"Adaptive_Enchantment.dck","colors":[],"year":2018},
{"id":"Exquisite_Invention","name":"Exquisite Invention","commander":"Saheeli, the Gifted","set":"Commander 2018","fileName":"Exquisite_Invention.dck","colors":[],"year":2018},
{"id":"Natures_Vengeance","name":"Nature's Vengeance","commander":"Lord Windgrace","set":"Commander 2018","fileName":"Natures_Vengeance.dck","colors":[],"year":2018},
{"id":"Subjective_Reality","name":"Subjective Reality","commander":"Aminatou, the Fateshifter","set":"Commander 2018","fileName":"Subjective_Reality.dck","colors":[],"year":2018},
{"id":"Faceless_Menace","name":"Faceless Menace","commander":"Kadena, Slinking Sorcerer","set":"Commander 2019","fileName":"Faceless_Menace.dck","colors":[],"year":2019},
{"id":"Merciless_Rage","name":"Merciless Rage","commander":"Anje Falkenrath","set":"Commander 2019","fileName":"Merciless_Rage.dck","colors":[],"year":2019},
{"id":"Mystic_Intellect","name":"Mystic Intellect","commander":"Sevinne, the Chronoclasm","set":"Commander 2019","fileName":"Mystic_Intellect.dck","colors":[],"year":2019},
{"id":"Primal_Genesis","name":"Primal Genesis","commander":"Ghired, Conclave Exile","set":"Commander 2019","fileName":"Primal_Genesis.dck","colors":[],"year":2019},
{"id":"Arcane_Maelstrom","name":"Arcane Maelstrom","commander":"Kalamax, the Stormsire","set":"Commander 2020","fileName":"Arcane_Maelstrom.dck","colors":[],"year":2020},
{"id":"Enhanced_Evolution","name":"Enhanced Evolution","commander":"Otrimi, the Ever-Playful","set":"Commander 2020","fileName":"Enhanced_Evolution.dck","colors":[],"year":2020},
{"id":"Ruthless_Regiment","name":"Ruthless Regiment","commander":"Jirina Kudro","set":"Commander 2020","fileName":"Ruthless_Regiment.dck","colors":[],"year":2020},
{"id":"Symbiotic_Swarm","name":"Symbiotic Swarm","commander":"Kathril, Aspect Warper","set":"Commander 2020","fileName":"Symbiotic_Swarm.dck","colors":[],"year":2020},
{"id":"Timeless_Wisdom","name":"Timeless Wisdom","commander":"Gavi, Nest Warden","set":"Commander 2020","fileName":"Timeless_Wisdom.dck","colors":[],"year":2020},
{"id":"Lands_Wrath","name":"Land's Wrath","commander":"Obuun, Mul Daya Ancestor","set":"Zendikar Rising Commander","fileName":"Lands_Wrath.dck","colors":[],"year":2020},
{"id":"Sneak_Attack","name":"Sneak Attack","commander":"Anowon, the Ruin Thief","set":"Zendikar Rising Commander","fileName":"Sneak_Attack.dck","colors":[],"year":2020},
{"id":"Arm_for_Battle","name":"Arm for Battle","commander":"Wyleth, Soul of Steel","set":"Commander Legends","fileName":"Arm_for_Battle.dck","colors":[],"year":2020},
{"id":"Reap_the_Tides","name":"Reap the Tides","commander":"Aesi, Tyrant of Gyre Strait","set":"Commander Legends","fileName":"Reap_the_Tides.dck","colors":[],"year":2020},
{"id":"Elven_Empire","name":"Elven Empire","commander":"Lathril, Blade of the Elves","set":"Kaldheim Commander","fileName":"Elven_Empire.dck","colors":[],"year":2021},
{"id":"Phantom_Premonition","name":"Phantom Premonition","commander":"Ranar the Ever-Watchful","set":"Kaldheim Commander","fileName":"Phantom_Premonition.dck","colors":[],"year":2021},
{"id":"Lorehold_Legacies","name":"Lorehold Legacies","commander":"Osgir, the Reconstructor","set":"Commander 2021","fileName":"Lorehold_Legacies.dck","colors":[],"year":2021},
{"id":"Prismari_Performance","name":"Prismari Performance","commander":"Zaffai, Thunder Conductor","set":"Commander 2021","fileName":"Prismari_Performance.dck","colors":[],"year":2021},
{"id":"Quantum_Quandrix","name":"Quantum Quandrix","commander":"Adrix and Nev, Twincasters","set":"Commander 2021","fileName":"Quantum_Quandrix.dck","colors":[],"year":2021},
{"id":"Silverquill_Statement","name":"Silverquill Statement","commander":"Breena, the Demagogue","set":"Commander 2021","fileName":"Silverquill_Statement.dck","colors":[],"year":2021},
{"id":"Witherbloom_Witchcraft","name":"Witherbloom Witchcraft","commander":"Willowdusk, Essence Seer","set":"Commander 2021","fileName":"Witherbloom_Witchcraft.dck","colors":[],"year":2021},
{"id":"Aura_of_Courage","name":"Aura of Courage","commander":"Galea, Kindler of Hope","set":"Forgotten Realms Commander","fileName":"Aura_of_Courage.dck","colors":[],"year":2021},
{"id":"Draconic_Rage","name":"Draconic Rage","commander":"Vrondiss, Rage of Ancients","set":"Forgotten Realms Commander","fileName":"Draconic_Rage.dck","colors":[],"year":2021},
{"id":"Dungeons_of_Death","name":"Dungeons of Death","commander":"Sefris of the Hidden Ways","set":"Forgotten Realms Commander","fileName":"Dungeons_of_Death.dck","colors":[],"year":2021},
{"id":"Planar_Portal","name":"Planar Portal","commander":"Prosper, Tome-Bound","set":"Forgotten Realms Commander","fileName":"Planar_Portal.dck","colors":[],"year":2021},
{"id":"Coven_Counters","name":"Coven Counters","commander":"Leinore, Autumn Sovereign","set":"Midnight Hunt Commander","fileName":"Coven_Counters.dck","colors":[],"year":2021},
{"id":"Undead_Unleashed","name":"Undead Unleashed","commander":"Wilhelt, the Rotcleaver","set":"Midnight Hunt Commander","fileName":"Undead_Unleashed.dck","colors":[],"year":2021},
{"id":"Spirit_Squadron","name":"Spirit Squadron","commander":"Millicent, Restless Revenant","set":"Crimson Vow Commander","fileName":"Spirit_Squadron.dck","colors":[],"year":2021},
{"id":"Vampiric_Bloodline","name":"Vampiric Bloodline","commander":"Strefan, Maurer Progenitor","set":"Crimson Vow Commander","fileName":"Vampiric_Bloodline.dck","colors":[],"year":2021},
{"id":"Buckle_Up","name":"Buckle Up","commander":"Kotori, Pilot Prodigy","set":"Neon Dynasty Commander","fileName":"Buckle_Up.dck","colors":[],"year":2022},
{"id":"Upgrades_Unleashed","name":"Upgrades Unleashed","commander":"Chishiro, the Shattered Blade","set":"Neon Dynasty Commander","fileName":"Upgrades_Unleashed.dck","colors":[],"year":2022},
{"id":"Heads_I_Win,_Tails_You_Lose","name":"Heads I Win, Tails You Lose","commander":"Zndrsplt, Eye of Wisdom","set":"Secret Lair Drop","fileName":"Heads_I_Win,_Tails_You_Lose.dck","colors":[],"year":2022},
{"id":"Bedecked_Brokers","name":"Bedecked Brokers","commander":"Perrie, the Pulverizer","set":"New Capenna Commander","fileName":"Bedecked_Brokers.dck","colors":[],"year":2022},
{"id":"Cabaretti_Cacophony","name":"Cabaretti Cacophony","commander":"Kitt Kanto, Mayhem Diva","set":"New Capenna Commander","fileName":"Cabaretti_Cacophony.dck","colors":[],"year":2022},
{"id":"Maestros_Massacre","name":"Maestros Massacre","commander":"Anhelo, the Painter","set":"New Capenna Commander","fileName":"Maestros_Massacre.dck","colors":[],"year":2022},
{"id":"Obscura_Operation","name":"Obscura Operation","commander":"Kamiz, Obscura Oculus","set":"New Capenna Commander","fileName":"Obscura_Operation.dck","colors":[],"year":2022},
{"id":"Riveteers_Rampage","name":"Riveteers Rampage","commander":"Henzie \"Toolbox\" Torre","set":"New Capenna Commander","fileName":"Riveteers_Rampage.dck","colors":[],"year":2022},
{"id":"Draconic_Dissent","name":"Draconic Dissent","commander":"Firkraag, Cunning Instigator","set":"Commander Legends: Battle for Baldur's Gate","fileName":"Draconic_Dissent.dck","colors":[],"year":2022},
{"id":"Exit_from_Exile","name":"Exit from Exile","commander":"Faldorn, Dread Wolf Herald","set":"Commander Legends: Battle for Baldur's Gate","fileName":"Exit_from_Exile.dck","colors":[],"year":2022},
{"id":"Mind_Flayarrrs","name":"Mind Flayarrrs","commander":"Captain N'ghathrod","set":"Commander Legends: Battle for Baldur's Gate","fileName":"Mind_Flayarrrs.dck","colors":[],"year":2022},
{"id":"Party_Time","name":"Party Time","commander":"Nalia de'Arnise","set":"Commander Legends: Battle for Baldur's Gate","fileName":"Party_Time.dck","colors":[],"year":2022},
{"id":"Legends_Legacy","name":"Legends' Legacy","commander":"Dihada, Binder of Wills","set":"Dominaria United Commander","fileName":"Legends_Legacy.dck","colors":[],"year":2022},
{"id":"Painbow","name":"Painbow","commander":"Jared Carthalion","set":"Dominaria United Commander","fileName":"Painbow.dck","colors":[],"year":2022},
{"id":"Forces_of_the_Imperium","name":"Forces of the Imperium","commander":"Inquisitor Greyfax","set":"Warhammer 40,000 Commander","fileName":"Forces_of_the_Imperium.dck","colors":[],"year":2022},
{"id":"Forces_of_the_Imperium_Collectors_Edition","name":"Forces of the Imperium Collector's Edition","commander":"Inquisitor Greyfax","set":"Warhammer 40,000 Commander","fileName":"Forces_of_the_Imperium_Collectors_Edition.dck","colors":[],"year":2022},
{"id":"Necron_Dynasties","name":"Necron Dynasties","commander":"Szarekh, the Silent King","set":"Warhammer 40,000 Commander","fileName":"Necron_Dynasties.dck","colors":[],"year":2022},
{"id":"Necron_Dynasties_Collectors_Edition","name":"Necron Dynasties Collector's Edition","commander":"Szarekh, the Silent King","set":"Warhammer 40,000 Commander","fileName":"Necron_Dynasties_Collectors_Edition.dck","colors":[],"year":2022},
{"id":"The_Ruinous_Powers","name":"The Ruinous Powers","commander":"Abaddon the Despoiler","set":"Warhammer 40,000 Commander","fileName":"The_Ruinous_Powers.dck","colors":[],"year":2022},
{"id":"The_Ruinous_Powers_Collectors_Edition","name":"The Ruinous Powers Collector's Edition","commander":"Abaddon the Despoiler","set":"Warhammer 40,000 Commander","fileName":"The_Ruinous_Powers_Collectors_Edition.dck","colors":[],"year":2022},
{"id":"Tyranid_Swarm","name":"Tyranid Swarm","commander":"The Swarmlord","set":"Warhammer 40,000 Commander","fileName":"Tyranid_Swarm.dck","colors":[],"year":2022},
{"id":"Tyranid_Swarm_Collectors_Edition","name":"Tyranid Swarm Collector's Edition","commander":"The Swarmlord","set":"Warhammer 40,000 Commander","fileName":"Tyranid_Swarm_Collectors_Edition.dck","colors":[],"year":2022},
{"id":"Mishras_Burnished_Banner","name":"Mishra's Burnished Banner","commander":"Mishra, Eminent One","set":"The Brothers' War Commander","fileName":"Mishras_Burnished_Banner.dck","colors":[],"year":2022},
{"id":"Urzas_Iron_Alliance","name":"Urza's Iron Alliance","commander":"Urza, Chief Artificer","set":"The Brothers' War Commander","fileName":"Urzas_Iron_Alliance.dck","colors":[],"year":2022},
{"id":"Chaos_Incarnate","name":"Chaos Incarnate","commander":"Kardur, Doomscourge","set":"Starter Commander Decks","fileName":"Chaos_Incarnate.dck","colors":[],"year":2022},
{"id":"Draconic_Destruction","name":"Draconic Destruction","commander":"Atarka, World Render","set":"Starter Commander Decks","fileName":"Draconic_Destruction.dck","colors":[],"year":2022},
{"id":"First_Flight","name":"First Flight","commander":"Isperia, Supreme Judge","set":"Starter Commander Decks","fileName":"First_Flight.dck","colors":[],"year":2022},
{"id":"Grave_Danger","name":"Grave Danger","commander":"Gisa and Geralf","set":"Starter Commander Decks","fileName":"Grave_Danger.dck","colors":[],"year":2022},
{"id":"Token_Triumph","name":"Token Triumph","commander":"Emmara, Soul of the Accord","set":"Starter Commander Decks","fileName":"Token_Triumph.dck","colors":[],"year":2022},
{"id":"Corrupting_Influence","name":"Corrupting Influence","commander":"Ixhel, Scion of Atraxa","set":"Phyrexia: All Will Be One Commander","fileName":"Corrupting_Influence.dck","colors":[],"year":2023},
{"id":"Rebellion_Rising","name":"Rebellion Rising","commander":"Neyali, Suns' Vanguard","set":"Phyrexia: All Will Be One Commander","fileName":"Rebellion_Rising.dck","colors":[],"year":2023},
{"id":"From_Cute_to_Brute","name":"From Cute to Brute","commander":"Esika, God of the Tree","set":"Secret Lair Drop","fileName":"From_Cute_to_Brute.dck","colors":[],"year":2023},
{"id":"Elven_Council","name":"Elven Council","commander":"Galadriel, Elven-Queen","set":"Tales of Middle-earth Commander","fileName":"Elven_Council.dck","colors":[],"year":2023},
{"id":"Food_and_Fellowship","name":"Food and Fellowship","commander":"Frodo, Adventurous Hobbit","set":"Tales of Middle-earth Commander","fileName":"Food_and_Fellowship.dck","colors":[],"year":2023},
{"id":"Riders_of_Rohan","name":"Riders of Rohan","commander":"Éowyn, Shieldmaiden","set":"Tales of Middle-earth Commander","fileName":"Riders_of_Rohan.dck","colors":[],"year":2023},
{"id":"The_Hosts_of_Mordor","name":"The Hosts of Mordor","commander":"Sauron, Lord of the Rings","set":"Tales of Middle-earth Commander","fileName":"The_Hosts_of_Mordor.dck","colors":[],"year":2023},
{"id":"Eldrazi_Unbound","name":"Eldrazi Unbound","commander":"Zhulodok, Void Gorger","set":"Commander Masters","fileName":"Eldrazi_Unbound.dck","colors":[],"year":2023},
{"id":"Enduring_Enchantments","name":"Enduring Enchantments","commander":"Anikthea, Hand of Erebos","set":"Commander Masters","fileName":"Enduring_Enchantments.dck","colors":[],"year":2023},
{"id":"Planeswalker_Party","name":"Planeswalker Party","commander":"Commodore Guff","set":"Commander Masters","fileName":"Planeswalker_Party.dck","colors":[],"year":2023},
{"id":"Sliver_Swarm","name":"Sliver Swarm","commander":"Sliver Gravemother","set":"Commander Masters","fileName":"Sliver_Swarm.dck","colors":[],"year":2023},
{"id":"Angels_Theyre_Just_Like_Us_but_Cooler_and_with_Wings","name":"Angels: They're Just Like Us but Cooler and with Wings","commander":"Gisela, the Broken Blade","set":"Secret Lair Drop","fileName":"Angels_Theyre_Just_Like_Us_but_Cooler_and_with_Wings.dck","colors":[],"year":2023},
{"id":"Fae_Dominion","name":"Fae Dominion","commander":"Tegwyll, Duke of Splendor","set":"Wilds of Eldraine Commander","fileName":"Fae_Dominion.dck","colors":[],"year":2023},
{"id":"Virtue_and_Valor","name":"Virtue and Valor","commander":"Ellivere of the Wild Court","set":"Wilds of Eldraine Commander","fileName":"Virtue_and_Valor.dck","colors":[],"year":2023},
{"id":"Ahoy_Mateys","name":"Ahoy Mateys","commander":"Admiral Brass, Unsinkable","set":"The Lost Caverns of Ixalan Commander","fileName":"Ahoy_Mateys.dck","colors":[],"year":2023},
{"id":"Blood_Rites","name":"Blood Rites","commander":"Clavileño, First of the Blessed","set":"The Lost Caverns of Ixalan Commander","fileName":"Blood_Rites.dck","colors":[],"year":2023},
{"id":"Explorers_of_the_Deep","name":"Explorers of the Deep","commander":"Hakbal of the Surging Soul","set":"The Lost Caverns of Ixalan Commander","fileName":"Explorers_of_the_Deep.dck","colors":[],"year":2023},
{"id":"Veloci-Ramp-Tor","name":"Veloci-Ramp-Tor","commander":"Pantlaza, Sun-Favored","set":"The Lost Caverns of Ixalan Commander","fileName":"Veloci-Ramp-Tor.dck","colors":[],"year":2023},
{"id":"Raining_Cats_and_Dogs","name":"Raining Cats and Dogs","commander":"Rin and Seri, Inseparable","set":"Secret Lair Drop","fileName":"Raining_Cats_and_Dogs.dck","colors":[],"year":2024},
{"id":"Blame_Game","name":"Blame Game","commander":"Nelly Borca, Impulsive Accuser","set":"Murders at Karlov Manor Commander","fileName":"Blame_Game.dck","colors":[],"year":2024},
{"id":"Deadly_Disguise","name":"Deadly Disguise","commander":"Kaust, Eyes of the Glade","set":"Murders at Karlov Manor Commander","fileName":"Deadly_Disguise.dck","colors":[],"year":2024},
{"id":"Deep_Clue_Sea","name":"Deep Clue Sea","commander":"Morska, Undersea Sleuth","set":"Murders at Karlov Manor Commander","fileName":"Deep_Clue_Sea.dck","colors":[],"year":2024},
{"id":"Revenant_Recon","name":"Revenant Recon","commander":"Mirko, Obsessive Theorist","set":"Murders at Karlov Manor Commander","fileName":"Revenant_Recon.dck","colors":[],"year":2024},
{"id":"Hail,_Caesar","name":"Hail, Caesar","commander":"Caesar, Legion's Emperor","set":"Fallout","fileName":"Hail,_Caesar.dck","colors":[],"year":2024},
{"id":"Mutant_Menace","name":"Mutant Menace","commander":"The Wise Mothman","set":"Fallout","fileName":"Mutant_Menace.dck","colors":[],"year":2024},
{"id":"Science","name":"Science!","commander":"Dr. Madison Li","set":"Fallout","fileName":"Science.dck","colors":[],"year":2024},
{"id":"Scrappy_Survivors","name":"Scrappy Survivors","commander":"Dogmeat, Ever Loyal","set":"Fallout","fileName":"Scrappy_Survivors.dck","colors":[],"year":2024},
{"id":"Desert_Bloom","name":"Desert Bloom","commander":"Yuma, Proud Protector","set":"Outlaws of Thunder Junction Commander","fileName":"Desert_Bloom.dck","colors":[],"year":2024},
{"id":"Grand_Larceny","name":"Grand Larceny","commander":"Gonti, Canny Acquisitor","set":"Outlaws of Thunder Junction Commander","fileName":"Grand_Larceny.dck","colors":[],"year":2024},
{"id":"Most_Wanted","name":"Most Wanted","commander":"Olivia, Opulent Outlaw","set":"Outlaws of Thunder Junction Commander","fileName":"Most_Wanted.dck","colors":[],"year":2024},
{"id":"Quick_Draw","name":"Quick Draw","commander":"Stella Lee, Wild Card","set":"Outlaws of Thunder Junction Commander","fileName":"Quick_Draw.dck","colors":[],"year":2024},
{"id":"Creative_Energy","name":"Creative Energy","commander":"Satya, Aetherflux Genius","set":"Modern Horizons 3 Commander","fileName":"Creative_Energy.dck","colors":[],"year":2024},
{"id":"Creative_Energy_Collectors_Edition","name":"Creative Energy Collector's Edition","commander":"Satya, Aetherflux Genius","set":"Modern Horizons 3 Commander","fileName":"Creative_Energy_Collectors_Edition.dck","colors":[],"year":2024},
{"id":"Eldrazi_Incursion","name":"Eldrazi Incursion","commander":"Ulalek, Fused Atrocity","set":"Modern Horizons 3 Commander","fileName":"Eldrazi_Incursion.dck","colors":[],"year":2024},
{"id":"Eldrazi_Incursion_Collectors_Edition","name":"Eldrazi Incursion Collector's Edition","commander":"Ulalek, Fused Atrocity","set":"Modern Horizons 3 Commander","fileName":"Eldrazi_Incursion_Collectors_Edition.dck","colors":[],"year":2024},
{"id":"Graveyard_Overdrive","name":"Graveyard Overdrive","commander":"Disa the Restless","set":"Modern Horizons 3 Commander","fileName":"Graveyard_Overdrive.dck","colors":[],"year":2024},
{"id":"Graveyard_Overdrive_Collectors_Edition","name":"Graveyard Overdrive Collector's Edition","commander":"Disa the Restless","set":"Modern Horizons 3 Commander","fileName":"Graveyard_Overdrive_Collectors_Edition.dck","colors":[],"year":2024},
{"id":"Tricky_Terrain","name":"Tricky Terrain","commander":"Omo, Queen of Vesuva","set":"Modern Horizons 3 Commander","fileName":"Tricky_Terrain.dck","colors":[],"year":2024},
{"id":"Tricky_Terrain_Collectors_Edition","name":"Tricky Terrain Collector's Edition","commander":"Omo, Queen of Vesuva","set":"Modern Horizons 3 Commander","fileName":"Tricky_Terrain_Collectors_Edition.dck","colors":[],"year":2024},
{"id":"Animated_Army","name":"Animated Army","commander":"Bello, Bard of the Brambles","set":"Bloomburrow Commander","fileName":"Animated_Army.dck","colors":[],"year":2024},
{"id":"Family_Matters","name":"Family Matters","commander":"Zinnia, Valley's Voice","set":"Bloomburrow Commander","fileName":"Family_Matters.dck","colors":[],"year":2024},
{"id":"Peace_Offering","name":"Peace Offering","commander":"Ms. Bumbleflower","set":"Bloomburrow Commander","fileName":"Peace_Offering.dck","colors":[],"year":2024},
{"id":"Squirreled_Away","name":"Squirreled Away","commander":"Hazel of the Rootbloom","set":"Bloomburrow Commander","fileName":"Squirreled_Away.dck","colors":[],"year":2024},
{"id":"20_Ways_to_Win","name":"20 Ways to Win","commander":"Go-Shintai of Life's Origin","set":"Secret Lair Drop","fileName":"20_Ways_to_Win.dck","colors":[],"year":2024},
{"id":"Eternal_Might","name":"Eternal Might","commander":"Temmet, Naktamun's Will","set":"Aetherdrift Commander","fileName":"Eternal_Might.dck","colors":[],"year":2025},
{"id":"Living_Energy","name":"Living Energy","commander":"Saheeli, Radiant Creator","set":"Aetherdrift Commander","fileName":"Living_Energy.dck","colors":[],"year":2025},
{"id":"Abzan_Armor","name":"Abzan Armor","commander":"Felothar the Steadfast","set":"Tarkir: Dragonstorm Commander","fileName":"Abzan_Armor.dck","colors":[],"year":2025},
{"id":"Jeskai_Striker","name":"Jeskai Striker","commander":"Shiko and Narset, Unified","set":"Tarkir: Dragonstorm Commander","fileName":"Jeskai_Striker.dck","colors":[],"year":2025},
{"id":"Mardu_Surge","name":"Mardu Surge","commander":"Zurgo Stormrender","set":"Tarkir: Dragonstorm Commander","fileName":"Mardu_Surge.dck","colors":[],"year":2025},
{"id":"Sultai_Arisen","name":"Sultai Arisen","commander":"Teval, the Balanced Scale","set":"Tarkir: Dragonstorm Commander","fileName":"Sultai_Arisen.dck","colors":[],"year":2025},
{"id":"Temur_Roar","name":"Temur Roar","commander":"Eshki, Temur's Roar","set":"Tarkir: Dragonstorm Commander","fileName":"Temur_Roar.dck","colors":[],"year":2025},
{"id":"Everyones_Invited","name":"Everyone's Invited!","commander":"Morophon, the Boundless","set":"Secret Lair Drop","fileName":"Everyones_Invited.dck","colors":[],"year":2025},
{"id":"Counter_Blitz_(FINAL_FANTASY_X)","name":"Counter Blitz (FINAL FANTASY X)","commander":"Tidus, Yuna's Guardian","set":"Final Fantasy Commander","fileName":"Counter_Blitz_(FINAL_FANTASY_X).dck","colors":[],"year":2025},
{"id":"Counter_Blitz_Collectors_Edition_(FINAL_FANTASY_X)","name":"Counter Blitz Collector's Edition (FINAL FANTASY X)","commander":"Tidus, Yuna's Guardian","set":"Final Fantasy Commander","fileName":"Counter_Blitz_Collectors_Edition_(FINAL_FANTASY_X).dck","colors":[],"year":2025},
{"id":"Limit_Break_(FINAL_FANTASY_VII)","name":"Limit Break (FINAL FANTASY VII)","commander":"Cloud, Ex-SOLDIER","set":"Final Fantasy Commander","fileName":"Limit_Break_(FINAL_FANTASY_VII).dck","colors":[],"year":2025},
{"id":"Limit_Break_Collectors_Edition_(FINAL_FANTASY_VII)","name":"Limit Break Collector's Edition (FINAL FANTASY VII)","commander":"Cloud, Ex-SOLDIER","set":"Final Fantasy Commander","fileName":"Limit_Break_Collectors_Edition_(FINAL_FANTASY_VII).dck","colors":[],"year":2025},
{"id":"Revival_Trance_(FINAL_FANTASY_VI)","name":"Revival Trance (FINAL FANTASY VI)","commander":"Terra, Herald of Hope","set":"Final Fantasy Commander","fileName":"Revival_Trance_(FINAL_FANTASY_VI).dck","colors":[],"year":2025},
{"id":"Revival_Trance_Collectors_Edition_(FINAL_FANTASY_VI)","name":"Revival Trance Collector's Edition (FINAL FANTASY VI)","commander":"Terra, Herald of Hope","set":"Final Fantasy Commander","fileName":"Revival_Trance_Collectors_Edition_(FINAL_FANTASY_VI).dck","colors":[],"year":2025},
{"id":"Scions_&_Spellcraft_(FINAL_FANTASY_XIV)","name":"Scions & Spellcraft (FINAL FANTASY XIV)","commander":"Y'shtola, Night's Blessed","set":"Final Fantasy Commander","fileName":"Scions_&_Spellcraft_(FINAL_FANTASY_XIV).dck","colors":[],"year":2025},
{"id":"Scions_&_Spellcraft_Collectors_Edition_(FINAL_FANTASY_XIV)","name":"Scions & Spellcraft Collector's Edition (FINAL FANTASY XIV)","commander":"Y'shtola, Night's Blessed","set":"Final Fantasy Commander","fileName":"Scions_&_Spellcraft_Collectors_Edition_(FINAL_FANTASY_XIV).dck","colors":[],"year":2025},
{"id":"Counter_Intelligence","name":"Counter Intelligence","commander":"Inspirit, Flagship Vessel","set":"Edge of Eternities Commander","fileName":"Counter_Intelligence.dck","colors":[],"year":2025},
{"id":"World_Shaper","name":"World Shaper","commander":"Hearthhull, the Worldseed","set":"Edge of Eternities Commander","fileName":"World_Shaper.dck","colors":[],"year":2025},
{"id":"Blight_Curse","name":"Blight Curse","commander":"Auntie Ool, Cursewretch","set":"Lorwyn Eclipsed Commander","fileName":"Blight_Curse.dck","colors":[],"year":2026},
{"id":"Dance_of_the_Elements","name":"Dance of the Elements","commander":"Ashling, the Limitless","set":"Lorwyn Eclipsed Commander","fileName":"Dance_of_the_Elements.dck","colors":[],"year":2026},
{"id":"Turtle_Power","name":"Turtle Power!","commander":"Heroes in a Half Shell","set":"Teenage Mutant Ninja Turtles Eternal","fileName":"Turtle_Power.dck","colors":[],"year":2026}
];
+82 -203
View File
@@ -4,15 +4,10 @@ Commander AI Lab — Action Labeler
Maps raw Forge action records (from DecisionSnapshot JSONL)
to one of 8 macro-action labels for supervised policy learning.
Classification logic (updated):
1. Check action.type for unambiguous types (attack, land, pass, hold,
cast_commander)
2. For "cast" actions:
a. If action.card is present, match directly against name databases
b. If action.card is absent (Forge omits it), scan the active
player's hand against name databases to infer the cast type.
Priority: removal > ramp > draw > commander > creature (default)
3. Fallback: PASS
Classification logic:
1. Check action.type (cast, attack, land, cast_commander, pass)
2. For "cast" actions, classify by card oracle text / card type keywords
3. For ambiguous cases, use the raw log line and card name heuristics
Macro-actions (from ml.config.scope):
0: CAST_CREATURE — Play a creature
@@ -46,6 +41,11 @@ logger = logging.getLogger("ml.labeler")
# Card Type Keyword Databases
# ══════════════════════════════════════════════════════════
# Known removal spells (partial list — expanded from common Commander staples)
REMOVAL_KEYWORDS = {
"destroy", "exile", "sacrifice", "counter", "bounce", "return.*to.*hand",
"-\\d+/-\\d+", "damage to", "fight", "deathtouch",
}
REMOVAL_CARD_NAMES = {
"swords to plowshares", "path to exile", "beast within", "chaos warp",
"counterspell", "swan song", "negate", "arcane denial", "doomblade",
@@ -62,52 +62,45 @@ REMOVAL_CARD_NAMES = {
"decree of pain", "in garruk's wake", "plague wind",
"fire covenant", "imprisoned in the moon", "darksteel mutation",
"kenrith's transformation", "song of the dryads",
"abrade", "disenchant", "naturalize", "wear", "tear",
"shattering spree", "shatter", "smash to smithereens",
"lightning bolt", "lightning helix", "condemn", "oust",
"pongify", "reality shift", "turn to frog", "polymorph",
"boros charm", "utter end", "anguished unmaking", "mortify",
"putrefy", "maelstrom pulse", "void rend", "render silent",
"overwhelming denial", "test of talents", "dispel", "spell pierce",
"flusterstorm", "mental misstep", "pact of negation",
"opposition agent", "hullbreacher", "narset parter of veils",
"grafdigger's cage", "rest in peace", "leyline of the void",
"tormod's crypt", "relic of progenitus",
}
# Known draw spells
DRAW_KEYWORDS = {
"draw", "scry", "look at the top", "reveal.*library",
"search your library.*hand", "impulse", "brainstorm",
}
DRAW_CARD_NAMES = {
"rhystic study", "mystic remora", "phyrexian arena", "sylvan library",
"harmonize", "blue sun's zenith", "pull from tomorrow",
"windfall", "wheel of fortune", "timetwister", "brainstorm",
"ponder", "preordain", "opt", "consider", "treasure cruise",
"dig through time", "fact or fiction", "night's whisper",
"sign in blood", "read the bones", "painful truths",
"ambition's cost", "promise of power", "necropotence",
"dark confidant", "toski bearer of secrets", "beast whisperer",
"guardian project", "the great henge", "skullclamp",
"esper sentinel", "archivist of oghma", "mind's eye",
"consecrated sphinx", "ancient craving", "faithless looting",
"cathartic reunion", "thrill of possibility", "jeska's will",
"valakut awakening", "stinging study", "notion thief",
"tymna the weaver", "shamanic revelation", "rishkar's expertise",
"return of the wildspeaker", "garruk's uprising", "elemental bond",
"kindred discovery", "coastal piracy", "reconnaissance mission",
"bident of thassa", "distant melody", "slate of ancestry",
"wheel of fate", "reforge the soul", "magus of the wheel",
"river's rebuke", "prosperity", "intellectual offering",
"peer into the abyss", "mind spring", "stroke of genius",
"jace's ingenuity", "tidings", "concentrate", "divination",
"inspiration", "counsel of the soratami", "accumulated knowledge",
"predict", "pressure point", "quicken", "serum visions",
"gitaxian probe", "mental note", "thought scour",
"dig through time", "fact or fiction", "nights whisper",
"nights whisper", "sign in blood", "read the bones",
"painful truths", "ambition's cost", "promise of power",
"necropotence", "dark confidant", "toski bearer of secrets",
"beast whisperer", "guardian project", "the great henge",
"skullclamp", "esper sentinel", "archivist of oghma",
"mind's eye", "consecrated sphinx", "ancient craving",
"faithless looting", "cathartic reunion", "thrill of possibility",
"jeska's will", "valakut awakening", "stinging study",
"night's whisper", "notion thief", "tymna the weaver",
"shamanic revelation", "rishkar's expertise", "return of the wildspeaker",
"garruk's uprising", "elemental bond", "kindred discovery",
"coastal piracy", "reconnaissance mission", "bident of thassa",
}
# Known ramp cards
RAMP_KEYWORDS = {
"add {", "add one mana", "mana of any color",
"land.*onto the battlefield", "search.*basic land.*battlefield",
}
RAMP_CARD_NAMES = {
"sol ring", "mana crypt", "mana vault", "arcane signet",
"commander's sphere", "chromatic lantern", "fellwar stone",
"mind stone", "thought vessel", "thran dynamo", "worn powerstone",
"gilded lotus", "hedron archive", "everflowing chalice",
"coalition relic", "prismatic lens",
"coalition relic", "prismatic lens", "signets", # catch-all partial
"talisman", # catch-all for talisman cycle
"cultivate", "kodama's reach", "rampant growth", "farseek",
"nature's lore", "three visits", "skyshroud claim",
"explosive vegetation", "migration path", "circuitous route",
@@ -119,144 +112,13 @@ RAMP_CARD_NAMES = {
"birds of paradise", "llanowar elves", "elvish mystic",
"fyndhorn elves", "avacyn's pilgrim", "elves of deep shadow",
"bloom tender", "priest of titania", "selvala heart of the wilds",
"boreal druid", "green sun's zenith", "eternal witness",
"reclamation sage", "mystic snake", "fierce empath",
"signal the clans", "crop rotation", "harrow", "kodama's reach",
"traverse the ulvenwald", "search for tomorrow", "primal growth",
"land grant", "untamed wilds", "rangers path", "rangers' path",
"nissa's pilgrimage", "forest grove", "grove of the burnwillows",
"cabal stronghold", "urborg tomb of yawgmoth", "urborg, tomb of yawgmoth",
"bojuka bog", "ghost quarter", "field of ruin", "strip mine",
"wasteland", "tectonic edge", "dust bowl",
"worn powerstone", "basalt monolith", "grim monolith",
"mana geode", "darksteel ingot", "manalith", "opaline unicorn",
"vessel of endless rest", "corrupted grafstone", "dreamstone hedron",
"sisay's ring", "ur-golem's eye", "blinkmoth urn",
"astral cornucopia", "druids' repository", "black market",
"cryptolith rite", "earthcraft", "citanul hierophants",
"zendikar resurgent", "mirari's wake", "mana reflection",
"vorinclex voice of hunger", "vorinclex, voice of hunger",
}
# Partial-match prefixes (for cycles like Signets, Talismans)
RAMP_PARTIAL_PREFIXES = {
"talisman", "signet", "locket", "banner", "obelisk",
"keyrune", "cluestone", "monolith", "medallion",
# Known creature-type indicators
CREATURE_KEYWORDS = {
"creature", "token", "enters the battlefield",
}
DRAW_PARTIAL_PREFIXES = {
"scroll", "tome", "journal",
}
# ══════════════════════════════════════════════════════════
# Core classification helpers
# ══════════════════════════════════════════════════════════
def _classify_card_name(name: str) -> Optional[MacroAction]:
"""
Classify a single card name into a MacroAction, or None if unknown.
Checks exact matches first, then partial prefix matches.
Returns None for unrecognised cards (caller handles the default).
"""
n = name.lower().strip()
if not n:
return None
if n in REMOVAL_CARD_NAMES:
return MacroAction.CAST_REMOVAL
if n in DRAW_CARD_NAMES:
return MacroAction.CAST_DRAW
if n in RAMP_CARD_NAMES:
return MacroAction.CAST_RAMP
# Partial prefix match for cycles (Talismans, Signets, etc.)
for prefix in RAMP_PARTIAL_PREFIXES:
if n.startswith(prefix):
return MacroAction.CAST_RAMP
for prefix in DRAW_PARTIAL_PREFIXES:
if n.startswith(prefix):
return MacroAction.CAST_DRAW
# Substring match (catches "Doom Blade" inside longer names etc.)
for known in REMOVAL_CARD_NAMES:
if known in n or n in known:
return MacroAction.CAST_REMOVAL
for known in DRAW_CARD_NAMES:
if known in n or n in known:
return MacroAction.CAST_DRAW
for known in RAMP_CARD_NAMES:
if known in n or n in known:
return MacroAction.CAST_RAMP
return None # Unknown → caller defaults to CAST_CREATURE
def _classify_from_hand(
players: list,
active_seat: int,
commander_names: Optional[set] = None,
) -> MacroAction:
"""
Infer the cast action type by scanning the active player's hand.
When action.card is absent (Forge omits it), the hand snapshot
is the best available signal. We scan all hand cards and return
the highest-priority match:
removal > ramp > draw > commander > creature (default)
Priority rationale: Forge's AI plays the highest-impact available
action, so if any removal/ramp/draw spell is in hand during a cast
decision, it's the most likely card played.
"""
if active_seat >= len(players):
return MacroAction.CAST_CREATURE
hand: List[str] = players[active_seat].get("hand", [])
command_zone: List[str] = players[active_seat].get("command_zone", [])
# Build commander name set from command_zone if not provided
if commander_names is None:
commander_names = {c.lower().strip() for c in command_zone if c}
found_removal = False
found_ramp = False
found_draw = False
found_commander = False
for card in hand:
card_lower = card.lower().strip()
# Commander check: hand card matches a command zone card
if card_lower in commander_names:
found_commander = True
continue
result = _classify_card_name(card_lower)
if result == MacroAction.CAST_REMOVAL:
found_removal = True
elif result == MacroAction.CAST_RAMP:
found_ramp = True
elif result == MacroAction.CAST_DRAW:
found_draw = True
# Return highest-priority found
if found_removal:
return MacroAction.CAST_REMOVAL
if found_ramp:
return MacroAction.CAST_RAMP
if found_draw:
return MacroAction.CAST_DRAW
if found_commander:
return MacroAction.CAST_COMMANDER
return MacroAction.CAST_CREATURE
# ══════════════════════════════════════════════════════════
# Main label_action entry point
# ══════════════════════════════════════════════════════════
def label_action(decision: dict) -> int:
"""
@@ -271,52 +133,74 @@ def label_action(decision: dict) -> int:
action = decision.get("action", {})
action_type = action.get("type", "").lower()
card_name = (action.get("card", "") or "").lower().strip()
raw_line = (action.get("raw", "") or "").lower()
players = decision.get("players", [])
active_seat = decision.get("active_seat", 0)
# ── Unambiguous direct-type matches ──────────────────────
# ── Direct type matching ────────────────────────────
# Commander cast is unambiguous
if action_type == "cast_commander":
return ACTION_TO_IDX[MacroAction.CAST_COMMANDER]
# Attack is unambiguous
if action_type == "attack":
return ACTION_TO_IDX[MacroAction.ATTACK_OPPONENT]
# Land play → developing mana base = ramp
# Land play → classify as CAST_RAMP (developing mana is ramp)
if action_type == "land":
return ACTION_TO_IDX[MacroAction.CAST_RAMP]
# Pass / hold mana — check available mana to distinguish
# Pass / hold mana
if action_type in ("pass", "hold"):
# Check if player had mana open (from state)
active_seat = decision.get("active_seat", 0)
players = decision.get("players", [])
if active_seat < len(players):
mana = players[active_seat].get("mana", 0)
if mana >= 2:
return ACTION_TO_IDX[MacroAction.HOLD_MANA]
return ACTION_TO_IDX[MacroAction.PASS]
# ── Cast actions ──────────────────────────────────────
# ── Cast actions: classify by card identity ─────────
if action_type == "cast":
# Path A: action.card is present — classify it directly
if card_name:
result = _classify_card_name(card_name)
if result is not None:
return ACTION_TO_IDX[result]
# Unrecognised named card → default creature
return ACTION_TO_IDX[MacroAction.CAST_CREATURE]
# 1. Check known card name databases
if card_name in REMOVAL_CARD_NAMES or _partial_match(card_name, REMOVAL_CARD_NAMES):
return ACTION_TO_IDX[MacroAction.CAST_REMOVAL]
# Path B: action.card absent (Forge omits it) — infer from hand
inferred = _classify_from_hand(players, active_seat)
return ACTION_TO_IDX[inferred]
if card_name in DRAW_CARD_NAMES or _partial_match(card_name, DRAW_CARD_NAMES):
return ACTION_TO_IDX[MacroAction.CAST_DRAW]
# ── Fallback ──────────────────────────────────────────
if card_name in RAMP_CARD_NAMES or _partial_match(card_name, RAMP_CARD_NAMES):
return ACTION_TO_IDX[MacroAction.CAST_RAMP]
# 2. Check raw log line for keyword patterns
for keyword in REMOVAL_KEYWORDS:
if re.search(keyword, raw_line):
return ACTION_TO_IDX[MacroAction.CAST_REMOVAL]
for keyword in DRAW_KEYWORDS:
if re.search(keyword, raw_line):
return ACTION_TO_IDX[MacroAction.CAST_DRAW]
for keyword in RAMP_KEYWORDS:
if re.search(keyword, raw_line):
return ACTION_TO_IDX[MacroAction.CAST_RAMP]
# 3. Default: if it's a spell cast and not recognized, assume creature
# (most casts in Commander are creatures or creature-adjacent)
return ACTION_TO_IDX[MacroAction.CAST_CREATURE]
# ── Fallback ────────────────────────────────────────
return ACTION_TO_IDX[MacroAction.PASS]
# ══════════════════════════════════════════════════════════
# File-level helpers
# ══════════════════════════════════════════════════════════
def _partial_match(name: str, name_set: set) -> bool:
"""Check if card name partially matches any name in the set."""
for known in name_set:
if known in name or name in known:
return True
return False
def label_decisions_file(jsonl_path: str) -> Tuple[np.ndarray, List[dict]]:
"""
@@ -348,11 +232,7 @@ def label_decisions_file(jsonl_path: str) -> Tuple[np.ndarray, List[dict]]:
def print_label_distribution(labels: np.ndarray) -> Dict[str, int]:
"""Print and return the distribution of action labels.
Iterates MacroAction enum in index order so the display always
matches ACTION_TO_IDX regardless of dict insertion order.
"""
"""Print and return the distribution of action labels."""
dist = {}
for action in MacroAction:
idx = ACTION_TO_IDX[action]
@@ -362,11 +242,10 @@ def print_label_distribution(labels: np.ndarray) -> Dict[str, int]:
total = len(labels)
logger.info(f"\n{'Action':<25} {'Count':>8} {'Pct':>8}")
logger.info("─" * 43)
# Sort descending by count for readability
for action_name, count in sorted(dist.items(), key=lambda x: -x[1]):
pct = (count / total * 100) if total > 0 else 0
logger.info(f" {action_name:<23} {count:>8} {pct:>7.1f}%")
logger.info("─" * 43)
logger.info(f"{'─' * 43}")
logger.info(f" {'TOTAL':<23} {total:>8}")
return dist
+17 -32
View File
@@ -6,9 +6,8 @@ Reads ML decision JSONL files, encodes states, labels actions,
and produces a training-ready dataset saved as NPZ.
Phase 2: Source Awareness (Issue #66)
- Scans Forge sim files (ml-decisions-sim-*.jsonl) → source "forge"
- Scans PPO self-play (ml-decisions-ppo-*.jsonl) → source "ppo"
- Scans DeepSeek files (ml-decisions-ds-*.jsonl) → source "ds"
- Scans both Forge sim files (ml-decisions-sim-*.jsonl) and
PPO self-play files (ml-decisions-ppo-*.jsonl)
- Configurable source_weights for sampling ratios
- min_reward_threshold filter for PPO data quality
- Each sample tagged with source for downstream analysis
@@ -22,7 +21,7 @@ Output NPZ structure:
game_ids: object (N,) — game ID for each sample
outcomes: object (N,) — game outcome per sample
playstyles: object (N,) — deck archetype per sample
sources: object (N,) — data source ("forge", "ppo", or "ds")
sources: object (N,) — data source ("forge" or "ppo")
"""
import argparse
@@ -63,11 +62,11 @@ class DatasetConfig:
embeddings_dir: Optional[str] = None
max_samples: Optional[int] = None
# Source weights control sampling ratios between Forge, PPO, and DS data.
# ds=4.0 oversamples the 8 DeepSeek files from ~5.8% → ~20% of effective
# training tokens, matching their higher signal quality relative to sim data.
# Source weights control sampling ratios between Forge and PPO data.
# Default: Forge-only (ppo=0.0). Use MIXED_MODE_PRESETS from
# ml.config.scope for blended configurations (e.g. 90/10, 80/20).
source_weights: Dict[str, float] = field(
default_factory=lambda: {"forge": 1.0, "ppo": 0.0, "ds": 4.0}
default_factory=lambda: {"forge": 1.0, "ppo": 0.0}
)
# Minimum reward threshold for PPO data — only include decisions
@@ -82,13 +81,12 @@ class DatasetConfig:
def _discover_jsonl_files(results_dir: str) -> Dict[str, List[Path]]:
"""
Scan results directory for Forge sim, PPO, and DeepSeek decision files.
Scan results directory for both Forge sim and PPO decision files.
Returns:
Dict mapping source name to list of JSONL file paths.
Keys: "forge" for ml-decisions-sim-*.jsonl
"ppo" for ml-decisions-ppo-*.jsonl
"ds" for ml-decisions-ds-*.jsonl
"""
results_path = Path(results_dir)
sources = {}
@@ -103,16 +101,10 @@ def _discover_jsonl_files(results_dir: str) -> Dict[str, List[Path]]:
if ppo_files:
sources["ppo"] = ppo_files
# DeepSeek high-quality decisions (upweighted by default)
ds_files = sorted(results_path.glob("ml-decisions-ds-*.jsonl"))
if ds_files:
sources["ds"] = ds_files
# Legacy files that don't match any known prefix — treat as forge
known = set(forge_files + ppo_files + ds_files)
# Also pick up legacy files that don't have sim/ppo prefix
legacy_files = sorted(
f for f in results_path.glob("ml-decisions-*.jsonl")
if f not in known
if f not in set(forge_files + ppo_files)
)
if legacy_files:
sources.setdefault("forge", []).extend(legacy_files)
@@ -131,7 +123,7 @@ def _passes_reward_filter(
) -> bool:
"""
Filter PPO decisions by reward threshold.
Forge and DS data always passes. PPO data must meet the threshold.
Forge data always passes. PPO data must meet the threshold.
"""
if source != "ppo":
return True
@@ -163,7 +155,7 @@ def _apply_source_weights(
if weight <= 0:
logger.info(" Skipping %d %s samples (weight=0)", len(samples), source)
continue
if weight == 1.0:
if weight >= 1.0 and weight == 1.0:
combined.extend(samples)
elif weight < 1.0:
# Subsample
@@ -201,9 +193,8 @@ def build_dataset(
Build complete training dataset from all ML decision files.
Phase 2 additions:
- Scans Forge, PPO, and DeepSeek (ds) JSONL files
- Scans both Forge and PPO JSONL files
- Applies source_weights for configurable mixing
(default: ds=4.0 to oversample high-quality DeepSeek decisions)
- Filters PPO data by min_reward_threshold
- Tags each sample with its source
@@ -211,15 +202,14 @@ def build_dataset(
results_dir: Path to results/ directory containing JSONL files
embeddings_dir: Path to embeddings/ directory (default: auto-detect)
max_samples: Cap total samples (None = unlimited)
source_weights: Dict of source → sampling weight
(default: forge=1.0, ppo=0.0, ds=4.0)
source_weights: Dict of source → sampling weight (default: forge=1.0, ppo=0.5)
min_reward_threshold: Min episode_return for PPO data (default: 0.0)
Returns:
Dict with keys: states, labels, game_ids, outcomes, playstyles, sources
"""
if source_weights is None:
source_weights = {"forge": 1.0, "ppo": 0.0, "ds": 4.0}
source_weights = {"forge": 1.0, "ppo": 0.0}
# Load card embeddings
card_index = CardEmbeddingIndex(embeddings_dir)
@@ -235,7 +225,7 @@ def build_dataset(
encoder = StateEncoder(card_index)
# --- Phase 2 Task 1: Discover files from all sources ---
# --- Phase 2 Task 1: Discover files from both sources ---
source_files = _discover_jsonl_files(results_dir)
if not source_files:
logger.error("No ML decision files found in %s", results_dir)
@@ -513,11 +503,7 @@ def main():
)
parser.add_argument(
"--ppo-weight", type=float, default=0.0,
help="Sampling weight for PPO self-play data (default: 0.0, disabled)",
)
parser.add_argument(
"--ds-weight", type=float, default=4.0,
help="Sampling weight for DeepSeek decision data (default: 4.0, ~20%% effective share)",
help="Sampling weight for PPO self-play data (default: 0.0, Forge-only)",
)
parser.add_argument(
"--min-reward", type=float, default=0.0,
@@ -529,7 +515,6 @@ def main():
source_weights = {
"forge": args.forge_weight,
"ppo": args.ppo_weight,
"ds": args.ds_weight,
}
# Build dataset
+1 -24
View File
@@ -167,24 +167,6 @@ class CardEmbeddingIndex:
return self._loaded
def _resolve_cmdr_dmg(raw) -> int:
"""Collapse cmdr_dmg to a scalar integer regardless of source format.
Forge sends cmdr_dmg as a dict keyed by opponent seat string, e.g.
{"0": 14, "2": 7}. _build_encoder_snapshot already sums this before
passing to predict(), but the live Forge IPC path (and legacy JSONL)
may send the raw dict. Summing all values is correct for Commander:
the total commander damage received from all opponents is what matters
for the life-loss threshold (21).
"""
if isinstance(raw, dict):
return sum(int(v) for v in raw.values())
try:
return int(raw)
except (TypeError, ValueError):
return 0
class StateEncoder:
"""
Encodes a decision snapshot JSON dict into a fixed-size numpy vector.
@@ -259,10 +241,6 @@ class StateEncoder:
Index 7 priority for total_power:
1. p['total_power'] — real Forge value from Step 4 / _build_encoder_snapshot()
2. p['creatures'] * 3 — legacy heuristic for old JSONL snapshots
cmdr_dmg is resolved via _resolve_cmdr_dmg() which handles both the
live Forge format (dict keyed by opponent seat) and the pre-collapsed
int from _build_encoder_snapshot / JSONL training snapshots.
"""
features = []
@@ -272,8 +250,7 @@ class StateEncoder:
features.append(life / 40.0)
# idx 1: commander damage taken
# _resolve_cmdr_dmg handles dict (live Forge IPC) and int (JSONL/pre-collapsed)
cmdr_dmg = _resolve_cmdr_dmg(p.get("cmdr_dmg", 0))
cmdr_dmg = p.get("cmdr_dmg", 0)
features.append(cmdr_dmg / 21.0)
# idx 2: mana available
+13 -48
View File
@@ -52,44 +52,14 @@ from ml.config.scope import (
)
from ml.encoder.state_encoder import CardEmbeddingIndex, StateEncoder
# Unique logger name so log lines are attributable to this module specifically
logger = logging.getLogger("ml.serving.policy_server")
def _unwrap_logits(raw):
"""
Normalise whatever self.model() returns to a plain logits tensor.
PolicyNetwork.forward() returns a raw tensor, but the model may be
wrapped (DataParallel, torch.compile) or accidentally swapped for
PolicyValueNetwork whose forward_with_value() returns (logits, value).
A dict return would cause 'dict / float' TypeError on the temperature
division -- guard against all three cases here.
"""
if isinstance(raw, (tuple, list)):
# (logits, value) from PolicyValueNetwork or similar
return raw[0]
if isinstance(raw, dict):
# e.g. {"logits": tensor, "value": tensor}
for key in ("logits", "policy", "action_logits"):
if key in raw:
return raw[key]
# Fallback: grab the first tensor value in the dict
for v in raw.values():
if isinstance(v, torch.Tensor):
return v
raise TypeError(
f"model() returned a dict with no recognisable logits key: {list(raw.keys())}"
)
# Plain tensor -- the normal case
return raw
logger = logging.getLogger("ml.serving")
class PolicyInferenceService:
"""
Loads a trained PolicyNetwork and provides action predictions.
Thread-safe -- uses torch.no_grad() for inference.
Thread-safe — uses torch.no_grad() for inference.
Designed to be embedded in lab_api.py or run standalone.
"""
@@ -130,7 +100,7 @@ class PolicyInferenceService:
"""
if not TORCH_AVAILABLE:
self._load_error = "PyTorch not installed"
logger.error("PyTorch not installed -- cannot serve policy")
logger.error("PyTorch not installed — cannot serve policy")
return False
# 1. Load card embeddings
@@ -176,7 +146,7 @@ class PolicyInferenceService:
except Exception as e:
self._load_error = str(e)
logger.error("Failed to load checkpoint: %s", e, exc_info=True)
logger.error("Failed to load checkpoint: %s", e)
return False
def reload(self, checkpoint_path: str = None) -> bool:
@@ -208,7 +178,7 @@ class PolicyInferenceService:
except Exception as e:
self._load_error = str(e)
logger.error("Hot-reload failed: %s", e, exc_info=True)
logger.error("Hot-reload failed: %s", e)
return False
def predict(
@@ -254,10 +224,7 @@ class PolicyInferenceService:
# Run inference
with torch.no_grad():
raw_output = self.model(state_tensor)
# Guard: unwrap tuple/dict returns (DataParallel, torch.compile,
# or accidental PolicyValueNetwork swap) before any arithmetic.
logits = _unwrap_logits(raw_output)
logits = self.model(state_tensor)
if greedy:
action_idx = logits.argmax(dim=-1).item()
@@ -287,7 +254,7 @@ class PolicyInferenceService:
except Exception as e:
elapsed_ms = (time.time() - t_start) * 1000
logger.error("Inference error: %s", e, exc_info=True)
logger.error("Inference error: %s", e)
return {
"error": str(e),
"inference_ms": round(elapsed_ms, 2),
@@ -319,9 +286,7 @@ class PolicyInferenceService:
# Batch inference
with torch.no_grad():
raw_output = self.model(state_tensor)
# Same guard as predict() -- unwrap before softmax/argmax.
logits = _unwrap_logits(raw_output)
logits = self.model(state_tensor)
probs = torch.softmax(logits, dim=-1).cpu().numpy()
if greedy:
@@ -347,7 +312,7 @@ class PolicyInferenceService:
)
except Exception as e:
logger.error("Batch inference error: %s", e, exc_info=True)
logger.error("Batch inference error: %s", e)
results = [{"error": str(e)}] * len(snapshots)
return results
@@ -366,9 +331,9 @@ class PolicyInferenceService:
}
# ==========================================================
# ══════════════════════════════════════════════════════════
# Standalone FastAPI Server
# ==========================================================
# ══════════════════════════════════════════════════════════
def create_standalone_app():
"""Create a standalone FastAPI app for the policy server."""
@@ -376,7 +341,7 @@ def create_standalone_app():
from pydantic import BaseModel
app = FastAPI(
title="Commander AI Lab -- Policy Server",
title="Commander AI Lab — Policy Server",
description="Serves macro-action predictions from a trained policy network",
version="1.0.0",
)
@@ -459,7 +424,7 @@ def main():
import uvicorn
parser = argparse.ArgumentParser(
description="Commander AI Lab -- Policy Inference Server"
description="Commander AI Lab — Policy Inference Server"
)
parser.add_argument("--port", type=int, default=8090)
parser.add_argument("--host", default="127.0.0.1")
+10 -153
View File
@@ -34,7 +34,6 @@ from ml.training.reward import (
compute_intermediate_reward,
compute_terminal_reward,
)
from ml.training.decision_exporter import DecisionExporter, ExporterConfig
logger = logging.getLogger("ml.forge_episode_generator")
@@ -52,8 +51,6 @@ class ForgeTransition:
log_prob: float
value: float
done: bool
# Raw snapshot retained so the exporter can reconstruct game-state context
snapshot: Optional[Dict[str, Any]] = None
@dataclass
@@ -64,8 +61,6 @@ class ForgeEpisode:
winner: Optional[int] = None
total_turns: int = 0
deck_names: List[str] = field(default_factory=list)
agent_seat: int = 0
playstyle: str = "midrange"
@property
def length(self) -> int:
@@ -75,10 +70,6 @@ class ForgeEpisode:
def total_reward(self) -> float:
return sum(t.reward for t in self.transitions)
@property
def won(self) -> bool:
return self.winner == self.agent_seat
# ══════════════════════════════════════════════════════════
# JSONL Parser — reads Forge ML decision snapshots
@@ -104,44 +95,9 @@ def parse_forge_jsonl(path: Path) -> List[Dict[str, Any]]:
return snapshots
def _make_minimal_state(snap: Dict[str, Any]) -> Dict[str, Any]:
"""Build a minimal prev/curr state dict from a Forge snapshot.
compute_intermediate_reward() expects a dict with a 'players' list
where each player has 'life_total', 'cards_in_hand',
'creatures_on_battlefield', etc. Forge snapshots carry a 'players'
array directly; we forward it as-is and fall back to scalar fields
when the array is absent.
"""
if "players" in snap:
return {"players": snap["players"]}
# Fallback: reconstruct a two-player view from flat snapshot fields
agent_seat = snap.get("active_seat", 0)
opp_seat = 1 - agent_seat
players = [None, None]
def _player(life_key: str, hand_key: str, creatures_key: str) -> Dict:
return {
"life_total": snap.get(life_key, 40),
"cards_in_hand": snap.get(hand_key, 0),
"creatures_on_battlefield": snap.get(creatures_key, 0),
"cards_in_graveyard": 0,
"mana_available": snap.get("mana_available", 0),
"commander_damage_taken": 0,
"total_power_on_board": 0,
}
players[agent_seat] = _player("agent_life", "agent_hand_size", "agent_creatures")
players[opp_seat] = _player("opp_life", "opp_hand_size", "opp_creatures")
return {"players": players}
def snapshots_to_episode(
snapshots: List[Dict[str, Any]],
reward_config: Optional[RewardConfig] = None,
agent_seat: int = 0,
playstyle: str = "midrange",
) -> ForgeEpisode:
"""Convert a sequence of Forge snapshots into a ForgeEpisode.
@@ -155,8 +111,6 @@ def snapshots_to_episode(
episode = ForgeEpisode(
game_id=first.get("game_id", "unknown"),
deck_names=first.get("deck_names", []),
agent_seat=agent_seat,
playstyle=playstyle,
)
rc = reward_config or RewardConfig()
@@ -176,26 +130,20 @@ def snapshots_to_episode(
except (ValueError, KeyError):
action_idx = ACTION_TO_IDX[MacroAction.PASS]
# Reward — use correct reward.py signatures
# Reward
is_done = i == len(snapshots) - 1
if is_done and "outcome" in snap:
outcome = snap["outcome"]
reward = compute_terminal_reward(
won=outcome.get("won", False),
draw=outcome.get("draw", False),
timeout=outcome.get("timeout", False),
won=snap["outcome"].get("won", False),
turns=snap.get("turn", 1),
life_remaining=snap["outcome"].get("life_remaining", 0),
config=rc,
)
else:
# Build minimal prev/curr dicts for intermediate reward
prev_snap = snapshots[i - 1] if i > 0 else snap
prev_state = _make_minimal_state(prev_snap)
curr_state = _make_minimal_state(snap)
reward = compute_intermediate_reward(
prev_state=prev_state,
curr_state=curr_state,
action_taken=action_label,
agent_seat=agent_seat,
life_delta=snap.get("life_delta", 0),
cards_drawn=snap.get("cards_drawn", 0),
creatures_played=snap.get("creatures_played", 0),
config=rc,
)
@@ -206,7 +154,6 @@ def snapshots_to_episode(
log_prob=snap.get("log_prob", 0.0),
value=snap.get("value", 0.0),
done=is_done,
snapshot=snap,
))
episode.total_turns = snapshots[-1].get("turn", len(snapshots))
@@ -216,61 +163,6 @@ def snapshots_to_episode(
return episode
# ══════════════════════════════════════════════════════════
# DecisionExporter adapter for Forge episodes
# ══════════════════════════════════════════════════════════
def _export_forge_episode(episode: ForgeEpisode, exporter: DecisionExporter) -> None:
"""Feed a completed ForgeEpisode into the DecisionExporter.
Translates each ForgeTransition back into the game_state_snapshot
format expected by DecisionExporter.record_step(), then finalises
the episode so the exporter can apply its win/length gates.
The raw snapshot stored on each ForgeTransition is used directly
when available; otherwise a minimal dict is synthesised from the
transition's action index and reward so the schema is always valid.
"""
exporter.begin_episode(
agent_seat=episode.agent_seat,
playstyle=episode.playstyle,
)
for t in episode.transitions:
if t.snapshot is not None:
game_state = _make_minimal_state(t.snapshot)
# Carry through turn/phase/active_seat if present
game_state["turn"] = t.snapshot.get("turn", 1)
game_state["phase"] = t.snapshot.get("phase", "main_1")
game_state["active_seat"] = t.snapshot.get("active_seat", episode.agent_seat)
else:
# Minimal fallback — exporter only needs players list for schema
game_state = {
"turn": 1,
"phase": "main_1",
"active_seat": episode.agent_seat,
"players": [
{"life_total": 40, "cards_in_hand": 0, "creatures_on_battlefield": 0,
"cards_in_graveyard": 0, "mana_available": 0,
"commander_damage_taken": 0, "total_power_on_board": 0, "commander_tax": 0},
{"life_total": 40, "cards_in_hand": 0, "creatures_on_battlefield": 0,
"cards_in_graveyard": 0, "mana_available": 0,
"commander_damage_taken": 0, "total_power_on_board": 0, "commander_tax": 0},
],
}
exporter.record_step(
game_state_snapshot=game_state,
action_idx=t.action,
reward=t.reward,
)
exporter.end_episode(
won=episode.won,
episode_return=episode.total_reward,
)
# ══════════════════════════════════════════════════════════
# Async Episode Queue (producer-consumer)
# ══════════════════════════════════════════════════════════
@@ -379,7 +271,6 @@ async def ppo_consumer(
queue: ForgeEpisodeQueue,
buffer_size: int = 64,
on_batch_ready=None,
exporter: Optional[DecisionExporter] = None,
) -> int:
"""Consumer coroutine: pulls episodes from the queue and batches
them for PPO training updates.
@@ -388,11 +279,6 @@ async def ppo_consumer(
queue: ForgeEpisodeQueue to consume from
buffer_size: number of episodes per training batch
on_batch_ready: callback(episodes) when a batch is full
exporter: Optional DecisionExporter — when provided, every
consumed episode is fed into the exporter so winning
Forge games accumulate in the distillation JSONL pool.
Call exporter.flush() after the pipeline completes to
write the JSONL file.
Returns total episodes consumed.
"""
@@ -406,14 +292,6 @@ async def ppo_consumer(
break
continue
# Feed into distillation exporter (win-gate applied inside exporter)
if exporter is not None:
try:
_export_forge_episode(episode, exporter)
except Exception as exc:
logger.warning("[CONSUMER] Exporter error for episode %s: %s",
episode.game_id, exc)
batch.append(episode)
total_consumed += 1
@@ -444,24 +322,12 @@ async def run_forge_pipeline(
max_queue: int = 256,
on_batch_ready=None,
reward_config: Optional[RewardConfig] = None,
exporter: Optional[DecisionExporter] = None,
) -> Dict[str, Any]:
) -> Dict[str, int]:
"""Run the full Forge producer → PPO consumer pipeline.
The Forge Java batch must be started separately (via forge_runner.py
or MultiThreadBatchRunner). This function handles the Python side:
reading JSONL output and feeding episodes into the PPO trainer.
If an exporter is provided, winning Forge episodes are recorded and
flushed to a PPO JSONL file at the end of the pipeline run. The
output path is returned in the stats dict under "exporter_file".
Example::
from ml.training.decision_exporter import DecisionExporter, ExporterConfig
exporter = DecisionExporter(ExporterConfig(model_version="gen-1"))
stats = await run_forge_pipeline(num_games=128, exporter=exporter)
print(stats["exporter_file"]) # data/results/ml-decisions-ppo-<id>.jsonl
"""
queue = ForgeEpisodeQueue(max_size=max_queue)
@@ -470,25 +336,16 @@ async def run_forge_pipeline(
reward_config=reward_config)
)
consumer_task = asyncio.create_task(
ppo_consumer(queue, buffer_size, on_batch_ready, exporter=exporter)
ppo_consumer(queue, buffer_size, on_batch_ready)
)
produced = await producer_task
queue.close()
consumed = await consumer_task
# Flush exporter to disk and capture output path
exporter_file = None
if exporter is not None:
exporter_file = exporter.flush()
if exporter_file:
logger.info("[PIPELINE] Distillation export: %s stats=%s",
exporter_file, exporter.stats)
stats: Dict[str, Any] = {
stats = {
"produced": produced,
"consumed": consumed,
"exporter_file": exporter_file,
**queue.stats,
}
logger.info("[PIPELINE] Complete: %s", stats)
+131 -154
View File
@@ -1,154 +1,131 @@
"""Runtime configuration, state classes, and static data for Commander AI Lab."""
from __future__ import annotations
import json
import logging
import os
import subprocess
from datetime import datetime
from pathlib import Path
from typing import Optional
# ── .env bootstrap ────────────────────────────────────────────
# Load .env automatically so plain `python script.py` and bare uvicorn
# both pick up FORGE_DIR, PRECON_DIR, etc. without a manual load_dotenv
# call at every entry point. override=False means real env vars always win.
try:
from dotenv import load_dotenv as _load_dotenv
_here = Path(__file__).resolve().parent
for _candidate in [_here, _here.parent, _here.parent.parent]:
_env_file = _candidate / ".env"
if _env_file.is_file():
_load_dotenv(dotenv_path=_env_file, override=False)
break
except ImportError:
pass # python-dotenv not installed; rely on real environment variables
# ─────────────────────────────────────────────────────────────
log = logging.getLogger("commander_ai_lab.api")
# ══════════════════════════════════════════════════════════════
# Configuration
# ══════════════════════════════════════════════════════════════
class Config:
"""Runtime configuration -- set via CLI args or env vars."""
forge_jar: str = ""
forge_dir: str = ""
forge_decks_dir: str = ""
lab_jar: str = ""
precon_dir: str = ""
results_dir: str = "results"
port: int = 8080
ximilar_api_key: str = ""
pplx_api_key: str = ""
anthropic_api_key: str = ""
CFG = Config()
# Pre-populate from environment so uvicorn/ASGI mode works without CLI args.
# CLI args (lab_api.py main()) will override these if provided.
CFG.anthropic_api_key = os.environ.get("ANTHROPIC_API_KEY", "")
CFG.ximilar_api_key = os.environ.get("XIMILAR_API_KEY", "")
CFG.pplx_api_key = os.environ.get("PPLX_API_KEY", "")
CFG.forge_jar = os.environ.get("FORGE_JAR", "")
CFG.forge_dir = os.environ.get("FORGE_DIR", "")
CFG.lab_jar = os.environ.get("LAB_JAR", "")
# PRECON_DIR / PRECON_DECKS_DIR are aliases -- prefer PRECON_DIR
CFG.precon_dir = os.environ.get("PRECON_DIR") or os.environ.get("PRECON_DECKS_DIR", "")
CFG.forge_decks_dir = os.environ.get("FORGE_DECKS_DIR", "")
def validate_forge_config() -> None:
"""Warn clearly at startup if FORGE_DIR is misconfigured."""
if not CFG.forge_dir:
log.warning("FORGE_DIR not set -- Forge card enrichment disabled. "
"Set FORGE_DIR to your forge-repo root or forge-gui directory.")
return
base = Path(CFG.forge_dir)
a = base / "forge-gui" / "res" / "cardsfolder"
b = base / "res" / "cardsfolder"
if not a.is_dir() and not b.is_dir():
log.warning(
"FORGE_DIR=%s is set but cardsfolder not found at:\n"
" %s\n %s\n"
"Check that FORGE_DIR points to forge-repo root or forge-gui/.",
CFG.forge_dir, a, b
)
else:
resolved = a if a.is_dir() else b
log.info("Forge cardsfolder confirmed at %s", resolved)
# ══════════════════════════════════════════════════════════════
# In-Memory State
# ══════════════════════════════════════════════════════════════
class BatchState:
def __init__(self, batch_id: str, total_games: int, threads: int):
self.batch_id = batch_id
self.total_games = total_games
self.threads = threads
self.completed_games = 0
self.running = True
self.start_time = datetime.now()
self.elapsed_ms = 0
self.result_path: Optional[str] = None
self.error: Optional[str] = None
self.process: Optional[subprocess.Popen] = None
self.log_lines: list = []
self.sims_per_sec: float = 0.0
import asyncio as _asyncio
active_batches: dict[str, BatchState] = {}
active_batches_lock = _asyncio.Lock()
COMMANDER_META: dict = {}
BUILTIN_COMMANDERS: dict = {
"Edgar Markov": [{"source": "edhrec", "archetype": "aggro", "colorIdentity": ["W","B","R"]}],
"Atraxa, Praetors' Voice": [{"source": "edhrec", "archetype": "midrange", "colorIdentity": ["W","U","B","G"]}],
"Korvold, Fae-Cursed King": [{"source": "edhrec", "archetype": "combo", "colorIdentity": ["B","R","G"]}],
"Muldrotha, the Gravetide": [{"source": "edhrec", "archetype": "midrange", "colorIdentity": ["U","B","G"]}],
"The Ur-Dragon": [{"source": "edhrec", "archetype": "midrange", "colorIdentity": ["W","U","B","R","G"]}],
"Yuriko, the Tiger's Shadow": [{"source": "edhrec", "archetype": "aggro", "colorIdentity": ["U","B"]}],
"Krenko, Mob Boss": [{"source": "edhrec", "archetype": "aggro", "colorIdentity": ["R"]}],
"Meren of Clan Nel Toth": [{"source": "edhrec", "archetype": "midrange", "colorIdentity": ["B","G"]}],
"Prossh, Skyraider of Kher": [{"source": "edhrec", "archetype": "combo", "colorIdentity": ["B","R","G"]}],
"Kaalia of the Vast": [{"source": "edhrec", "archetype": "aggro", "colorIdentity": ["W","B","R"]}],
"Talrand, Sky Summoner": [{"source": "edhrec", "archetype": "control", "colorIdentity": ["U"]}],
"Omnath, Locus of Creation": [{"source": "edhrec", "archetype": "combo", "colorIdentity": ["W","U","R","G"]}],
"Teysa Karlov": [{"source": "edhrec", "archetype": "combo", "colorIdentity": ["W","B"]}],
"Lathril, Blade of the Elves": [{"source": "edhrec", "archetype": "aggro", "colorIdentity": ["B","G"]}],
"Breya, Etherium Shaper": [{"source": "edhrec", "archetype": "combo", "colorIdentity": ["W","U","B","R"]}],
}
def load_commander_meta() -> None:
"""Load commander meta mapping from file or fall back to builtins."""
meta_path = Path(__file__).parent.parent / "commander-meta.json"
if meta_path.exists():
try:
with open(meta_path, "r", encoding="utf-8") as f:
COMMANDER_META.clear()
COMMANDER_META.update(json.load(f))
log.info(f" Meta: Loaded {len(COMMANDER_META)} commanders from {meta_path}")
return
except Exception as e:
log.warning(f" WARNING: Failed to load commander-meta.json: {e}")
COMMANDER_META.clear()
COMMANDER_META.update(BUILTIN_COMMANDERS)
log.info(f" Meta: {len(COMMANDER_META)} built-in commanders")
# ══════════════════════════════════════════════════════════════
# AI Profiles
# ══════════════════════════════════════════════════════════════
AI_PROFILES = {
"default": {"name": "default", "description": "Balanced — Forge's default AI behavior", "aggression": 0.5, "cardAdvantage": 0.5, "removalPriority": 0.5, "boardPresence": 0.5, "comboPriority": 0.3, "patience": 0.5},
"aggro": {"name": "aggro", "description": "Aggressive — attacks early, prioritizes damage", "aggression": 0.9, "cardAdvantage": 0.3, "removalPriority": 0.3, "boardPresence": 0.8, "comboPriority": 0.1, "patience": 0.1},
"control": {"name": "control", "description": "Control — defensive, removal-heavy, card advantage", "aggression": 0.2, "cardAdvantage": 0.9, "removalPriority": 0.9, "boardPresence": 0.3, "comboPriority": 0.4, "patience": 0.9},
"combo": {"name": "combo", "description": "Combo — ramps, digs for pieces, assembles combos", "aggression": 0.2, "cardAdvantage": 0.8, "removalPriority": 0.4, "boardPresence": 0.3, "comboPriority": 0.95, "patience": 0.7},
"midrange": {"name": "midrange", "description": "Midrange — flexible, strong board presence, value-oriented", "aggression": 0.5, "cardAdvantage": 0.6, "removalPriority": 0.6, "boardPresence": 0.7, "comboPriority": 0.3, "patience": 0.5},
}
"""Runtime configuration, state classes, and static data for Commander AI Lab."""
from __future__ import annotations
import json
import logging
import os
import subprocess
from datetime import datetime
from pathlib import Path
from typing import Optional
log = logging.getLogger("commander_ai_lab.api")
# ══════════════════════════════════════════════════════════════
# Configuration
# ══════════════════════════════════════════════════════════════
class Config:
"""Runtime configuration -- set via CLI args or env vars."""
forge_jar: str = ""
forge_dir: str = ""
forge_decks_dir: str = ""
lab_jar: str = ""
precon_dir: str = ""
results_dir: str = "results"
port: int = 8080
ximilar_api_key: str = ""
pplx_api_key: str = ""
anthropic_api_key: str = ""
CFG = Config()
# Pre-populate from env so ASGI mode (uvicorn lab_api:app) works without main()
CFG.anthropic_api_key = os.environ.get("ANTHROPIC_API_KEY", "")
def validate_forge_config() -> None:
"""Warn clearly at startup if FORGE_DIR is misconfigured."""
if not CFG.forge_dir:
log.warning("FORGE_DIR not set -- Forge card enrichment disabled. "
"Set FORGE_DIR to your forge-repo root or forge-gui directory.")
return
base = Path(CFG.forge_dir)
a = base / "forge-gui" / "res" / "cardsfolder"
b = base / "res" / "cardsfolder"
if not a.is_dir() and not b.is_dir():
log.warning(
"FORGE_DIR=%s is set but cardsfolder not found at:\n"
" %s\n %s\n"
"Check that FORGE_DIR points to forge-repo root or forge-gui/.",
CFG.forge_dir, a, b
)
else:
resolved = a if a.is_dir() else b
log.info("Forge cardsfolder confirmed at %s", resolved)
CFG.ximilar_api_key = os.environ.get("XIMILAR_API_KEY", "")
CFG.pplx_api_key = os.environ.get("PPLX_API_KEY", "")
# ══════════════════════════════════════════════════════════════
# In-Memory State
# ══════════════════════════════════════════════════════════════
class BatchState:
def __init__(self, batch_id: str, total_games: int, threads: int):
self.batch_id = batch_id
self.total_games = total_games
self.threads = threads
self.completed_games = 0
self.running = True
self.start_time = datetime.now()
self.elapsed_ms = 0
self.result_path: Optional[str] = None
self.error: Optional[str] = None
self.process: Optional[subprocess.Popen] = None
self.log_lines: list = []
self.sims_per_sec: float = 0.0
import asyncio as _asyncio
active_batches: dict[str, BatchState] = {}
active_batches_lock = _asyncio.Lock()
COMMANDER_META: dict = {}
BUILTIN_COMMANDERS: dict = {
"Edgar Markov": [{"source": "edhrec", "archetype": "aggro", "colorIdentity": ["W","B","R"]}],
"Atraxa, Praetors' Voice": [{"source": "edhrec", "archetype": "midrange", "colorIdentity": ["W","U","B","G"]}],
"Korvold, Fae-Cursed King": [{"source": "edhrec", "archetype": "combo", "colorIdentity": ["B","R","G"]}],
"Muldrotha, the Gravetide": [{"source": "edhrec", "archetype": "midrange", "colorIdentity": ["U","B","G"]}],
"The Ur-Dragon": [{"source": "edhrec", "archetype": "midrange", "colorIdentity": ["W","U","B","R","G"]}],
"Yuriko, the Tiger's Shadow": [{"source": "edhrec", "archetype": "aggro", "colorIdentity": ["U","B"]}],
"Krenko, Mob Boss": [{"source": "edhrec", "archetype": "aggro", "colorIdentity": ["R"]}],
"Meren of Clan Nel Toth": [{"source": "edhrec", "archetype": "midrange", "colorIdentity": ["B","G"]}],
"Prossh, Skyraider of Kher": [{"source": "edhrec", "archetype": "combo", "colorIdentity": ["B","R","G"]}],
"Kaalia of the Vast": [{"source": "edhrec", "archetype": "aggro", "colorIdentity": ["W","B","R"]}],
"Talrand, Sky Summoner": [{"source": "edhrec", "archetype": "control", "colorIdentity": ["U"]}],
"Omnath, Locus of Creation": [{"source": "edhrec", "archetype": "combo", "colorIdentity": ["W","U","R","G"]}],
"Teysa Karlov": [{"source": "edhrec", "archetype": "combo", "colorIdentity": ["W","B"]}],
"Lathril, Blade of the Elves": [{"source": "edhrec", "archetype": "aggro", "colorIdentity": ["B","G"]}],
"Breya, Etherium Shaper": [{"source": "edhrec", "archetype": "combo", "colorIdentity": ["W","U","B","R"]}],
}
def load_commander_meta() -> None:
"""Load commander meta mapping from file or fall back to builtins."""
meta_path = Path(__file__).parent.parent / "commander-meta.json"
if meta_path.exists():
try:
with open(meta_path, "r", encoding="utf-8") as f:
COMMANDER_META.clear()
COMMANDER_META.update(json.load(f))
log.info(f" Meta: Loaded {len(COMMANDER_META)} commanders from {meta_path}")
return
except Exception as e:
log.warning(f" WARNING: Failed to load commander-meta.json: {e}")
COMMANDER_META.clear()
COMMANDER_META.update(BUILTIN_COMMANDERS)
log.info(f" Meta: {len(COMMANDER_META)} built-in commanders")
# ══════════════════════════════════════════════════════════════
# AI Profiles
# ══════════════════════════════════════════════════════════════
AI_PROFILES = {
"default": {"name": "default", "description": "Balanced \u2014 Forge's default AI behavior", "aggression": 0.5, "cardAdvantage": 0.5, "removalPriority": 0.5, "boardPresence": 0.5, "comboPriority": 0.3, "patience": 0.5},
"aggro": {"name": "aggro", "description": "Aggressive \u2014 attacks early, prioritizes damage", "aggression": 0.9, "cardAdvantage": 0.3, "removalPriority": 0.3, "boardPresence": 0.8, "comboPriority": 0.1, "patience": 0.1},
"control": {"name": "control", "description": "Control \u2014 defensive, removal-heavy, card advantage", "aggression": 0.2, "cardAdvantage": 0.9, "removalPriority": 0.9, "boardPresence": 0.3, "comboPriority": 0.4, "patience": 0.9},
"combo": {"name": "combo", "description": "Combo \u2014 ramps, digs for pieces, assembles combos", "aggression": 0.2, "cardAdvantage": 0.8, "removalPriority": 0.4, "boardPresence": 0.3, "comboPriority": 0.95, "patience": 0.7},
"midrange": {"name": "midrange", "description": "Midrange \u2014 flexible, strong board presence, value-oriented", "aggression": 0.5, "cardAdvantage": 0.6, "removalPriority": 0.6, "boardPresence": 0.7, "comboPriority": 0.3, "patience": 0.5},
}
+4
View File
@@ -0,0 +1,4 @@
unzip mtg-commander-lan.zip
cd mtg-commander-lan
npm install
node server.js
+6
View File
@@ -0,0 +1,6 @@
{
"name": "MTG Commander (HTML)",
"lockfileVersion": 3,
"requires": true,
"packages": {}
}
+65 -209
View File
@@ -1,29 +1,11 @@
"""Live game session routes.
Endpoints:
POST /api/game/start -- create and launch a live Forge game session
POST /api/game/action -- submit a human player action (called by HumanActionBar)
GET /api/game/{game_id}/status -- poll session status and last known game state
GET /api/game/{game_id}/actions -- Forge IPC: drain pending human actions
GET /api/game/sessions -- list active sessions (debug)
Forge IPC flow
--------------
1. POST /api/game/start
- Validates seats, resolves deck names
- Picks a playstyle per AI seat from seat_type (e.g. "AI Aggro" -> "aggro")
- Calls run_batch_subprocess(num_games=1, use_learned_policy=True, ...)
which builds the Java command with --policy <style> --policyServer http://localhost:8080
and spawns the Forge JAR in a background thread
- Returns game_id + ws_url immediately (non-blocking)
2. Forge JAR (once launched) calls POST /api/policy/decide on every AI decision
3. Human actions are queued via POST /api/game/action and drained by
GET /api/game/{game_id}/actions (polled by the Forge IPC loop inside the JAR)
4. GET /api/game/{game_id}/status returns live log tail + completion state
POST /api/game/start — create a new live game session (called by LobbySetupModal)
POST /api/game/action — submit a human player action (called by HumanActionBar)
"""
from __future__ import annotations
import asyncio
import logging
import uuid
from typing import List, Optional
@@ -31,39 +13,14 @@ from typing import List, Optional
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
from models.state import BatchState
from services.forge_runner import run_batch_subprocess
log = logging.getLogger("routes.game")
router = APIRouter(tags=["game"])
# ---------------------------------------------------------------------------
# Playstyle mapping: seat_type string -> policy playstyle token
# ---------------------------------------------------------------------------
_PLAYSTYLE_MAP: dict[str, str] = {
"ai aggro": "aggro",
"ai control": "control",
"ai combo": "combo",
"ai political": "political",
"ai midrange": "midrange",
"ai": "midrange", # bare "AI" seat -> midrange default
"human": None, # human seats skipped for policy
}
def _seat_playstyle(seat_type: str) -> Optional[str]:
"""Map a SeatConfig.seat_type string to a policy playstyle token.
Returns None for human seats (no policy needed).
"""
return _PLAYSTYLE_MAP.get(seat_type.lower().strip(), "midrange")
# ---------------------------------------------------------------------------
# ───────────────────────────────────────────────────────────────
# Request / Response models
# ---------------------------------------------------------------------------
# ───────────────────────────────────────────────────────────────
class SeatConfig(BaseModel):
seat_index: int = 0
@@ -74,16 +31,12 @@ class SeatConfig(BaseModel):
class StartGameRequest(BaseModel):
seats: List[SeatConfig] = Field(default_factory=list)
clock: int = Field(default=6000, description="Per-game wall-clock limit in seconds (0 = unlimited)")
use_learned_policy: bool = Field(default=True, description="Route AI decisions through /api/policy/decide")
policy_greedy: bool = Field(default=False, description="Use greedy (argmax) action selection instead of sampling")
class StartGameResponse(BaseModel):
game_id: str
status: str = "started"
ws_url: str
policy_enabled: bool = False
class GameActionRequest(BaseModel):
@@ -101,139 +54,73 @@ class GameActionResponse(BaseModel):
action: str
# ---------------------------------------------------------------------------
# In-memory session store
# ---------------------------------------------------------------------------
# ───────────────────────────────────────────────────────────────
# In-memory session store (replace with DB / Redis for persistence)
# ───────────────────────────────────────────────────────────────
# { game_id: { "seats": [...], "status": "active"|"ended"|"error",
# "batch_state": BatchState|None, "pending_actions": [...] } }
# { game_id: { "seats": [...], "status": "active" | "ended", "pending_actions": [...] } }
_sessions: dict[str, dict] = {}
# ---------------------------------------------------------------------------
# ───────────────────────────────────────────────────────────────
# POST /api/game/start
# ---------------------------------------------------------------------------
# ───────────────────────────────────────────────────────────────
@router.post("/api/game/start", response_model=StartGameResponse)
async def start_game(req: StartGameRequest):
"""Create and launch a live Forge game session.
"""Create a new live game session.
Resolves deck names from the seat config, launches the Forge JAR
as a background subprocess with --policy routing enabled (unless
use_learned_policy=False), and returns a game_id immediately.
Called by Unity's LobbySetupModal after the player configures seats.
Returns a game_id that Unity uses to connect to the WebSocket at
/ws/game/{game_id}.
The Forge JAR will begin calling POST /api/policy/decide for every
AI seat decision as soon as it is up. Human actions are queued via
POST /api/game/action and polled by the JAR via GET /api/game/{id}/actions.
TODO: Wire Forge engine launch here once the IPC layer is ready.
For now, creates a session record and returns the game_id so Unity
can connect and receive state pushes from the Forge IPC client.
"""
if not req.seats:
raise HTTPException(status_code=400, detail="At least one seat is required.")
# Collect deck names from seats that have one, preserving seat order.
decks = [s.deck_name for s in req.seats if s.deck_name.strip()]
if not decks:
raise HTTPException(status_code=400, detail="At least one seat must have a deck_name.")
# Determine playstyle from the first AI seat (the JAR uses a single global
# playstyle for its --policy flag; per-seat styles are a future extension).
policy_style = "midrange"
for seat in req.seats:
ps = _seat_playstyle(seat.seat_type)
if ps is not None: # skip human seats
policy_style = ps
break
game_id = uuid.uuid4().hex
# Build a BatchState so the forge_runner watchdog and progress tracking
# work the same way they do for overnight batch runs.
state = BatchState(batch_id=game_id)
_sessions[game_id] = {
"game_id": game_id,
"seats": [s.dict() for s in req.seats],
"status": "active",
"game_id": game_id,
"seats": [s.dict() for s in req.seats],
"status": "active",
"pending_actions": [],
"batch_state": state,
}
log.info(
"Game session created: game_id=%s seats=%d decks=%s policy=%s greedy=%s",
game_id, len(req.seats), decks, policy_style if req.use_learned_policy else "off",
req.policy_greedy,
)
# Launch Forge subprocess in the background (non-blocking).
# num_games=1 -> single live game, threads=1, no seed.
# clock is passed through from the request (default 6000s for live play).
asyncio.create_task(
_run_and_finalize(
game_id=game_id,
state=state,
decks=decks,
clock=req.clock,
use_learned_policy=req.use_learned_policy,
policy_style=policy_style,
policy_greedy=req.policy_greedy,
)
"Game session created: game_id=%s seats=%d",
game_id,
len(req.seats),
)
return StartGameResponse(
game_id=game_id,
status="started",
ws_url=f"/ws/game/{game_id}",
policy_enabled=req.use_learned_policy,
)
async def _run_and_finalize(
game_id: str,
state: BatchState,
decks: list,
clock: int,
use_learned_policy: bool,
policy_style: str,
policy_greedy: bool,
):
"""Background task: run Forge subprocess then mark session ended."""
try:
await run_batch_subprocess(
state=state,
decks=decks,
num_games=1,
threads=1,
seed=None,
clock=clock,
output_path=f"results/live-{game_id}.json",
use_learned_policy=use_learned_policy,
policy_style=policy_style,
policy_greedy=policy_greedy,
)
except Exception as exc:
log.error("Game %s subprocess error: %s", game_id, exc)
if game_id in _sessions:
_sessions[game_id]["status"] = "error"
return
if game_id in _sessions:
_sessions[game_id]["status"] = "ended" if not state.error else "error"
log.info(
"Game %s finished: status=%s error=%s",
game_id, _sessions[game_id]["status"], state.error or "none",
)
# ---------------------------------------------------------------------------
# ───────────────────────────────────────────────────────────────
# POST /api/game/action
# ---------------------------------------------------------------------------
# ───────────────────────────────────────────────────────────────
@router.post("/api/game/action", response_model=GameActionResponse)
async def game_action(req: GameActionRequest):
"""Submit a human player action during a live game.
Called by Unity's HumanActionBar when the human seat has priority.
The action is queued in the session; the Forge IPC polling loop
drains it via GET /api/game/{game_id}/actions.
Called by Unity's HumanActionBar when seat 0 (human) has priority.
The action is queued in the session's pending_actions list, where
the Forge IPC polling loop will pick it up.
Valid actions:
pass_priority — pass priority to the next player
end_turn — end the current turn
declare_attackers — declare attacking creatures
declare_blockers — declare blocking creatures
select_target — select a target (requires target_id)
"""
valid_actions = {
"pass_priority", "end_turn",
@@ -255,73 +142,47 @@ async def game_action(req: GameActionRequest):
session = _sessions.get(req.game_id)
if session is None:
raise HTTPException(status_code=404, detail=f"Game session '{req.game_id}' not found.")
raise HTTPException(
status_code=404,
detail=f"Game session '{req.game_id}' not found.",
)
if session["status"] != "active":
raise HTTPException(
status_code=409,
detail=f"Game '{req.game_id}' is not active (status={session['status']}).",
detail=f"Game session '{req.game_id}' is not active (status={session['status']}).",
)
session["pending_actions"].append({
"seat": req.seat,
"action": req.action,
action_record = {
"seat": req.seat,
"action": req.action,
"target_id": req.target_id,
"extra": req.extra,
})
log.info("Action queued: game_id=%s seat=%d action=%s", req.game_id, req.seat, req.action)
return GameActionResponse(status="ok", game_id=req.game_id, action=req.action)
# ---------------------------------------------------------------------------
# GET /api/game/{game_id}/status
# ---------------------------------------------------------------------------
@router.get("/api/game/{game_id}/status")
async def game_status(game_id: str):
"""Return live status, log tail, and completion info for a game session.
Useful for polling from the frontend or a test script to track
whether Forge has finished launching and started calling /decide.
"""
session = _sessions.get(game_id)
if session is None:
raise HTTPException(status_code=404, detail=f"Game session '{game_id}' not found.")
state: Optional[BatchState] = session.get("batch_state")
log_tail = []
completed = 0
total = 1
error = None
if state:
log_tail = state.log_lines[-20:] # last 20 lines
completed = state.completed_games
total = max(state.total_games, 1)
error = state.error
return {
"game_id": game_id,
"status": session["status"],
"seats": session["seats"],
"progress": {"completed": completed, "total": total},
"log_tail": log_tail,
"error": error,
"pending_actions": len(session["pending_actions"]),
"extra": req.extra,
}
session["pending_actions"].append(action_record)
log.info(
"Action queued: game_id=%s seat=%d action=%s",
req.game_id, req.seat, req.action,
)
return GameActionResponse(
status="ok",
game_id=req.game_id,
action=req.action,
)
# ---------------------------------------------------------------------------
# GET /api/game/{game_id}/actions (Forge IPC polling)
# ---------------------------------------------------------------------------
# ───────────────────────────────────────────────────────────────
# GET /api/game/{game_id}/actions (Forge IPC polling endpoint)
# ───────────────────────────────────────────────────────────────
@router.get("/api/game/{game_id}/actions")
async def poll_actions(game_id: str):
"""Drain and return all pending human actions (consume-once).
"""Drain and return all pending human actions for a game session.
Called by the Forge IPC polling loop to consume human player decisions.
Clears the queue on each call (consume-once semantics).
"""
session = _sessions.get(game_id)
if session is None:
@@ -332,22 +193,17 @@ async def poll_actions(game_id: str):
return {"game_id": game_id, "actions": actions}
# ---------------------------------------------------------------------------
# ───────────────────────────────────────────────────────────────
# GET /api/game/sessions (debug)
# ---------------------------------------------------------------------------
# ───────────────────────────────────────────────────────────────
@router.get("/api/game/sessions")
async def list_sessions():
"""List all tracked game sessions (debug)."""
"""List active game sessions (debug endpoint)."""
return {
"count": len(_sessions),
"sessions": [
{
"game_id": gid,
"status": s["status"],
"seats": len(s["seats"]),
"pending": len(s["pending_actions"]),
}
{"game_id": gid, "status": s["status"], "seats": len(s["seats"])}
for gid, s in _sessions.items()
],
}
-69
View File
@@ -14,8 +14,6 @@ Batch simulation & lab management endpoints:
GET /api/lab/trends/{deck_name}
GET /api/lab/log
GET /api/lab/debug-log
GET /api/lab/precons
GET /api/lab/precons/deck
"""
from __future__ import annotations
@@ -470,73 +468,6 @@ async def get_debug_log():
return {"path": None, "content": "No debug log found. Run a simulation first."}
# ════════════════════════════════════════════════════════════
# Precon deck endpoints (used by lan-client ai-bridge.js)
# ════════════════════════════════════════════════════════════
@router.get("/api/lab/precons")
async def list_precons():
"""Return precon deck metadata for the LAN client deck selector."""
precon_dir = Path(CFG.precon_dir) if CFG.precon_dir else None
if not precon_dir or not precon_dir.is_dir():
log.warning(f"Precon dir not found or not configured: {CFG.precon_dir!r}")
return {"precons": []}
precons = []
for f in sorted(precon_dir.glob("*.dck")):
deck_info = {
"fileName": f.name,
"deckName": f.stem,
"commander": "",
"colors": [],
"set": "",
}
# Extract commander name from the [Commander] section
try:
with open(f, "r", encoding="utf-8") as fh:
in_commander = False
for line in fh:
line = line.strip()
if line == "[Commander]":
in_commander = True
continue
if line.startswith("[") and line.endswith("]"):
in_commander = False
continue
if in_commander:
m = re.match(r"^\d+\s+(.+?)(?:\|.+)?$", line)
if m:
deck_info["commander"] = m.group(1).strip()
break
except Exception as exc:
log.debug(f"Could not parse commander from {f.name}: {exc}")
precons.append(deck_info)
return {"precons": precons}
@router.get("/api/lab/precons/deck")
async def get_precon_deck(fileName: str):
"""Return the full card list for a specific precon .dck file."""
precon_dir = Path(CFG.precon_dir) if CFG.precon_dir else None
if not precon_dir or not precon_dir.is_dir():
raise HTTPException(404, f"Precon directory not configured or missing: {CFG.precon_dir!r}")
# Sanitize — prevent path traversal
safe_name = Path(fileName).name
if not safe_name.endswith(".dck"):
raise HTTPException(400, "fileName must end with .dck")
deck_path = precon_dir / safe_name
if not deck_path.exists():
raise HTTPException(404, f"Precon deck not found: {safe_name}")
try:
deck_data = parse_dck_file(str(deck_path))
return deck_data
except Exception as e:
raise HTTPException(500, f"Failed to parse deck: {e}")
@router.post('/api/lab/start-deepseek')
async def start_batch_deepseek(request: FastAPIRequest, background_tasks: BackgroundTasks):
+7 -37
View File
@@ -1,5 +1,5 @@
"""Commander AI Lab — Policy Decision Routes (Phase 2)
════════════════════════════════════════════════════════
════════════════════════════════════════════════════
Live Forge ↔ policy server IPC endpoints for online training.
These endpoints are purpose-built for the real-time decision loop
where Forge's Java side calls the Python policy server at each
@@ -24,8 +24,7 @@ import numpy as np
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
# Unique logger name so log lines are attributable to this module specifically
logger = logging.getLogger("routes.policy.decide")
logger = logging.getLogger("routes.policy")
router = APIRouter(prefix="/api/policy", tags=["policy"])
@@ -311,10 +310,7 @@ async def decide(req: DecideRequest):
req.snapshot_schema, req.resolved_turn(),
)
except Exception as e:
logger.warning(
"Precomputed vector encode failed — falling back to full encoder",
exc_info=True,
)
logger.warning("Precomputed vector encode failed (%s) — falling back", e)
state_vec = None
else:
state_vec = None
@@ -342,24 +338,6 @@ async def decide(req: DecideRequest):
if "error" in result:
raise HTTPException(500, detail=result["error"])
# ----------------------------------------------------------------
# Probability diagnostic — logs top-5 actions on every decision.
# Remove or downgrade to logger.debug once training looks healthy.
# ----------------------------------------------------------------
probs = result.get("probabilities", {})
if probs:
top5 = sorted(probs.items(), key=lambda kv: kv[1], reverse=True)[:5]
top5_str = ", ".join(f"{a}:{p:.3f}" for a, p in top5)
logger.info(
"[decide] turn=%d phase=%s → %s (conf=%.3f) | top5=[%s] | src=%s",
req.resolved_turn(),
req.phase,
result["action"],
result["confidence"],
top5_str,
vector_source,
)
log_prob = 0.0
try:
conf = result.get("confidence", 0.5)
@@ -395,7 +373,7 @@ async def collect_tuples(req: CollectRequest):
try:
_online_store.add_tuples(req.tuples)
except Exception as e:
logger.error("Failed to store tuples: %s", e, exc_info=True)
logger.error("Failed to store tuples: %s", e)
raise HTTPException(500, detail=str(e))
return {
@@ -424,7 +402,7 @@ async def submit_reward(req: RewardRequest):
winner_seat=req.winner_seat,
)
except Exception as e:
logger.error("Failed to assign reward: %s", e, exc_info=True)
logger.error("Failed to assign reward: %s", e)
raise HTTPException(500, detail=str(e))
return {
@@ -540,24 +518,16 @@ def _infer_from_vector(state_vec: np.ndarray, policy_service, temperature: float
Mirrors the core of PolicyInferenceService.predict() but accepts an
ndarray instead of a snapshot dict, avoiding a second encode() call.
Uses _unwrap_logits (same helper as predict()) to guard against
tuple/dict returns from wrapped or swapped model variants before any
arithmetic on the logits tensor.
"""
import torch
from ml.config.scope import NUM_ACTIONS, IDX_TO_ACTION
from ml.serving.policy_server import _unwrap_logits
t_start = time.time()
try:
state_tensor = torch.from_numpy(state_vec).unsqueeze(0).to(policy_service.device)
with torch.no_grad():
raw_output = policy_service.model(state_tensor)
# Guard: unwrap tuple/dict returns (DataParallel, torch.compile,
# PolicyValueNetwork swap) before temperature division / argmax.
logits = _unwrap_logits(raw_output)
logits = policy_service.model(state_tensor)
if greedy:
action_idx = logits.argmax(dim=-1).item()
@@ -585,7 +555,7 @@ def _infer_from_vector(state_vec: np.ndarray, policy_service, temperature: float
}
except Exception as e:
elapsed_ms = (time.time() - t_start) * 1000
logger.error("Direct inference error in _infer_from_vector: %s", e, exc_info=True)
logger.error("Direct inference error: %s", e)
return {"error": str(e), "inference_ms": round(elapsed_ms, 2)}
-25
View File
@@ -29,31 +29,6 @@ async def list_precons():
return {"precons": PRECON_INDEX} # reads current value every call
@router.get("/api/lab/precons/deck")
async def get_precon_deck(fileName: str):
"""Return the raw decklist content of a precon .dck file.
Query: ?fileName=Elven_Empire.dck
"""
if not fileName:
raise HTTPException(400, "fileName query parameter is required")
# Sanitize: only allow .dck files, no path traversal
if '..' in fileName or '/' in fileName or '\\' in fileName:
raise HTTPException(400, "Invalid fileName")
if not fileName.endswith('.dck'):
raise HTTPException(400, "Only .dck files are supported")
src = _get_precon_dir() / fileName
if not src.exists():
raise HTTPException(404, f"Precon not found: {fileName}")
try:
content = src.read_text(encoding='utf-8')
except OSError as e:
raise HTTPException(500, f"Failed to read deck file: {e}")
return {"fileName": fileName, "decklist": content}
@router.post("/api/lab/precons/install")
async def install_precon(req: dict):
"""Install a precon deck to the Forge decks directory.
-35
View File
@@ -1,35 +0,0 @@
#!/usr/bin/env node
/**
* Generate lan-client/precons.js from precon-decks/precon-index.json
* Usage: node scripts/generate-precons-js.js
*/
const fs = require('fs');
const path = require('path');
const indexPath = path.join(__dirname, '..', 'precon-decks', 'precon-index.json');
const outputPath = path.join(__dirname, '..', 'lan-client', 'precons.js');
const index = JSON.parse(fs.readFileSync(indexPath, 'utf8'));
let js = '// Auto-generated from precon-decks/precon-index.json\n';
js += '// Run: node scripts/generate-precons-js.js to regenerate\n';
js += 'var PRECON_DATA = [\n';
index.forEach(function(p, i) {
const entry = {
id: (p.fileName || p.name || '').replace('.dck', ''),
name: p.name || '',
commander: p.commander || (p.commanders && p.commanders[0]) || '',
set: p.set || '',
fileName: p.fileName || '',
colors: p.colors || [],
year: p.year || 0,
};
js += ' ' + JSON.stringify(entry);
js += (i < index.length - 1) ? ',\n' : '\n';
});
js += '];\n';
fs.writeFileSync(outputPath, js);
console.log(`Generated ${outputPath} with ${index.length} precon entries`);
+7 -26
View File
@@ -13,16 +13,6 @@ from services.database import _get_db_conn, _row_to_dict
log_collect = logging.getLogger("lab.collection")
# Repo root = two levels up from this file (services/deck_service.py)
_REPO_ROOT = Path(__file__).parent.parent
# Repo-relative deck dirs always searched as fallbacks (zero-config support)
_BUILTIN_DECK_DIRS = [
_REPO_ROOT / "precon-decks",
_REPO_ROOT / "sample-decks",
_REPO_ROOT / "imported-decks",
]
_TYPE_PRIORITY = ["Land", "Instant", "Sorcery", "Artifact", "Enchantment", "Planeswalker", "Creature"]
_TYPE_TARGETS = {
@@ -207,7 +197,7 @@ def _save_profile_to_dck(profile: dict) -> Path:
safe_name = "imported_deck"
save_dir = CFG.forge_decks_dir
if not save_dir or not os.path.isdir(save_dir):
save_dir = str(_REPO_ROOT / "imported-decks")
save_dir = os.path.join(Path(__file__).parent.parent, "imported-decks")
os.makedirs(save_dir, exist_ok=True)
out_path = Path(save_dir) / f"{safe_name}.dck"
out_path.write_text(content, encoding="utf-8")
@@ -219,19 +209,15 @@ def _find_dck_file(deck_name: str) -> Optional[Path]:
"""Search known deck directories for a .dck file matching deck_name.
Resolution order:
1. CFG.precon_dir (explicit CLI/env config)
2. CFG.forge_decks_dir (Forge user decks)
1. precon_dir (precon-decks/)
2. forge_decks_dir (Forge user decks)
3. FORGE_DIR/res/decks/commander (Forge bundled commander decks)
4. Repo-relative fallbacks: precon-decks/, sample-decks/, imported-decks/
(always searched so precon decks work with zero configuration)
Within each directory tries:
a. Exact stem match (Elven_Empire.dck)
b. Case-insensitive fuzzy match stripping underscores/spaces
"""
search_dirs: list[Path] = []
# CFG-configured paths (set via CLI args)
search_dirs = []
if CFG.precon_dir and os.path.isdir(CFG.precon_dir):
search_dirs.append(Path(CFG.precon_dir))
if CFG.forge_decks_dir and os.path.isdir(CFG.forge_decks_dir):
@@ -241,11 +227,6 @@ def _find_dck_file(deck_name: str) -> Optional[Path]:
if forge_cmdr.is_dir():
search_dirs.append(forge_cmdr)
# Repo-relative fallbacks -- always active so precon decks need no config
for builtin_dir in _BUILTIN_DECK_DIRS:
if builtin_dir.is_dir() and builtin_dir not in search_dirs:
search_dirs.append(builtin_dir)
target_norm = deck_name.lower().replace("_", "").replace(" ", "")
for d in search_dirs:
@@ -322,9 +303,9 @@ def _load_deck_cards_by_name(deck_name: str) -> list:
Resolution order:
1. SQLite DB (decks built/imported via the Deck Builder UI)
2. .dck file fallback -- searches precon_dir, forge_decks_dir,
FORGE_DIR/res/decks/commander, and repo-relative precon-decks/
sample-decks/ so precon decks work without any configuration.
2. .dck file fallback -- searches precon_dir, forge_decks_dir, and
FORGE_DIR/res/decks/commander so that precon decks work without
needing to be manually imported into the DB first.
"""
# -- 1. DB lookup --
conn = _get_db_conn()
@@ -30,13 +30,9 @@ import java.util.regex.*;
* waits on {@code humanActionQueue}, converts the action to the
* macro-action string expected by /api/policy/decide, and injects it
* via POST /api/policy/override so the policy server returns it.
* 4. AI seats (1+) are intercepted at every Priority event: the session
* calls policyClient.decide() with the current state snapshot and
* immediately POSTs the result to /api/policy/override so Forge uses
* the learned policy instead of its built-in AI.
* 5. Publishes a full state snapshot to the WebSocket frontend after every
* 4. Publishes a full state snapshot to the WebSocket frontend after every
* meaningful Forge output event.
* 6. Falls back to the synthetic stub loop if Forge cannot be started
* 5. Falls back to the synthetic stub loop if Forge cannot be started
* (e.g., missing JAR, wrong Java version).
*
* Zone sync model:
@@ -124,12 +120,6 @@ public class GameSession {
private volatile boolean gameOver = false;
private volatile long elapsedMs = 0;
// Tracks whether policy was injected for the current priority window
// to avoid double-injecting on duplicate log lines.
private volatile int lastPolicyInjectionTurn = -1;
private volatile String lastPolicyInjectionPhase = "";
private volatile int lastPolicyInjectionSeat = -1;
private final int numSeats;
private final int[] life;
private final int[] poison;
@@ -319,10 +309,6 @@ public class GameSession {
watchdog.setDaemon(true);
watchdog.start();
// Connect to policy server before the game loop begins
boolean policyConnected = policyClient.connect();
log("[Session] Policy server connection: " + (policyConnected ? "OK" : "UNAVAILABLE — AI uses Forge built-in"));
// Emit initial state so UI shows a board immediately
onStateChange.accept(buildStateSnapshot());
@@ -340,29 +326,19 @@ public class GameSession {
reader.setDaemon(true);
reader.start();
// Main loop: drain line queue and service human/AI input
// Main loop: drain line queue and service human input
while (!gameOver && running) {
String line = lineQueue.poll(200, TimeUnit.MILLISECONDS);
if (line != null) {
lastActivityEpoch.incrementAndGet();
boolean changed = parseForgeLine(line);
if (changed) onStateChange.accept(buildStateSnapshot());
// Human seat
if (awaitingHumanInput) handleHumanTurn(onStateChange);
} else if (forgeDone.get() && lineQueue.isEmpty()) {
break;
}
}
// Flush online learning tuples and submit reward if game finished
if (gameOver && policyClient.isServerAvailable()) {
double reward = winningSeat != null && winningSeat != 0 ? 1.0 : -0.5;
policyClient.submitReward("game-" + seed, reward);
policyClient.flushCollectedTuples();
log(String.format("[Session] Submitted game reward=%.1f and flushed %d tuples",
reward, policyClient.getPendingTuples()));
}
watchdog.interrupt();
try { forgeProcess.waitFor(10, TimeUnit.SECONDS); } catch (InterruptedException ignored) {}
@@ -456,28 +432,8 @@ public class GameSession {
// Priority
Matcher mPrio = P_PRIORITY.matcher(line);
if (mPrio.find()) {
int seat = clampSeat(Integer.parseInt(mPrio.group(1)) - 1);
priorityPlayer = seat;
priorityPlayer = clampSeat(Integer.parseInt(mPrio.group(1)) - 1);
changed = true;
// ── Policy injection for AI seats ────────────────────────
// Forge doesn't honour --policyServer natively, so we intercept
// every AI priority window here and push the policy decision to
// /api/policy/override before Forge's next read.
if (seat != 0 && policyClient.isServerAvailable()) {
// Deduplicate: only inject once per (turn, phase, seat) window
boolean alreadyInjected =
lastPolicyInjectionTurn == turnNumber
&& lastPolicyInjectionPhase.equals(phase)
&& lastPolicyInjectionSeat == seat;
if (!alreadyInjected) {
lastPolicyInjectionTurn = turnNumber;
lastPolicyInjectionPhase = phase;
lastPolicyInjectionSeat = seat;
injectAiPolicyDecision(seat);
}
}
}
// Life totals
@@ -579,49 +535,6 @@ public class GameSession {
return changed;
}
// ----------------------------------------------------------------
// AI policy injection (real Forge IPC path)
// ----------------------------------------------------------------
/**
* Ask the Python policy server what action AI seat {@code seat} should
* take given the current game state, then POST it to /api/policy/override
* so that the next time Forge calls /api/policy/decide for this seat it
* receives the pre-computed answer without an extra round-trip.
*
* This is the core wiring that was missing: Forge's sim mode does not
* natively call --policyServer, so we intercept every Priority log line
* and drive the decision from the Java side instead.
*/
private void injectAiPolicyDecision(int seat) {
try {
PolicyClient.PolicyDecision decision =
policyClient.decide(GSON.toJson(buildStateSnapshot()), seat);
if (decision == null || decision.action() == null) {
log(String.format("[Policy] seat=%d turn=%d phase=%s → null decision, skipping override",
seat, turnNumber, phase));
return;
}
String action = decision.action();
log(String.format("[Policy] seat=%d turn=%d phase=%s → %s (conf=%.2f)",
seat, turnNumber, phase, action, decision.confidence()));
// Push the decision to the override endpoint so Forge's next
// /api/policy/decide call for this seat returns it immediately.
JsonObject body = new JsonObject();
body.addProperty("seat", seat);
body.addProperty("action", action);
httpPost(policyServerUrl + "/api/policy/override", body.toString());
} catch (Exception e) {
// Non-fatal: Forge falls back to its built-in AI for this window
log(String.format("[Policy] seat=%d override failed (%s) — Forge built-in takes over",
seat, e.getMessage()));
}
}
// ----------------------------------------------------------------
// Human turn handling
// ----------------------------------------------------------------
+63 -474
View File
@@ -341,22 +341,18 @@ input { font-family: inherit; }
border: 1px solid var(--color-border-strong);
border-radius: var(--radius-xl);
padding: 2.5rem;
width: min(860px, 95vw);
max-height: 92vh;
overflow-y: auto;
width: min(640px, 95vw);
box-shadow: var(--shadow-lg);
position: relative;
overflow: hidden;
}
.setup-card::before {
content: '';
position: sticky;
position: absolute;
top: 0; left: 0; right: 0;
display: block;
height: 3px;
margin: -2.5rem -2.5rem 0 -2.5rem;
background: linear-gradient(90deg, var(--p1), var(--p2), var(--p3), var(--p4));
z-index: 1;
}
.setup-title {
@@ -1464,6 +1460,66 @@ body.stack-pick-mode .battlefield-card {
line-height: 1;
}
/* ============================================================
MANA POOL DISPLAY (floating)
============================================================ */
#mana-pool-display {
position: absolute;
z-index: 35;
bottom: 8px;
left: 50%;
transform: translateX(-50%);
background: rgba(10,10,20,0.9);
border: 1px solid var(--color-border-strong);
border-radius: var(--radius-md);
padding: 4px 10px;
display: flex;
align-items: center;
gap: 5px;
font-size: 11px;
color: var(--color-text-muted);
backdrop-filter: blur(6px);
-webkit-backdrop-filter: blur(6px);
}
.mana-pip {
display: inline-flex;
width: 18px; height: 18px;
border-radius: 50%;
align-items: center;
justify-content: center;
font-size: 10px;
font-weight: 700;
line-height: 1;
cursor: pointer;
}
.mana-W { background: #F9FAF4; color: #333; }
.mana-U { background: #0E68AB; color: #fff; }
.mana-B { background: #3a2d1a; color: #aaa; border: 1px solid #555; }
.mana-R { background: #D3202A; color: #fff; }
.mana-G { background: #00733E; color: #fff; }
.mana-C { background: #8C8C8C; color: #fff; }
.mana-empty { color: var(--color-text-faint); font-size: 10px; }
.mana-pool-label {
font-size: 10px;
color: var(--color-text-faint);
margin-right: 3px;
}
.mana-pool-clear-btn {
font-size: 9px;
color: var(--color-text-faint);
background: none;
border: none;
cursor: pointer;
padding: 1px 4px;
border-radius: 3px;
margin-left: 3px;
}
.mana-pool-clear-btn:hover { color: var(--color-error); }
/* ============================================================
TRIGGER STACK PANEL
============================================================ */
@@ -2970,470 +3026,3 @@ kbd {
/* Shortcuts modal */
#shortcuts-modal { z-index: 640; }
/* ============================================================
DECK SELECTOR — 3-Category Tabs
============================================================ */
.deck-assignment-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
@media (max-width: 640px) {
.deck-assignment-grid {
grid-template-columns: 1fr;
}
}
.deck-select-panel {
background: rgba(255,255,255,0.03);
border: 1px solid rgba(255,255,255,0.08);
border-radius: 8px;
padding: 8px 10px;
}
.deck-select-panel-header {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 6px;
}
.player-color-dot {
width: 8px; height: 8px;
border-radius: 50%;
}
.deck-select-player-name {
font-size: 12px;
font-weight: 600;
color: var(--color-text);
}
.deck-select-ai-badge {
font-size: 10px;
background: rgba(91,141,217,0.2);
color: rgba(91,141,217,0.9);
padding: 1px 6px;
border-radius: 3px;
font-weight: 600;
}
.deck-select-ai-note {
font-size: 11px;
color: var(--color-text-faint);
}
.deck-select-status {
font-size: 10px;
color: var(--color-text-faint);
margin-left: auto;
}
.deck-select-status.selected {
color: var(--mtg-gold);
}
.deck-tabs {
display: flex;
gap: 2px;
margin-bottom: 6px;
}
.deck-tab {
flex: 1;
padding: 4px 8px;
font-size: 11px;
background: transparent;
border: 1px solid rgba(255,255,255,0.08);
color: var(--color-text-muted);
cursor: pointer;
border-radius: 4px;
transition: all 0.15s;
}
.deck-tab:hover { background: rgba(255,255,255,0.05); }
.deck-tab.active {
background: rgba(91,141,217,0.15);
border-color: rgba(91,141,217,0.3);
color: var(--color-text);
}
.deck-tab-content {
max-height: 170px;
overflow-y: auto;
}
.deck-filter-row {
display: flex;
gap: 4px;
margin-bottom: 6px;
}
.deck-filter-input {
flex: 1;
font-size: 11px;
padding: 4px 8px;
background: rgba(0,0,0,0.3);
border: 1px solid rgba(255,255,255,0.1);
border-radius: 4px;
color: var(--color-text);
outline: none;
}
.deck-filter-input:focus {
border-color: rgba(91,141,217,0.4);
}
.deck-precon-list {
max-height: 140px;
overflow-y: auto;
}
.deck-set-header {
font-size: 11px;
font-weight: 600;
color: var(--color-text-muted);
padding: 3px 4px;
cursor: pointer;
user-select: none;
}
.deck-set-header:hover { color: var(--color-text); }
.deck-set-arrow {
display: inline-block;
width: 10px;
font-size: 10px;
}
.deck-precon-item {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
padding: 4px 8px 4px 18px;
background: transparent;
border: 1px solid transparent;
border-radius: 4px;
color: var(--color-text-muted);
cursor: pointer;
font-size: 11px;
text-align: left;
transition: all 0.12s;
}
.deck-precon-item:hover {
background: rgba(255,255,255,0.04);
color: var(--color-text);
}
.deck-precon-item.selected {
background: rgba(91,141,217,0.12);
border-color: rgba(91,141,217,0.3);
color: var(--color-text);
}
.deck-precon-cmdr {
font-size: 10px;
color: var(--color-text-faint);
margin-left: auto;
padding-left: 8px;
}
.deck-tab-empty {
padding: 12px 8px;
text-align: center;
font-size: 11px;
color: var(--color-text-faint);
}
.deck-tab-loading {
padding: 12px 8px;
text-align: center;
font-size: 11px;
color: rgba(91,141,217,0.8);
}
.deck-import-textarea {
width: 100%;
min-height: 80px;
font-size: 11px;
font-family: monospace;
padding: 6px 8px;
background: rgba(0,0,0,0.3);
border: 1px solid rgba(255,255,255,0.1);
border-radius: 4px;
color: var(--color-text);
resize: vertical;
}
.backend-status-row {
margin-bottom: 6px;
}
.backend-status {
font-size: 10px;
padding: 2px 8px;
border-radius: 3px;
display: inline-block;
}
.backend-status.disconnected {
color: var(--color-text-faint);
background: rgba(255,255,255,0.03);
}
.backend-status.connected {
color: rgba(91,141,217,0.9);
background: rgba(91,141,217,0.1);
}
.backend-status.connected-ml {
color: rgba(39,174,96,0.9);
background: rgba(39,174,96,0.1);
}
/* ============================================================
ENHANCED PLAYER PANELS
============================================================ */
.epp-container {
margin: 2px 0;
}
.enhanced-player-panel {
background: rgba(0,0,0,0.4);
border: 1px solid rgba(255,255,255,0.08);
border-radius: 6px;
font-size: 11px;
overflow: hidden;
}
.enhanced-player-panel.active-turn {
border-color: rgba(255,255,255,0.15);
box-shadow: 0 0 12px rgba(255,255,255,0.05);
}
.enhanced-player-panel.eliminated {
opacity: 0.5;
filter: grayscale(0.5);
}
.epp-header {
display: flex;
align-items: center;
gap: 5px;
padding: 4px 8px;
cursor: pointer;
user-select: none;
background: rgba(255,255,255,0.02);
}
.epp-header:hover { background: rgba(255,255,255,0.04); }
.epp-collapse-arrow {
font-size: 9px;
width: 10px;
color: var(--color-text-faint);
}
.epp-name-dot {
width: 8px; height: 8px;
border-radius: 50%;
}
.epp-name {
font-weight: 600;
font-size: 11px;
color: var(--color-text);
}
.epp-ai-badge {
font-size: 9px;
background: rgba(91,141,217,0.2);
color: rgba(91,141,217,0.9);
padding: 0 4px;
border-radius: 2px;
}
.epp-life-badge {
margin-left: auto;
font-weight: 700;
font-size: 12px;
color: var(--color-text);
}
.epp-body {
padding: 4px 8px 6px;
}
/* Life Row */
.epp-life-row {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 4px 0;
}
.epp-life-btn {
width: 24px; height: 24px;
border-radius: 50%;
border: 1px solid rgba(255,255,255,0.15);
background: rgba(255,255,255,0.05);
color: var(--color-text);
font-size: 14px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
}
.epp-life-btn:hover { background: rgba(255,255,255,0.1); }
.epp-life-btn.minus:active { background: rgba(211,32,42,0.3); }
.epp-life-btn.plus:active { background: rgba(39,174,96,0.3); }
.epp-life-value {
font-size: 22px;
font-weight: 700;
color: var(--color-text);
min-width: 40px;
text-align: center;
cursor: pointer;
font-family: var(--font-display);
}
/* Sections */
.epp-section {
margin-top: 4px;
padding-top: 4px;
border-top: 1px solid rgba(255,255,255,0.05);
}
.epp-section-label {
font-size: 9px;
font-weight: 600;
color: var(--color-text-faint);
text-transform: uppercase;
letter-spacing: 0.05em;
margin-bottom: 3px;
}
/* Commander Damage */
.epp-cmd-dmg-grid {
display: flex;
flex-direction: column;
gap: 2px;
}
.epp-cmd-dmg-item {
display: flex;
align-items: center;
gap: 4px;
padding: 2px 4px;
border-radius: 3px;
position: relative;
overflow: hidden;
}
.epp-cmd-dmg-item.warning { background: rgba(241,196,15,0.08); }
.epp-cmd-dmg-item.critical { background: rgba(211,32,42,0.1); }
.epp-cmd-dmg-bar {
position: absolute;
left: 0; top: 0; bottom: 0;
background: rgba(211,32,42,0.08);
border-radius: 3px;
transition: width 0.3s;
}
.epp-cmd-dmg-dot {
width: 6px; height: 6px;
border-radius: 50%;
z-index: 1;
}
.epp-cmd-dmg-name {
font-size: 10px;
color: var(--color-text-muted);
z-index: 1;
}
.epp-cmd-dmg-value {
margin-left: auto;
font-weight: 600;
font-size: 10px;
z-index: 1;
}
/* Counters */
.epp-counters-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 3px;
}
.epp-counter {
display: flex;
align-items: center;
gap: 4px;
padding: 2px 4px;
border-radius: 3px;
background: rgba(255,255,255,0.02);
}
.epp-counter.warning { background: rgba(241,196,15,0.08); }
.epp-counter.critical { background: rgba(211,32,42,0.1); }
.epp-counter-icon { font-size: 12px; }
.epp-counter-value { font-weight: 700; font-size: 12px; }
.epp-counter-label { font-size: 9px; color: var(--color-text-faint); }
.epp-counter-info { display: flex; flex-direction: column; line-height: 1.1; }
.epp-counter-btns { margin-left: auto; display: flex; gap: 2px; }
.epp-counter-btn {
width: 16px; height: 16px;
border: 1px solid rgba(255,255,255,0.1);
border-radius: 3px;
background: transparent;
color: var(--color-text-muted);
font-size: 10px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
}
.epp-counter-btn:hover { background: rgba(255,255,255,0.08); }
/* Emblems */
.epp-emblems {
display: flex;
flex-wrap: wrap;
gap: 3px;
}
.epp-emblem-chip {
display: inline-flex;
align-items: center;
gap: 3px;
padding: 1px 6px;
background: rgba(200,168,67,0.1);
border: 1px solid rgba(200,168,67,0.2);
border-radius: 3px;
font-size: 10px;
color: var(--mtg-gold);
}
.epp-emblem-remove {
background: none;
border: none;
color: var(--color-text-faint);
cursor: pointer;
font-size: 10px;
padding: 0;
}
.epp-emblem-remove:hover { color: var(--color-error); }
.epp-no-emblems {
font-size: 10px;
color: var(--color-text-faint);
}
.epp-add-emblem-btn {
font-size: 9px;
padding: 1px 6px;
background: transparent;
border: 1px dashed rgba(255,255,255,0.1);
border-radius: 3px;
color: var(--color-text-faint);
cursor: pointer;
}
.epp-add-emblem-btn:hover {
border-color: rgba(255,255,255,0.2);
color: var(--color-text-muted);
}
+495
View File
@@ -0,0 +1,495 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Commander Battlefield</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Cinzel:wght@400;600;700&family=Inter:wght@400;500;600&display=swap');
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--felt: #2a2a2a;
--felt-light: #333333;
--felt-dark: #1e1e1e;
--felt-line: rgba(255,255,255,0.08);
--felt-line-strong: rgba(255,255,255,0.15);
--p1: #c0392b; --p1-soft: rgba(192,57,43,0.15); --p1-glow: rgba(192,57,43,0.35); --p1-text: #e74c3c;
--p2: #2980b9; --p2-soft: rgba(41,128,185,0.15); --p2-glow: rgba(41,128,185,0.35); --p2-text: #3498db;
--p3: #27ae60; --p3-soft: rgba(39,174,96,0.15); --p3-glow: rgba(39,174,96,0.35); --p3-text: #2ecc71;
--p4: #d4930d; --p4-soft: rgba(212,147,13,0.15); --p4-glow: rgba(212,147,13,0.35); --p4-text: #f1c40f;
--card-w: 63px;
--card-h: 88px;
--zone-radius: 8px;
}
html, body {
width: 100%; height: 100%;
overflow: hidden;
font-family: 'Inter', sans-serif;
background: var(--felt-dark);
}
body {
display: flex;
align-items: center;
justify-content: center;
}
.table-surface {
position: relative;
width: 100vw;
height: 100vh;
background: radial-gradient(ellipse at 50% 50%, var(--felt-light) 0%, var(--felt) 50%, var(--felt-dark) 100%);
overflow: hidden;
}
.table-surface::before {
content: '';
position: absolute;
inset: 0;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='0.08'/%3E%3C/svg%3E");
background-size: 200px 200px;
pointer-events: none;
z-index: 1;
opacity: 0.7;
}
.table-surface::after {
content: '';
position: absolute;
inset: 0;
background: radial-gradient(ellipse at center, transparent 40%, rgba(0,0,0,0.45) 100%);
pointer-events: none;
z-index: 2;
}
.battlefield {
position: absolute;
inset: 10px;
z-index: 5;
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
gap: 0;
}
.divider-h, .divider-v {
position: absolute;
z-index: 10;
pointer-events: none;
}
.divider-h {
top: 50%; left: 10px; right: 10px;
height: 2px;
transform: translateY(-50%);
background: var(--felt-line-strong);
box-shadow: 0 0 12px rgba(255,255,255,0.04);
}
.divider-v {
left: 50%; top: 10px; bottom: 10px;
width: 2px;
transform: translateX(-50%);
background: var(--felt-line-strong);
box-shadow: 0 0 12px rgba(255,255,255,0.04);
}
.center-emblem {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
z-index: 15;
width: 76px; height: 76px;
border-radius: 50%;
background: radial-gradient(circle, rgba(55,55,55,0.95), rgba(25,25,25,0.98));
border: 2px solid rgba(255,255,255,0.08);
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 0 30px rgba(0,0,0,0.6), inset 0 0 20px rgba(0,0,0,0.3);
}
.center-emblem svg { width: 40px; height: 40px; }
.player-area {
position: relative;
display: flex;
flex-direction: column;
padding: 8px;
overflow: hidden;
}
.player-area.p1 { grid-area: 1 / 1 / 2 / 2; }
.player-area.p2 { grid-area: 1 / 2 / 2 / 3; }
.player-area.p3 { grid-area: 2 / 1 / 3 / 2; }
.player-area.p4 { grid-area: 2 / 2 / 3 / 3; }
.p1, .p2 { justify-content: flex-start; }
.p3, .p4 { justify-content: flex-end; }
.player-label {
font-family: 'Cinzel', serif;
font-weight: 700;
font-size: 11px;
letter-spacing: 2px;
text-transform: uppercase;
padding: 3px 10px;
border-radius: 4px;
position: absolute;
z-index: 20;
white-space: nowrap;
}
.p1 .player-label { top: 8px; left: 8px; color: var(--p1-text); background: var(--p1-soft); }
.p2 .player-label { top: 8px; right: 8px; color: var(--p2-text); background: var(--p2-soft); }
.p3 .player-label { bottom: 8px; left: 8px; color: var(--p3-text); background: var(--p3-soft); }
.p4 .player-label { bottom: 8px; right: 8px; color: var(--p4-text); background: var(--p4-soft); }
.life-counter {
position: absolute;
z-index: 20;
display: flex;
align-items: center;
gap: 5px;
font-family: 'Cinzel', serif;
font-size: 20px;
font-weight: 700;
}
.life-counter button {
width: 22px; height: 22px;
border-radius: 50%;
border: 1px solid rgba(255,255,255,0.12);
background: rgba(255,255,255,0.04);
color: rgba(255,255,255,0.45);
font-size: 13px;
font-weight: 600;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s;
font-family: 'Inter', sans-serif;
line-height: 1;
}
.life-counter button:hover {
background: rgba(255,255,255,0.12);
color: rgba(255,255,255,0.8);
}
.p1 .life-counter { top: 8px; right: 8px; color: var(--p1-text); }
.p2 .life-counter { top: 8px; left: 8px; color: var(--p2-text); }
.p3 .life-counter { bottom: 8px; right: 8px; color: var(--p3-text); }
.p4 .life-counter { bottom: 8px; left: 8px; color: var(--p4-text); }
.zone-row {
display: flex;
align-items: center;
gap: 5px;
flex-shrink: 0;
}
.p1 .zone-row, .p3 .zone-row { flex-direction: row; }
.p2 .zone-row, .p4 .zone-row { flex-direction: row-reverse; }
.commander-row {
display: flex;
flex-shrink: 0;
margin: 4px 0;
}
.p1 .commander-row, .p3 .commander-row { justify-content: flex-start; }
.p2 .commander-row, .p4 .commander-row { justify-content: flex-end; }
.battle-zone {
flex: 1;
position: relative;
border-radius: var(--zone-radius);
min-height: 50px;
}
.battle-zone-inner {
position: absolute;
inset: 4px;
border-radius: var(--zone-radius);
border: 1px dashed;
opacity: 0.12;
pointer-events: none;
}
.p1 .battle-zone-inner { border-color: var(--p1); }
.p2 .battle-zone-inner { border-color: var(--p2); }
.p3 .battle-zone-inner { border-color: var(--p3); }
.p4 .battle-zone-inner { border-color: var(--p4); }
.battle-zone-label {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
font-family: 'Cinzel', serif;
font-size: 11px;
letter-spacing: 4px;
text-transform: uppercase;
opacity: 0.06;
pointer-events: none;
white-space: nowrap;
color: #fff;
}
.zone {
position: relative;
border-radius: var(--zone-radius);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
cursor: default;
transition: all 0.25s ease;
border: 1px solid rgba(255,255,255,0.05);
background: rgba(0,0,0,0.18);
overflow: hidden;
}
.zone:hover {
border-color: rgba(255,255,255,0.12);
background: rgba(0,0,0,0.28);
}
.zone-icon {
font-size: 16px;
opacity: 0.55;
margin-bottom: 2px;
pointer-events: none;
}
.zone-name {
font-size: 7.5px;
font-weight: 600;
letter-spacing: 1.2px;
text-transform: uppercase;
color: rgba(255,255,255,0.3);
pointer-events: none;
}
.zone.library, .zone.exile, .zone.graveyard {
width: var(--card-w);
height: var(--card-h);
}
.zone.hand {
flex: 1;
height: var(--card-h);
min-width: 80px;
flex-direction: row;
gap: 4px;
}
.zone.hand .zone-icon { margin-bottom: 0; margin-right: 3px; }
.zone.commander {
width: calc(var(--card-w) + 14px);
height: calc(var(--card-h) + 6px);
border-width: 2px;
}
.p1 .zone { border-color: rgba(192,57,43,0.12); }
.p1 .zone:hover { border-color: rgba(192,57,43,0.3); box-shadow: 0 0 12px var(--p1-soft); }
.p1 .zone.commander { border-color: rgba(192,57,43,0.25); background: var(--p1-soft); }
.p1 .zone-icon { color: var(--p1-text); }
.p2 .zone { border-color: rgba(41,128,185,0.12); }
.p2 .zone:hover { border-color: rgba(41,128,185,0.3); box-shadow: 0 0 12px var(--p2-soft); }
.p2 .zone.commander { border-color: rgba(41,128,185,0.25); background: var(--p2-soft); }
.p2 .zone-icon { color: var(--p2-text); }
.p3 .zone { border-color: rgba(39,174,96,0.12); }
.p3 .zone:hover { border-color: rgba(39,174,96,0.3); box-shadow: 0 0 12px var(--p3-soft); }
.p3 .zone.commander { border-color: rgba(39,174,96,0.25); background: var(--p3-soft); }
.p3 .zone-icon { color: var(--p3-text); }
.p4 .zone { border-color: rgba(212,147,13,0.12); }
.p4 .zone:hover { border-color: rgba(212,147,13,0.3); box-shadow: 0 0 12px var(--p4-soft); }
.p4 .zone.commander { border-color: rgba(212,147,13,0.25); background: var(--p4-soft); }
.p4 .zone-icon { color: var(--p4-text); }
.zone[data-tooltip]:hover::after {
content: attr(data-tooltip);
position: absolute;
bottom: calc(100% + 6px);
left: 50%;
transform: translateX(-50%);
background: rgba(0,0,0,0.88);
color: #ccc;
font-size: 10px;
padding: 3px 8px;
border-radius: 4px;
white-space: nowrap;
z-index: 50;
pointer-events: none;
}
.card-count {
position: absolute;
top: 3px;
right: 4px;
font-size: 8px;
font-weight: 600;
color: rgba(255,255,255,0.25);
background: rgba(0,0,0,0.3);
padding: 1px 4px;
border-radius: 8px;
}
.title-bar {
position: absolute;
top: 0; left: 0; right: 0;
z-index: 30;
text-align: center;
padding: 5px;
pointer-events: none;
}
.title-bar h1 {
font-family: 'Cinzel', serif;
font-size: 12px;
font-weight: 600;
letter-spacing: 5px;
text-transform: uppercase;
color: rgba(255,255,255,0.15);
}
.corner-accent {
position: absolute;
width: 24px; height: 24px;
z-index: 6;
pointer-events: none;
opacity: 0.12;
}
.corner-accent.tl { top: 6px; left: 6px; border-top: 2px solid var(--p1); border-left: 2px solid var(--p1); }
.corner-accent.tr { top: 6px; right: 6px; border-top: 2px solid var(--p2); border-right: 2px solid var(--p2); }
.corner-accent.bl { bottom: 6px; left: 6px; border-bottom: 2px solid var(--p3); border-left: 2px solid var(--p3); }
.corner-accent.br { bottom: 6px; right: 6px; border-bottom: 2px solid var(--p4); border-right: 2px solid var(--p4); }
@media (max-width: 768px) {
:root { --card-w: 42px; --card-h: 58px; }
.player-label { font-size: 7px; letter-spacing: 1px; padding: 2px 6px; }
.life-counter { font-size: 15px; }
.life-counter button { width: 18px; height: 18px; font-size: 11px; }
.zone-name { font-size: 6px; }
.zone-icon { font-size: 12px; }
.center-emblem { width: 46px; height: 46px; }
.center-emblem svg { width: 26px; height: 26px; }
.battle-zone-label { font-size: 8px; letter-spacing: 2px; }
.zone-row { gap: 3px; }
}
</style>
</head>
<body>
<div class="table-surface">
<div class="title-bar"><h1>Commander Battlefield</h1></div>
<div class="corner-accent tl"></div>
<div class="corner-accent tr"></div>
<div class="corner-accent bl"></div>
<div class="corner-accent br"></div>
<div class="divider-h"></div>
<div class="divider-v"></div>
<div class="center-emblem">
<svg viewBox="0 0 100 100" fill="none">
<circle cx="50" cy="50" r="42" stroke="rgba(255,255,255,0.2)" stroke-width="1.5"/>
<circle cx="50" cy="50" r="28" stroke="rgba(255,255,255,0.1)" stroke-width="1"/>
<polygon points="50,15 58.5,37 82,37 63,51 69,74 50,60 31,74 37,51 18,37 41.5,37"
fill="rgba(255,255,255,0.1)" stroke="rgba(255,255,255,0.2)" stroke-width="0.8"/>
</svg>
</div>
<div class="battlefield">
<!-- PLAYER 1: Top-Left (Crimson) -->
<div class="player-area p1">
<span class="player-label">Player 1</span>
<div class="life-counter">
<button onclick="changeLife(1,-1)" aria-label="Decrease life">−</button>
<span id="life1">40</span>
<button onclick="changeLife(1,1)" aria-label="Increase life">+</button>
</div>
<div class="zone-row">
<div class="zone library" data-tooltip="Library"><span class="card-count">99</span><span class="zone-icon">📚</span><span class="zone-name">Library</span></div>
<div class="zone exile" data-tooltip="Exile"><span class="zone-icon">✦</span><span class="zone-name">Exile</span></div>
<div class="zone graveyard" data-tooltip="Graveyard"><span class="zone-icon">💀</span><span class="zone-name">Grave</span></div>
<div class="zone hand" data-tooltip="Hand"><span class="zone-icon">🃏</span><span class="zone-name">Hand</span></div>
</div>
<div class="commander-row">
<div class="zone commander" data-tooltip="Commander Zone"><span class="zone-icon">👑</span><span class="zone-name">Commander</span></div>
</div>
<div class="battle-zone"><div class="battle-zone-inner"></div><span class="battle-zone-label">Battlefield</span></div>
</div>
<!-- PLAYER 2: Top-Right (Sapphire) -->
<div class="player-area p2">
<span class="player-label">Player 2</span>
<div class="life-counter">
<button onclick="changeLife(2,-1)" aria-label="Decrease life">−</button>
<span id="life2">40</span>
<button onclick="changeLife(2,1)" aria-label="Increase life">+</button>
</div>
<div class="zone-row">
<div class="zone library" data-tooltip="Library"><span class="card-count">99</span><span class="zone-icon">📚</span><span class="zone-name">Library</span></div>
<div class="zone exile" data-tooltip="Exile"><span class="zone-icon">✦</span><span class="zone-name">Exile</span></div>
<div class="zone graveyard" data-tooltip="Graveyard"><span class="zone-icon">💀</span><span class="zone-name">Grave</span></div>
<div class="zone hand" data-tooltip="Hand"><span class="zone-icon">🃏</span><span class="zone-name">Hand</span></div>
</div>
<div class="commander-row">
<div class="zone commander" data-tooltip="Commander Zone"><span class="zone-icon">👑</span><span class="zone-name">Commander</span></div>
</div>
<div class="battle-zone"><div class="battle-zone-inner"></div><span class="battle-zone-label">Battlefield</span></div>
</div>
<!-- PLAYER 3: Bottom-Left (Emerald) -->
<div class="player-area p3">
<div class="battle-zone"><div class="battle-zone-inner"></div><span class="battle-zone-label">Battlefield</span></div>
<div class="commander-row">
<div class="zone commander" data-tooltip="Commander Zone"><span class="zone-icon">👑</span><span class="zone-name">Commander</span></div>
</div>
<div class="zone-row">
<div class="zone library" data-tooltip="Library"><span class="card-count">99</span><span class="zone-icon">📚</span><span class="zone-name">Library</span></div>
<div class="zone exile" data-tooltip="Exile"><span class="zone-icon">✦</span><span class="zone-name">Exile</span></div>
<div class="zone graveyard" data-tooltip="Graveyard"><span class="zone-icon">💀</span><span class="zone-name">Grave</span></div>
<div class="zone hand" data-tooltip="Hand"><span class="zone-icon">🃏</span><span class="zone-name">Hand</span></div>
</div>
<span class="player-label">Player 3</span>
<div class="life-counter">
<button onclick="changeLife(3,-1)" aria-label="Decrease life">−</button>
<span id="life3">40</span>
<button onclick="changeLife(3,1)" aria-label="Increase life">+</button>
</div>
</div>
<!-- PLAYER 4: Bottom-Right (Gold) -->
<div class="player-area p4">
<div class="battle-zone"><div class="battle-zone-inner"></div><span class="battle-zone-label">Battlefield</span></div>
<div class="commander-row">
<div class="zone commander" data-tooltip="Commander Zone"><span class="zone-icon">👑</span><span class="zone-name">Commander</span></div>
</div>
<div class="zone-row">
<div class="zone library" data-tooltip="Library"><span class="card-count">99</span><span class="zone-icon">📚</span><span class="zone-name">Library</span></div>
<div class="zone exile" data-tooltip="Exile"><span class="zone-icon">✦</span><span class="zone-name">Exile</span></div>
<div class="zone graveyard" data-tooltip="Graveyard"><span class="zone-icon">💀</span><span class="zone-name">Grave</span></div>
<div class="zone hand" data-tooltip="Hand"><span class="zone-icon">🃏</span><span class="zone-name">Hand</span></div>
</div>
<span class="player-label">Player 4</span>
<div class="life-counter">
<button onclick="changeLife(4,-1)" aria-label="Decrease life">−</button>
<span id="life4">40</span>
<button onclick="changeLife(4,1)" aria-label="Increase life">+</button>
</div>
</div>
</div>
</div>
<script>
const lives = { 1: 40, 2: 40, 3: 40, 4: 40 };
function changeLife(p, d) {
lives[p] = Math.max(0, lives[p] + d);
const el = document.getElementById('life' + p);
el.textContent = lives[p];
el.style.transform = 'scale(1.25)';
el.style.transition = 'transform 0.15s ease';
setTimeout(() => { el.style.transform = 'scale(1)'; }, 150);
}
</script>
</body>
</html>
+82 -323
View File
@@ -1,5 +1,5 @@
/**
* MTG Commander Simulator — ui.js
/**
* MTG Commander Simulator — ui.js
* All UI rendering functions adapted for the 4-quadrant battlefield layout.
* This file overrides/extends DOM-touching functions from engine.js.
* ============================================================
@@ -83,7 +83,7 @@ function setLife(playerId, newLife) {
updateLifeCounterDisplay(playerId);
const diff = newLife - oldLife;
const sign = diff > 0 ? '+' : '';
addLogEntry('<strong>' + player.name + '</strong> life: ' + oldLife + ' → <strong>' + newLife + '</strong> (' + sign + diff + ')');
addLogEntry('<strong>' + player.name + '</strong> life: ' + oldLife + ' → <strong>' + newLife + '</strong> (' + sign + diff + ')');
if (diff > 0) fireBattlefieldTriggers('life_gain');
else if (diff < 0) fireBattlefieldTriggers('life_loss');
if (newLife <= 0 && !player.eliminated) eliminatePlayer(playerId, 'life total reached 0');
@@ -117,7 +117,7 @@ function updateActivePlayerHighlight() {
}
// ============================================================
// RENDER PLAYER PANELS (adapted for 4-quadrant — updates zones/labels)
// RENDER PLAYER PANELS (adapted for 4-quadrant — updates zones/labels)
// ============================================================
function renderPlayerPanels() {
if (!gameState) return;
@@ -358,7 +358,7 @@ function renderBattlefieldCard(cardData) {
card.appendChild(dmgBadge);
}
// Event listeners — use both for compatibility (Comet: inline onclick already on container)
// Event listeners — use both for compatibility (Comet: inline onclick already on container)
card.addEventListener('mousedown', e => {
if (e.button !== 0) return;
if (cardData.attachedTo) return;
@@ -570,7 +570,7 @@ function handlePhaseClick(phaseIdx) {
// Just provide info about the phase, don't jump to it
if (!gameState) return;
const phase = PHASES[phaseIdx];
if (phase) addLogEntry('Phase info: <strong>' + phase.label + '</strong> — ' + phase.tip);
if (phase) addLogEntry('Phase info: <strong>' + phase.label + '</strong> — ' + phase.tip);
}
function updateTurnDisplay() {
@@ -595,7 +595,29 @@ function updateStormCounter() {
// MANA POOL DISPLAY
// ============================================================
function renderManaPool(playerIdx) {
// mana pool display removed (Phase 1)
if (!gameState) return;
const pool = getManaPool(playerIdx !== undefined ? playerIdx : gameState.currentPlayerIndex);
const display = document.getElementById('mana-pool-display');
if (!display) return;
const colors = ['W', 'U', 'B', 'R', 'G', 'C'];
let html = '<span class="mana-pool-label">MANA:</span>';
let hasAny = false;
colors.forEach(c => {
if (pool[c] > 0) {
hasAny = true;
html += '<span class="mana-pip mana-' + c + '" title="' + getManaColorName(c) + ': ' + pool[c] + '">' + pool[c] + '</span>';
}
});
if (!hasAny) {
html += '<span class="mana-empty">Empty</span>';
}
html += '<button class="mana-pool-clear-btn" onclick="clearManaPool(' + gameState.currentPlayerIndex + ')" title="Clear mana pool">x</button>';
display.innerHTML = html;
display.style.display = gameState.inGame ? 'flex' : 'none';
}
// ============================================================
@@ -933,7 +955,7 @@ function handleZmCtxAction(playerId, zone, cardIndex, action) {
}
// ============================================================
// HAND AREA — full hand display (used in hand-area section, NOT the zone thumbnails)
// HAND AREA — full hand display (used in hand-area section, NOT the zone thumbnails)
// For the new layout, hand is rendered as thumbnails in the zone.hand element
// ============================================================
function renderHandArea() {
@@ -1005,11 +1027,9 @@ function initSetupScreen() {
'</div>' +
'<div class="setup-section">' +
'<div class="setup-label">Decks</div>' +
'<div class="backend-status-row">' +
'<span id="backend-status-indicator" class="backend-status disconnected">Checking backend...</span>' +
'</div>' +
'<div id="deck-assignment-grid" class="deck-assignment-grid"></div>' +
'<div class="setup-label">Decks (Optional)</div>' +
'<div id="deck-assignment-grid" style="display:flex;flex-direction:column;gap:6px;"></div>' +
'<button class="btn btn-cancel" style="margin-top:8px;font-size:11px;" onclick="openPreconBrowser()">Browse Commander Precons</button>' +
'</div>' +
'<button class="btn-start" onclick="startGame()">Begin Battle</button>' +
@@ -1101,23 +1121,7 @@ function initSetupScreen() {
// Sync AI config to engine globals
setupAiPlayers = _localAiSet;
setupAiDifficulty = _localAiDiff;
setupPlayerCount = selectedPlayerCount;
setupStartingLife = startingLife;
// Sync player names to engine globals
for (let i = 0; i < playerNames.length; i++) {
var nameInput = document.getElementById('player-name-' + i);
if (nameInput) nameInput.value = playerNames[i];
}
// If any deck choices were made, use startGameWithDecks (async deck loading)
var hasDecks = typeof setupDeckChoices !== 'undefined' &&
Object.keys(setupDeckChoices).length > 0;
if (hasDecks && typeof startGameWithDecks === 'function') {
startGameWithDecks();
} else {
initGame(selectedPlayerCount, playerNames, startingLife);
}
initGame(selectedPlayerCount, playerNames, startingLife);
};
// Trigger display update for player count
@@ -1125,296 +1129,41 @@ function initSetupScreen() {
}
function updateDeckAssignmentGrid(playerCount) {
var grid = document.getElementById('deck-assignment-grid');
const grid = document.getElementById('deck-assignment-grid');
if (!grid) return;
const preconList = (typeof PRECON_DATA !== 'undefined') ? PRECON_DATA : (typeof PRECONS !== 'undefined') ? PRECONS : null;
if (!preconList || preconList.length === 0) {
grid.innerHTML = '<div style="font-size:11px;color:var(--color-text-faint);">Import deck in the Deck Manager after starting.</div>';
return;
}
// Pick random unique precons for each player slot
var shuffled = preconList.slice();
for (var si = shuffled.length - 1; si > 0; si--) {
var sj = Math.floor(Math.random() * (si + 1));
var tmp = shuffled[si]; shuffled[si] = shuffled[sj]; shuffled[sj] = tmp;
}
var defaults = shuffled.slice(0, playerCount);
grid.innerHTML = '';
var playerColors = [
{ color: '#c0392b', name: 'Crimson' },
{ color: '#2980b9', name: 'Sapphire' },
{ color: '#27ae60', name: 'Emerald' },
{ color: '#d4930d', name: 'Gold' },
];
for (var i = 0; i < playerCount; i++) {
var isAi = typeof setupAiPlayers !== 'undefined' && setupAiPlayers.has
? setupAiPlayers.has(i)
: (typeof _localAiSet !== 'undefined' && _localAiSet.has(i));
var nameInput = document.getElementById('player-name-' + i);
var playerName = (nameInput && nameInput.value.trim()) ||
(isAi ? ('AI Bot ' + (i + 1)) : ('Player ' + (i + 1)));
var panel = document.createElement('div');
panel.className = 'deck-select-panel';
panel.id = 'deck-panel-' + i;
if (isAi) {
panel.innerHTML =
'<div class="deck-select-panel-header">' +
'<div class="player-color-dot" style="background:' + playerColors[i].color + '"></div>' +
'<span class="deck-select-player-name">' + playerName + '</span>' +
'<span class="deck-select-ai-badge">AI</span>' +
'</div>' +
'<div class="deck-select-ai-note">AI Deck (auto-generated)</div>';
} else {
panel.innerHTML =
'<div class="deck-select-panel-header">' +
'<div class="player-color-dot" style="background:' + playerColors[i].color + '"></div>' +
'<span class="deck-select-player-name">' + playerName + '</span>' +
'<span class="deck-select-status" id="deck-status-' + i + '">No deck selected</span>' +
'</div>' +
'<div class="deck-tabs" id="deck-tabs-' + i + '">' +
'<button class="deck-tab active" data-tab="precons" onclick="switchDeckTab(' + i + ',\'precons\')">Precons</button>' +
'<button class="deck-tab" data-tab="edhrec" onclick="switchDeckTab(' + i + ',\'edhrec\')">EDHREC</button>' +
'<button class="deck-tab" data-tab="mydecks" onclick="switchDeckTab(' + i + ',\'mydecks\')">My Decks</button>' +
'</div>' +
'<div class="deck-tab-content" id="deck-content-' + i + '">' +
_buildPreconTabContent(i) +
'</div>';
}
grid.appendChild(panel);
}
// If backend is connected, load precons from API
_loadBackendPrecons();
}
function _buildPreconTabContent(playerIdx) {
// Local precons from precons.js (PRECON_DATA)
var preconList = (typeof PRECON_DATA !== 'undefined') ? PRECON_DATA : [];
if (preconList.length === 0) {
return '<div class="deck-tab-empty">No precon data loaded.<br>Connect to Commander-AI-Lab backend for 163+ precons.</div>';
}
var html = '<div class="deck-filter-row">' +
'<input class="deck-filter-input" type="text" placeholder="Filter precons..." ' +
'oninput="filterPrecons(' + playerIdx + ', this.value)" />' +
'</div>';
// Group by set
var sets = {};
preconList.forEach(function(p) {
var setName = p.set || 'Other';
if (!sets[setName]) sets[setName] = [];
sets[setName].push(p);
});
html += '<div class="deck-precon-list" id="precon-list-' + playerIdx + '">';
Object.keys(sets).sort().forEach(function(setName) {
html += '<div class="deck-set-group">';
html += '<div class="deck-set-header" onclick="toggleDeckSet(this)">';
html += '<span class="deck-set-arrow">\u25b8</span> ' + setName + ' (' + sets[setName].length + ')';
html += '</div>';
html += '<div class="deck-set-items" style="display:none;">';
sets[setName].forEach(function(p) {
html += '<button class="deck-precon-item" data-precon-id="' + p.id + '" ' +
'onclick="selectPreconDeck(' + playerIdx + ',\'' + p.id.replace(/'/g, "\\'") + '\')">';
html += '<span class="deck-precon-name">' + (p.name || p.id).replace(/</g, '&lt;') + '</span>';
if (p.commander) {
html += '<span class="deck-precon-cmdr">' + p.commander.replace(/</g, '&lt;') + '</span>';
}
html += '</button>';
for (let i = 0; i < playerCount; i++) {
var defaultId = defaults[i] ? defaults[i].id : '';
const row = document.createElement('div');
row.className = 'deck-select-row';
var optionsHtml = '<option value="">— No deck (empty) —</option>';
preconList.forEach(function(p) {
var sel = (p.id === defaultId) ? ' selected' : '';
optionsHtml += '<option value="' + p.id + '"' + sel + '>' + p.name + (p.commander ? ' (' + p.commander + ')' : '') + '</option>';
});
html += '</div></div>';
});
html += '</div>';
return html;
}
async function _loadBackendPrecons() {
if (typeof AIBridge === 'undefined' || !AIBridge.connector.connected) return;
try {
var precons = await AIBridge.deckSource.fetchPrecons();
if (precons && precons.length > 0) {
// Merge backend precons into PRECON_DATA so the UI can render them
window.PRECON_DATA = precons.map(function(p) {
return {
id: (p.fileName || p.name || '').replace('.dck', ''),
name: p.name || p.fileName || '',
commander: p.commander || (p.commanders && p.commanders[0]) || '',
set: p.set || '',
fileName: p.fileName || '',
colors: p.colors || [],
year: p.year || 0
};
});
// Re-render the precon tab content for all visible player panels
var panels = document.querySelectorAll('[id^="deck-content-"]');
panels.forEach(function(panel) {
var idx = parseInt(panel.id.replace('deck-content-', ''));
if (!isNaN(idx)) {
var activeTab = panel.closest('.deck-select-panel');
var activeBtn = activeTab ? activeTab.querySelector('.deck-tab.active') : null;
// Only re-render if Precons tab is active (or no tab selected yet)
if (!activeBtn || activeBtn.getAttribute('data-tab') === 'precons') {
panel.innerHTML = _buildPreconTabContent(idx);
}
}
});
// Update status indicator
var indicator = document.getElementById('backend-status-indicator');
if (indicator) {
indicator.textContent = '\u26a1 ' + precons.length + ' precons from backend';
indicator.className = 'backend-status connected';
}
}
} catch (e) {
console.warn('[_loadBackendPrecons] Error:', e);
row.innerHTML =
'<span class="deck-select-label" style="color:' + PLAYER_COLORS[i] + '">P' + (i + 1) + ':</span>' +
'<select id="deck-sel-' + i + '" class="game-input" style="flex:1;height:24px;font-size:11px;">' +
optionsHtml +
'</select>';
grid.appendChild(row);
}
}
function switchDeckTab(playerIdx, tab) {
var tabs = document.querySelectorAll('#deck-tabs-' + playerIdx + ' .deck-tab');
tabs.forEach(function(t) {
t.classList.toggle('active', t.getAttribute('data-tab') === tab);
});
var content = document.getElementById('deck-content-' + playerIdx);
if (!content) return;
switch (tab) {
case 'precons':
content.innerHTML = _buildPreconTabContent(playerIdx);
break;
case 'edhrec':
content.innerHTML =
'<div class="deck-edhrec-content">' +
'<div class="deck-filter-row">' +
'<input class="deck-filter-input" type="text" placeholder="Search by commander name..." ' +
'id="edhrec-search-' + playerIdx + '" />' +
'<button class="btn btn-sm" onclick="searchEdhrec(' + playerIdx + ')">Search</button>' +
'</div>' +
'<div id="edhrec-results-' + playerIdx + '" class="deck-edhrec-results">' +
'<div class="deck-tab-empty">Enter a commander name to find EDHREC recommendations.<br>' +
'<em style="font-size:10px;opacity:0.6">EDHREC integration coming soon.</em></div>' +
'</div>' +
'</div>';
break;
case 'mydecks':
content.innerHTML =
'<div class="deck-mydecks-content">' +
'<div class="deck-tab-empty">' +
'<div style="margin-bottom:8px;">Import a decklist:</div>' +
'<textarea class="deck-import-textarea" id="deck-import-' + playerIdx + '" ' +
'placeholder="Paste decklist here...\n1 Sol Ring\n1 Command Tower\n..."></textarea>' +
'<button class="btn btn-sm" style="margin-top:6px;" ' +
'onclick="importDeckFromTextarea(' + playerIdx + ')">Import Decklist</button>' +
'</div>' +
'</div>';
break;
}
}
function filterPrecons(playerIdx, query) {
var list = document.getElementById('precon-list-' + playerIdx);
if (!list) return;
var q = query.toLowerCase().trim();
list.querySelectorAll('.deck-precon-item').forEach(function(item) {
var name = item.querySelector('.deck-precon-name')?.textContent?.toLowerCase() || '';
var cmdr = item.querySelector('.deck-precon-cmdr')?.textContent?.toLowerCase() || '';
var match = !q || name.includes(q) || cmdr.includes(q);
item.style.display = match ? '' : 'none';
});
// Auto-expand groups that have visible items
list.querySelectorAll('.deck-set-group').forEach(function(group) {
var items = group.querySelector('.deck-set-items');
var hasVisible = items && Array.from(items.querySelectorAll('.deck-precon-item'))
.some(function(it) { return it.style.display !== 'none'; });
if (items && q) {
items.style.display = hasVisible ? '' : 'none';
}
});
}
function toggleDeckSet(headerEl) {
var items = headerEl.nextElementSibling;
if (!items) return;
var isOpen = items.style.display !== 'none';
items.style.display = isOpen ? 'none' : '';
var arrow = headerEl.querySelector('.deck-set-arrow');
if (arrow) arrow.textContent = isOpen ? '\u25b8' : '\u25be';
}
function selectPreconDeck(playerIdx, preconId) {
var panel = document.getElementById('deck-panel-' + playerIdx);
if (panel) {
panel.querySelectorAll('.deck-precon-item').forEach(function(item) {
item.classList.remove('selected');
});
var selected = panel.querySelector('[data-precon-id="' + preconId + '"]');
if (selected) selected.classList.add('selected');
}
var status = document.getElementById('deck-status-' + playerIdx);
var preconList = (typeof PRECON_DATA !== 'undefined') ? PRECON_DATA : [];
var precon = preconList.find(function(p) { return p.id === preconId; });
if (status) {
status.textContent = precon ? (precon.name || preconId) + ' selected' : preconId + ' selected';
status.className = 'deck-select-status selected';
}
if (typeof setupDeckChoices === 'undefined') window.setupDeckChoices = {};
setupDeckChoices[playerIdx] = { type: 'precon', preconId: preconId };
}
function searchEdhrec(playerIdx) {
var input = document.getElementById('edhrec-search-' + playerIdx);
var results = document.getElementById('edhrec-results-' + playerIdx);
if (!input || !results) return;
var query = input.value.trim();
if (!query) return;
results.innerHTML = '<div class="deck-tab-loading">Searching EDHREC for "' + query + '"...</div>';
if (typeof AIBridge !== 'undefined' && AIBridge.connector.connected) {
AIBridge.deckSource.fetchEdhrecDecks(query).then(function(decks) {
if (decks.length === 0) {
results.innerHTML = '<div class="deck-tab-empty">No results for "' + query + '".<br>' +
'<em style="font-size:10px;opacity:0.6">EDHREC integration is coming soon.</em></div>';
} else {
var html = '';
decks.forEach(function(d) {
html += '<button class="deck-precon-item" onclick="selectEdhrecDeck(' + playerIdx + ',\'' + d.name + '\')">' +
'<span class="deck-precon-name">' + d.name + '</span>' +
'</button>';
});
results.innerHTML = html;
}
});
} else {
results.innerHTML = '<div class="deck-tab-empty">EDHREC search requires Commander-AI-Lab backend.<br>' +
'<em style="font-size:10px;opacity:0.6">Start the backend: python lab_api.py</em></div>';
}
}
function importDeckFromTextarea(playerIdx) {
var textarea = document.getElementById('deck-import-' + playerIdx);
if (!textarea) return;
var text = textarea.value.trim();
if (!text) return;
var status = document.getElementById('deck-status-' + playerIdx);
if (status) {
status.textContent = 'Decklist imported';
status.className = 'deck-select-status selected';
}
if (typeof setupDeckChoices === 'undefined') window.setupDeckChoices = {};
setupDeckChoices[playerIdx] = { type: 'import', text: text };
}
// ============================================================
// GAME INITIALIZATION
// ============================================================
@@ -1455,9 +1204,15 @@ function initGame(playerCount, playerNames, startingLife) {
}
}
// NOTE: Precon deck loading is handled by the "Begin Battle" button
// which calls startGameWithDecks() when setupDeckChoices has entries.
// The old deck-sel-{i} dropdown path is removed.
// Assign precon decks if selected
for (let i = 0; i < playerCount; i++) {
const sel = document.getElementById('deck-sel-' + i);
if (sel && sel.value) {
const preconList2 = (typeof PRECON_DATA !== 'undefined') ? PRECON_DATA : (typeof PRECONS !== 'undefined') ? PRECONS : [];
const precon = preconList2.find(p => p.id === sel.value);
if (precon) loadPreconDeck(i, precon);
}
}
// Mark AI players
setupAiPlayers.forEach(function(idx) {
@@ -1851,7 +1606,10 @@ function showToast(message) {
// MANA POOL DISPLAY BUTTON
// ============================================================
function showManaPool() {
// mana pool display removed (Phase 1)
const display = document.getElementById('mana-pool-display');
if (display) {
display.style.display = display.style.display === 'none' ? 'flex' : 'none';
}
}
// ============================================================
@@ -1978,7 +1736,8 @@ function renderSettingsPanel() {
'<div class="settings-row"><span>Commander Tax</span>' + renderToggle('commanderTaxEnabled', re.commanderTaxEnabled) + '</div>' +
'<div class="settings-row"><span>Auto Resolve Triggers</span>' + renderToggle('autoResolveTriggers', re.autoResolveTriggers) + '</div>' +
'<div class="settings-row"><span>Enforce Hand Size</span>' + renderToggle('enforceHandSize', re.enforceHandSize) + '</div>' +
'<div class="settings-row"><span>Auto Eliminate on SBA</span>' + renderToggle('autoEliminateOnSBA', re.autoEliminateOnSBA) + '</div>';
'<div class="settings-row"><span>Auto Eliminate on SBA</span>' + renderToggle('autoEliminateOnSBA', re.autoEliminateOnSBA) + '</div>' +
'<div class="settings-row"><span>Mana Auto-Clear</span>' + renderToggle('manaAutoClear', gameState.manaAutoClear) + '</div>';
}
function renderToggle(key, value) {
@@ -1998,7 +1757,7 @@ function toggleSetting(key) {
// ============================================================
// PLACEHOLDER STUBS for engine-called UI functions
// (engine.js calls these — we provide no-op or simple implementations)
// (engine.js calls these — we provide no-op or simple implementations)
// ============================================================
function renderPlayerPanelsNoOp() { renderPlayerPanels(); }
@@ -2230,7 +1989,7 @@ function openPreconBrowser() {
}
// ============================================================
// DOM UTILITY — updateCardCounterBadge
// DOM UTILITY — updateCardCounterBadge
// ============================================================
function updateCardCounterBadge(cardId) {
if (!gameState) return;
@@ -2264,7 +2023,7 @@ function updateCardCounterBadge(cardId) {
}
// ============================================================
// DOM — toggleTap visual update
// DOM — toggleTap visual update
// ============================================================
function _refreshCardEl(cardId) {
if (!gameState) return;
@@ -2277,7 +2036,7 @@ function _refreshCardEl(cardId) {
}
// ============================================================
// DOMContentLoaded — wire up everything
// DOMContentLoaded — wire up everything
// ============================================================
document.addEventListener('DOMContentLoaded', () => {
initSetupScreen();