Files
scrollsmith/dungeonGenerator.js
Madison Grubb 96480a351f
Some checks failed
ci/woodpecker/cron/ci Pipeline failed
make it start working again
2025-12-11 23:13:07 -05:00

521 lines
24 KiB
JavaScript

import { callOllama } from "./ollamaClient.js";
// Utility: strip markdown artifacts and clean up extra whitespace
function cleanText(str) {
if (!str) return "";
return str
.replace(/^#+\s*/gm, "")
.replace(/\*\*(.*?)\*\*/g, "$1") // Removes bolding
.replace(/[*_`]/g, "") // Removes other markdown
.replace(/\s+/g, " ")
.trim();
}
function parseList(raw) {
return raw
.split(/\n?\d+[).]\s+/)
.map(line => cleanText(line))
.filter(Boolean);
}
function parseObjects(raw, type = "rooms") {
const cleanedRaw = raw.replace(/Intermediate Rooms:/i, "").replace(/Climax Room:/i, "").trim();
const mapper = (entry) => {
const [name, ...descParts] = entry.split(/[-–—:]/);
const desc = descParts.join(" ").trim();
const obj = { name: name.trim() };
if (type === "rooms") return { ...obj, description: desc };
if (type === "encounters") return { ...obj, details: desc };
if (type === "npcs") return { ...obj, trait: desc };
if (type === "treasure") return { ...obj, description: desc };
return entry;
};
return cleanedRaw.split(/\n?\d+[).]\s+/).map(cleanText).filter(Boolean).map(mapper);
}
const parseEncounterText = (text, idx) => {
const match = text.match(/^(\d+)\s+(.+?)(?::\s*(.+))?$/);
if (match) {
const [, , name, details] = match;
return name && details ? { name: name.trim(), details: details.trim() } : null;
}
const colonSplit = text.split(/[:]/);
if (colonSplit.length > 1) {
return {
name: colonSplit[0].replace(/^\d+\s+/, "").trim(),
details: colonSplit.slice(1).join(":").trim()
};
}
const nameMatch = text.match(/^\d+\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)/);
if (nameMatch) {
return {
name: nameMatch[1],
details: text.replace(/^\d+\s+[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\s*/, "").trim()
};
}
return { name: `Encounter ${idx + 1}`, details: text.replace(/^\d+\s+/, "").trim() };
};
const splitCombinedEncounters = (encounters) => {
const shouldSplit = encounters.length === 1 && (encounters[0].name === "1" || encounters[0].details.match(/\d+\s+[A-Z]/));
if (!shouldSplit) return encounters;
console.warn("Encounters appear combined, attempting to split...");
const combinedText = encounters[0].details || "";
const split = combinedText.split(/(?=\d+\s+[A-Z][a-z])/).filter(Boolean);
return (split.length > 1 || (split.length === 1 && combinedText.length > 100))
? split.map(parseEncounterText).filter(e => e?.name && e?.details?.length > 10)
: encounters;
};
const splitCombinedNPCs = (npcs) => {
const shouldSplit = npcs.length === 1 && npcs[0].trait?.length > 80;
if (!shouldSplit) return npcs;
console.warn("NPCs appear combined, attempting to split...");
const split = npcs[0].trait.split(/(?=[A-Z][a-z]+\s+[A-Z][a-z]+\s*:)/).filter(Boolean);
return split.length > 1
? split.map(text => {
const [name, ...traitParts] = text.split(/[:]/);
return { name: name.trim(), trait: traitParts.join(":").trim() };
}).filter(n => n.name && n.trait?.length > 10)
: npcs;
};
const parseTreasureText = (text, idx, splitTreasures) => {
if (idx === splitTreasures.length - 1 && text.length < 40) {
return { name: splitTreasures[idx - 1]?.split(/\s+/).slice(-2).join(" ") || `Treasure ${idx}`, description: text };
}
const dashSplit = text.split(/[—]/);
if (dashSplit.length === 2) return { name: dashSplit[0].trim(), description: dashSplit[1].trim() };
if (text.length < 30 && /^[A-Z]/.test(text)) return { name: text.trim(), description: "" };
return null;
};
const splitCombinedTreasures = (treasure) => {
const shouldSplit = treasure.length === 1 && treasure[0].description?.length > 60;
if (!shouldSplit) return treasure;
console.warn("Treasures appear combined, attempting to split...");
const split = treasure[0].description.split(/\s+—\s+/).filter(Boolean);
if (split.length <= 1) return treasure;
const parsed = split.map((text, idx) => parseTreasureText(text, idx, split)).filter(t => t?.name && t?.description);
if (parsed.length > 0) return parsed;
const nameDescPairs = treasure[0].description.match(/([A-Z][^—]+?)\s+—\s+([^—]+?)(?=\s+[A-Z][^—]+\s+—|$)/g);
return nameDescPairs
? nameDescPairs.map(pair => {
const match = pair.match(/([^—]+)\s+—\s+(.+)/);
return match ? { name: match[1].trim(), description: match[2].trim() } : null;
}).filter(t => t)
: treasure;
};
function extractCanonicalNames(dungeonData) {
const names = {
npcs: [],
rooms: [],
factions: []
};
// Extract NPC names
if (dungeonData.npcs) {
dungeonData.npcs.forEach(npc => {
if (npc.name) names.npcs.push(npc.name.trim());
});
}
// Extract room names
if (dungeonData.rooms) {
dungeonData.rooms.forEach(room => {
if (room.name) names.rooms.push(room.name.trim());
});
}
// Extract faction names from core concepts (if available)
if (dungeonData.coreConcepts) {
const factionMatch = dungeonData.coreConcepts.match(/Primary Faction[:\s]+([^\.]+)/i);
if (factionMatch) {
names.factions.push(factionMatch[1].trim());
}
}
return names;
}
function validateNameConsistency(dungeonData) {
const canonicalNames = extractCanonicalNames(dungeonData);
const fixes = [];
// Fix NPC names in all text fields - ensure consistency across all references
canonicalNames.npcs.forEach(canonicalName => {
// Check and fix in flavor text
if (dungeonData.flavor) {
const original = dungeonData.flavor;
// Use canonical name as the source of truth
dungeonData.flavor = dungeonData.flavor.replace(new RegExp(canonicalName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), canonicalName);
if (original !== dungeonData.flavor) {
fixes.push(`Fixed NPC name in flavor text: ${canonicalName}`);
}
}
// Check and fix in hooks
if (dungeonData.hooksRumors) {
dungeonData.hooksRumors = dungeonData.hooksRumors.map(hook => {
const original = hook;
const fixed = hook.replace(new RegExp(canonicalName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), canonicalName);
if (original !== fixed) {
fixes.push(`Fixed NPC name in hook: ${canonicalName}`);
}
return fixed;
});
}
// Check and fix in encounters
if (dungeonData.encounters) {
dungeonData.encounters.forEach(encounter => {
if (encounter.details) {
const original = encounter.details;
encounter.details = encounter.details.replace(new RegExp(canonicalName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), canonicalName);
if (original !== encounter.details) {
fixes.push(`Fixed NPC name in encounter: ${canonicalName}`);
}
}
});
}
// Check and fix in plot resolutions
if (dungeonData.plotResolutions) {
dungeonData.plotResolutions = dungeonData.plotResolutions.map(resolution => {
const original = resolution;
const fixed = resolution.replace(new RegExp(canonicalName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), canonicalName);
if (original !== fixed) {
fixes.push(`Fixed NPC name in plot resolution: ${canonicalName}`);
}
return fixed;
});
}
});
// Fix room names in encounters and other text
canonicalNames.rooms.forEach(canonicalRoom => {
if (dungeonData.encounters) {
dungeonData.encounters.forEach(encounter => {
if (encounter.details) {
const original = encounter.details;
encounter.details = encounter.details.replace(new RegExp(canonicalRoom.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'), canonicalRoom);
if (original !== encounter.details) {
fixes.push(`Fixed room name in encounter: ${canonicalRoom}`);
}
}
});
}
});
return fixes;
}
function standardizeEncounterLocations(encounters, rooms) {
if (!encounters || !rooms) return { encounters, fixes: [] };
const roomNames = rooms.map(r => r.name.trim());
const fixes = [];
const fixedEncounters = encounters.map(encounter => {
if (!encounter.details) return encounter;
let details = encounter.details.trim();
const original = details;
// Check if details start with a room name
for (const roomName of roomNames) {
// Check for room name at start (with or without colon)
const roomNameRegex = new RegExp(`^${roomName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*:?\\s*`, 'i');
if (roomNameRegex.test(details)) {
// Already has location, ensure format is "Location: Description"
if (!details.match(new RegExp(`^${roomName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}:`, 'i'))) {
details = details.replace(roomNameRegex, `${roomName}: `);
fixes.push(`Standardized location format for encounter: ${encounter.name}`);
}
break;
}
}
if (original !== details) {
encounter.details = details;
}
return encounter;
});
return { encounters: fixedEncounters, fixes };
}
function validateAndFixContent(dungeonData) {
const allFixes = [];
// Validate name consistency
const nameFixes = validateNameConsistency(dungeonData);
allFixes.push(...nameFixes);
// Standardize encounter locations
if (dungeonData.encounters && dungeonData.rooms) {
const locationResult = standardizeEncounterLocations(dungeonData.encounters, dungeonData.rooms);
dungeonData.encounters = locationResult.encounters;
allFixes.push(...locationResult.fixes);
}
if (allFixes.length > 0) {
console.log("\n[Validation] Applied fixes:");
allFixes.forEach(fix => console.log(` - ${fix}`));
}
return dungeonData;
}
export async function generateDungeon() {
// Step 1: Titles
const generatedTitlesRaw = await callOllama(
`Generate 50 short, punchy dungeon titles (max 5 words each), numbered as a plain text list.
Each title should come from a different style or theme. Make the set varied and evocative. For example:
- OSR / classic tabletop: gritty, mysterious, old-school
- Mörk Borg: dark, apocalyptic, foreboding
- Pulpy fantasy: adventurous, dramatic, larger-than-life
- Mildly sci-fi: alien, technological, strange
- Weird fantasy: uncanny, surreal, unsettling
- Whimsical: fun, quirky, playful
CRITICAL: Ensure all spelling is correct. Double-check all words before outputting.
Avoid repeating materials or adjectives. Absolutely do not use the words "Obsidian" or "Clockwork" in any title. Do not include explanations, markdown, or preambles. Do not include the style or theme in parenthesis. Only the 50 numbered titles.`,
undefined, 5, "Step 1: Titles"
);
const generatedTitles = parseList(generatedTitlesRaw);
console.log("Generated Titles:", generatedTitles);
const title = generatedTitles[Math.floor(Math.random() * generatedTitles.length)];
console.log("Selected title:", title);
// Step 2: Core Concepts
const coreConceptsRaw = await callOllama(
`For a dungeon titled "${title}", generate three core concepts: a central conflict, a primary faction, and a major environmental hazard or dynamic element.
Output as a numbered list with bolded headings. Plain text only. Absolutely do not use the word "Obsidian" or "obsidian" anywhere in the output.
Example:
1. **Central Conflict:** The dungeon's power source is failing, causing reality to warp.
2. **Primary Faction:** A group of rival cultists trying to seize control of the power source.
3. **Dynamic Element:** Zones of temporal distortion that cause random, brief time shifts.`,
undefined, 5, "Step 2: Core Concepts"
);
const coreConcepts = coreConceptsRaw;
console.log("Core Concepts:", coreConcepts);
// Step 3: Flavor Text & Hooks
const flavorHooksRaw = await callOllama(
`Based on the title "${title}" and these core concepts:
${coreConcepts}
Write a single evocative paragraph describing the location. Maximum 2 sentences. Maximum 100 words. Then, generate 4-5 short adventure hooks or rumors.
The hooks should reference the central conflict, faction, and dynamic element. Hooks should suggest different approaches (stealth, diplomacy, force, exploration) and create anticipation.
CRITICAL: Hooks must be concise to fit in a single column on a one-page dungeon layout. Each hook must be a maximum of 35 words.
CRITICAL: Ensure all spelling is correct. Double-check all words, especially proper nouns and technical terms.
Output two sections labeled "Description:" and "Hooks & Rumors:". Use a numbered list for the hooks. Plain text only. Do not use em-dashes (—) anywhere in the output. Absolutely do not use the word "Obsidian" or "obsidian" anywhere in the output.`,
undefined, 5, "Step 3: Flavor & Hooks"
);
const [flavorSection, hooksSection] = flavorHooksRaw.split(/Hooks & Rumors[:\n]/i);
const flavor = cleanText(flavorSection.replace(/Description[:\n]*/i, ""));
const hooksRumors = parseList(hooksSection || "");
console.log("Flavor Text:", flavor);
console.log("Hooks & Rumors:", hooksRumors);
// Step 4: Key Rooms
const keyRoomsRaw = await callOllama(
`Based on the title "${title}", description "${flavor}", and these core concepts:
${coreConcepts}
Generate two key rooms that define the dungeon's narrative arc.
CRITICAL: These rooms need rich environmental and tactical details with multiple interaction possibilities.
1. Entrance Room: Give it a name (max 5 words) and a description (30-40 words) that includes:
- Immediate observable features and environmental details (lighting, sounds, smells, textures, temperature, visibility)
- Interactable elements that players can use (levers, objects, portals, mechanisms, environmental hazards)
- Tactical considerations (cover, elevation, movement restrictions, line of sight)
- Sets the tone and introduces the environmental hazard/dynamic element
2. Climax Room: Give it a name (max 5 words) and a description (35-45 words) that includes:
- Connection to the primary faction and the central conflict
- Rich environmental and tactical details
- Multiple approach options or solutions
- Tactical considerations and environmental factors that affect gameplay
EXACT FORMAT REQUIRED - each room on its own numbered line:
1. Room Name: Description text here.
2. Room Name: Description text here.
CRITICAL: Ensure all spelling is correct. Double-check all words before outputting.
Output ONLY the two numbered items, one per line. Use colons (:) to separate room names from descriptions, not em-dashes. Do not use em-dashes (—) anywhere. Do not combine items. Do not use bolded headings. Do not include any intro or other text. Absolutely do not use the word "Obsidian" or "obsidian" anywhere in the output.`,
undefined, 5, "Step 4: Key Rooms"
);
const [entranceSection, climaxSection] = keyRoomsRaw.split(/\n?2[).] /); // Split on "2. " to separate the two rooms
const entranceRoom = parseObjects(entranceSection, "rooms")[0];
const climaxRoom = parseObjects(`1. ${climaxSection}`, "rooms")[0]; // Prepend "1. " to make parsing consistent
console.log("Entrance Room:", entranceRoom);
console.log("Climax Room:", climaxRoom);
// Step 5: Main Content (Locations, Encounters, NPCs, Treasures, Random Events)
const mainContentRaw = await callOllama(
`Based on the following dungeon elements and the need for narrative flow:
Title: "${title}"
Description: "${flavor}"
Core Concepts:
${coreConcepts}
Entrance Room: ${JSON.stringify(entranceRoom)}
Climax Room: ${JSON.stringify(climaxRoom)}
Generate the rest of the dungeon's content to fill the space between the entrance and the climax. CRITICAL: All content must fit on a single one-page dungeon layout with three columns. Keep descriptions rich and evocative with tactical/environmental details.
- **Strictly 3 Locations (EXACTLY 3, no more, no less):** Each with a name (max 6 words) and a description (30-40 words). Each room must include:
- Rich environmental features that affect gameplay (lighting, sounds, smells, textures, temperature, visibility)
- Interactable elements that players can use (levers, objects, portals, mechanisms, environmental hazards)
- Multiple approaches or solutions to challenges in the room
- Tactical considerations (cover, elevation, movement restrictions, line of sight)
- Hidden aspects discoverable through interaction or investigation
Format as "Name: description" using colons, NOT em-dashes.
- **Strictly 6 Encounters:** Numbered 1-6 (for d6 rolling). Name (max 6 words) and details (90-120 words per encounter). Each encounter must:
- Start with the room/location name followed by a colon, then the details (e.g., "Location Name: Details text")
- The location name must match one of the actual room names from this dungeon
- Include environmental hazards/opportunities (cover, elevation, traps, interactable objects, terrain features)
- Include tactical considerations (positioning, line of sight, escape routes, bottlenecks, high ground)
- Offer multiple resolution options (combat, negotiation, stealth, puzzle-solving, environmental manipulation, timing-based solutions)
- Include consequences and outcomes tied to player choices
- Integrate with the environmental dynamic element from core concepts
- At least two encounters must be directly tied to the primary faction
Format as "Name: Location Name: details" using colons, NOT em-dashes. CRITICAL: Always start encounter details with the location name and a colon.
- **Strictly 4-5 NPCs:** Proper name (max 4 words) and a description (60-80 words). Each NPC must include:
- Clear motivation or goal
- Relationship to primary faction
- How they can help or hinder the party
- Quirks or memorable traits
- Multiple interaction possibilities (negotiation, intimidation, help, betrayal)
- One NPC should be a key figure tied to the central conflict
- One should be a member of the primary faction, one should be a potential ally, one should be a rival
Format as "Name: description" using colons, NOT em-dashes.
- **Strictly 4-5 Treasures:** Name (max 5 words) and a description (40-50 words). Each treasure must:
- Include a clear danger or side-effect
- Be connected to a specific encounter, NPC, or room
- Have story significance beyond just value
- Have potential for creative use beyond obvious purpose
- Some should be cursed, have activation requirements, or serve dual purposes
Format as "Name — Description" using em-dash.
- **Strictly 1 Random Events Table:** A d6 table (exactly 6 entries) with random events/wandering encounters. Each entry should:
- Provide interesting complications or opportunities (not just combat)
- Tie to the core concepts and dynamic element
- Add replayability and surprise
Format as numbered 1-6 list under "Random Events:" label.
CRITICAL: Each item must be on its own numbered line. DO NOT combine multiple items into a single numbered entry.
EXACT FORMAT REQUIRED:
Locations:
1. Location Name: Description text.
2. Location Name: Description text.
3. Location Name: Description text.
Encounters:
1. Encounter Name: Location Name: Details text.
2. Encounter Name: Location Name: Details text.
3. Encounter Name: Location Name: Details text.
4. Encounter Name: Location Name: Details text.
5. Encounter Name: Location Name: Details text.
6. Encounter Name: Location Name: Details text.
NPCs:
1. NPC Name: Description text.
2. NPC Name: Description text.
3. NPC Name: Description text.
4. NPC Name: Description text.
Treasures:
1. Treasure Name — Description text.
2. Treasure Name — Description text.
3. Treasure Name — Description text.
4. Treasure Name — Description text.
Random Events:
1. Event description.
2. Event description.
3. Event description.
4. Event description.
5. Event description.
6. Event description.
CRITICAL: Ensure all spelling is correct. Double-check all words, especially proper nouns, character names, and location names. Verify consistency of names across all sections.
Output as five separate numbered lists with these exact labels: "Locations:", "Encounters:", "NPCs:", "Treasures:", and "Random Events:". Each item must be on its own line starting with a number. Do not combine items. Do not use any bolding, preambles, or extra text. Do not use em-dashes (—) in encounters or NPCs, only use colons for those sections. Absolutely do not use the word "Obsidian" or "obsidian" anywhere in the output.`,
undefined, 5, "Step 5: Main Content"
);
const [intermediateRoomsSection, encountersSection, npcsSection, treasureSection, randomEventsSection] = mainContentRaw.split(/Encounters:|NPCs:|Treasures?:|Random Events:/i);
const intermediateRooms = parseObjects(intermediateRoomsSection.replace(/Locations:/i, ""), "rooms");
// Limit to exactly 3 intermediate rooms to ensure total of 5 rooms (entrance + 3 intermediate + climax)
const limitedIntermediateRooms = intermediateRooms.slice(0, 3);
if (intermediateRooms.length > 3) {
console.warn(`Expected exactly 3 intermediate locations but got ${intermediateRooms.length}, limiting to first 3`);
}
const rooms = [entranceRoom, ...limitedIntermediateRooms, climaxRoom];
const encounters = splitCombinedEncounters(parseObjects(encountersSection || "", "encounters"));
const npcs = splitCombinedNPCs(parseObjects(npcsSection || "", "npcs"));
const treasure = splitCombinedTreasures(parseObjects(treasureSection || "", "treasure"));
const randomEvents = parseList(randomEventsSection || "");
[[encounters, 6, 'encounters'], [npcs, 4, 'NPCs'], [treasure, 4, 'treasures'], [randomEvents, 6, 'random events']]
.filter(([arr, expected]) => arr.length < expected && arr.length > 0)
.forEach(([arr, expected, name]) => console.warn(`Expected at least ${expected} ${name} but got ${arr.length}`));
console.log("Rooms:", rooms);
console.log("Encounters:", encounters);
console.log("NPCs:", npcs);
console.log("Treasure:", treasure);
console.log("Random Events:", randomEvents);
// Step 6: Player Choices and Consequences
const npcNamesList = npcs.map(n => n.name).join(", ");
const factionName = coreConcepts.match(/Primary Faction[:\s]+([^\.]+)/i)?.[1]?.trim() || "the primary faction";
const plotResolutionsRaw = await callOllama(
`Based on all of the following elements, suggest 4-5 possible, non-conflicting story climaxes or plot resolutions for adventurers exploring this location. Each resolution must provide a meaningful choice with a tangible consequence, directly related to the Central Conflict, the Primary Faction, or the NPCs.
Dungeon Elements:
${JSON.stringify({ title, flavor, hooksRumors, rooms, encounters, treasure, npcs, coreConcepts }, null, 2)}
CRITICAL: This content must fit in a single column on a one-page dungeon layout. Keep descriptions meaningful but concise.
Start each item with phrases like "The adventurers could" or "The adventurers might". Do not use "PCs" or "player characters" - always use "adventurers" instead.
IMPORTANT: When referencing NPCs, use these exact names with correct spelling: ${npcNamesList}. When referencing the faction, use: ${factionName}. Ensure all names are spelled consistently and correctly.
CRITICAL: Double-check all spelling before outputting. Verify all proper nouns match exactly as provided above.
Each resolution should:
- Offer meaningful choice with clear consequences
- Integrate NPCs, faction dynamics, and player actions
- Include failure states or unexpected outcomes as options
- Reflect different approaches players might take
Keep each item to 50-60 words (2-3 sentences). Output as a numbered list, plain text only. Do not use em-dashes (—) anywhere in the output. Absolutely do not use the word "Obsidian" or "obsidian" anywhere in the output.`,
undefined, 5, "Step 6: Plot Resolutions"
);
const plotResolutions = parseList(plotResolutionsRaw);
console.log("Plot Resolutions:", plotResolutions);
// Step 7: Validation and Content Fixing
console.log("\n[Validation] Running content validation and fixes...");
const dungeonData = {
title,
flavor,
map: "map.png",
hooksRumors,
rooms,
encounters,
treasure,
npcs,
plotResolutions,
randomEvents,
coreConcepts
};
const validatedData = validateAndFixContent(dungeonData);
console.log("\nDungeon generation complete!");
return validatedData;
}