Compare commits

...
Author SHA1 Message Date
Commander AI Lab 7750b43494 fix: deck loading — wire startGameWithDecks, fetch .dck content, parse [sections]
Three fixes that prevented precon decks from loading into actual gameplay:

1. ui.js: window.startGame() now calls startGameWithDecks() when
   setupDeckChoices has entries (the 3-tab selector stores choices there).
   Previously it called initGame() which looked for old deck-sel-{i}
   dropdowns that no longer exist.

2. engine.js: loadPreconForPlayer() now fetches .dck file content from
   the backend (/api/lab/precons/deck?fileName=...) when precon.decklist
   is empty. Falls back to fetching precon-decks/{file} directly.
   PRECON_DATA entries only have metadata (name, commander, set) — the
   actual card list lives in the .dck files.

3. engine.js: parseDeckList() now handles .dck bracket-style section
   headers like [Commander], [Main], [metadata]. Previously only matched
   bare text like 'COMMANDER:' without brackets. Also skips [metadata]
   lines (e.g. 'Name=Elven Empire').

4. routes/precon.py: Added GET /api/lab/precons/deck?fileName=... endpoint
   to serve raw .dck file content for the LAN client.
2026-04-03 13:45:15 +00:00
KoalaTrapLord fa58463cde Merge pull request #198 from KoalaTrapLord/fix/setup-screen-layout
fix: Setup screen overflows viewport — 2-col deck grid + scroll
2026-04-03 09:38:26 -04:00
3 changed files with 90 additions and 14 deletions

No files matched your search

+45 -4
View File
@@ -10877,16 +10877,20 @@ function parseDeckList(text) {
let line = raw.trim();
if (!line) continue;
// 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();
// 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();
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;
@@ -12719,7 +12723,44 @@ async function loadPreconForPlayer(playerIdx, preconId) {
var player = gameState.players[playerIdx];
if (!player) return;
var parsedCards = parseDeckList(precon.decklist);
// Try to get decklist text: embedded first, then fetch from backend .dck file
var decklistText = precon.decklist || '';
if (!decklistText && precon.fileName) {
// Fetch .dck file from backend if available
if (typeof AIBridge !== 'undefined' && AIBridge.connector.connected) {
try {
var deckData = await AIBridge.deckSource.fetchPreconDeck(precon.fileName);
if (deckData && deckData.decklist) {
decklistText = deckData.decklist;
} else if (deckData && typeof deckData === 'string') {
decklistText = deckData;
}
} catch (e) {
console.warn('[loadPreconForPlayer] Backend deck fetch failed:', e);
}
}
// Fallback: try to fetch .dck file directly from precon-decks/ (same origin)
if (!decklistText) {
try {
var resp = await fetch('precon-decks/' + precon.fileName);
if (resp.ok) {
decklistText = await resp.text();
}
} catch (e) {
// Fallback: try relative to backend
try {
var resp2 = await fetch('/precon-decks/' + precon.fileName);
if (resp2.ok) {
decklistText = await resp2.text();
}
} catch (e2) {
console.warn('[loadPreconForPlayer] Could not fetch .dck file:', precon.fileName);
}
}
}
}
var parsedCards = parseDeckList(decklistText);
if (!parsedCards.length) return;
var allCardNames = [];
+20 -10
View File
@@ -1123,7 +1123,23 @@ function initSetupScreen() {
// Sync AI config to engine globals
setupAiPlayers = _localAiSet;
setupAiDifficulty = _localAiDiff;
initGame(selectedPlayerCount, playerNames, startingLife);
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);
}
};
// Trigger display update for player count
@@ -1461,15 +1477,9 @@ function initGame(playerCount, playerNames, startingLife) {
}
}
// 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);
}
}
// 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.
// Mark AI players
setupAiPlayers.forEach(function(idx) {
+25
View File
@@ -29,6 +29,31 @@ 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.