import { callOllama } from "./ollamaClient.js"; import { cleanText } from "./textUtils.js"; import { parseList, parseObjects, parseMainContentSections, parseRandomEventsRaw, splitCombinedEncounters, } from "./parsing.js"; import { deduplicateRoomsByName, padNpcsToMinimum, buildEncountersList, mergeRandomEventsWithFallbacks, limitIntermediateRooms, fixRoomPlaceholderName, } from "./dungeonBuild.js"; import { validateAndFixContent } from "./contentFixes.js"; export async function generateDungeon() { // Step 1: Titles const generatedTitles = 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. Do not include the theme in the name of the title (no parenthesis).`, undefined, 5, "Step 1: Titles" ); console.log("Generated Titles:", generatedTitles); const titlesList = parseList(generatedTitles); const title = titlesList[Math.floor(Math.random() * titlesList.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 50-60 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. EXAMPLE OF GOOD HOOK: "A merchant's cart was found abandoned near the entrance, its cargo of rare herbs scattered. The merchant's journal mentions strange lights in the depths and a warning about 'the watchers'." CRITICAL: Hooks must be concise to fit in a single column on a one-page dungeon layout. Each hook must be 25-30 words maximum. Be specific with details, not vague. 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 rawFlavor = cleanText(flavorSection.replace(/Description[:\n]*/i, "")); const flavorWords = rawFlavor.split(/\s+/); const flavor = flavorWords.length > 60 ? flavorWords.slice(0, 60).join(' ') + '...' : rawFlavor; const hooksRumors = parseList(hooksSection || "").map(h => h.replace(/^[^:]+:\s*/, '').trim()); 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. EXAMPLE OF GOOD ROOM DESCRIPTION: "Chamber of Echoes: Flickering torchlight casts dancing shadows across moss-covered walls. A constant dripping echoes from stalactites overhead, and the air smells of damp earth and ozone. Three stone pillars provide cover, while a raised dais in the center offers high ground. A rusted lever on the west wall controls a hidden portcullis. The floor is slick with moisture, making movement difficult." 1. Entrance Room: Give it a name (max 5 words) and a description (25-35 words) that MUST include: - 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 (25-35 words) that MUST include: - 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. CRITICAL: Be specific and concrete. Avoid vague words like "some", "various", "several" without details. 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[).] /); const entranceRoom = parseObjects(entranceSection, "rooms")[0]; const climaxRoom = parseObjects(`1. ${climaxSection}`, "rooms")[0]; if (entranceRoom) fixRoomPlaceholderName(entranceRoom); if (climaxRoom) fixRoomPlaceholderName(climaxRoom); console.log("Entrance Room:", entranceRoom); console.log("Climax Room:", climaxRoom); // Step 5: Main Content (Locations, Encounters, NPCs, Treasures, Random Events) // To avoid overloading the AI server with a single huge prompt, we generate // each section in smaller, focused calls and then stitch them together. const sharedContext = `Title: "${title}" Description: "${flavor}" Core Concepts: ${coreConcepts} Entrance Room: ${JSON.stringify(entranceRoom)} Climax Room: ${JSON.stringify(climaxRoom)}`; const locationsRaw = await callOllama( `${sharedContext} Generate EXACTLY 3 intermediate dungeon locations between the entrance and climax. Requirements: - Each location gets a unique name (max 6 words) and a description (25-35 words). - Include sensory details and environmental features that affect gameplay (lighting, sounds, smells, textures, temperature, visibility). - Include interactable elements (levers, objects, portals, mechanisms, environmental hazards). - Include tactical considerations (cover, elevation, movement restrictions, line of sight) and at least one hidden aspect per room. Format: 1. Room Name: Description text. 2. Room Name: Description text. 3. Room Name: Description text. Plain text only. Do not use em-dashes (—). Absolutely do not use the word "Obsidian" or "obsidian" anywhere in the output.`, undefined, 5, "Step 5a: Locations" ); const encountersRaw = await callOllama( `${sharedContext} Existing rooms: - Entrance: ${entranceRoom?.name} - Climax: ${climaxRoom?.name} You will add 3 more locations (from the locations list) and must reference only real room names. Generate EXACTLY 6 encounters, numbered 1-6 for a d6 table. Requirements: - Name (max 6 words) and details (2 sentences MAX, ~25-40 words). - Each encounter MUST start with the room/location name followed by a colon, then the details (e.g., "Room Name: details"). - The location name must match either the entrance room, climax room, or one of the 3 new locations. - Include environmental hazards/opportunities and tactical considerations (cover, elevation, traps, bottlenecks, escape routes, high ground). - Offer multiple resolution options (combat, negotiation, stealth, puzzle-solving, environmental manipulation, timing, etc.). - At least two encounters must be directly tied to the primary faction from the core concepts. Format: 1. Encounter Name: Room Name: Details text. 2. Encounter Name: Room Name: Details text. 3. Encounter Name: Room Name: Details text. 4. Encounter Name: Room Name: Details text. 5. Encounter Name: Room Name: Details text. 6. Encounter Name: Room Name: Details text. Plain text only. Use colons, NOT em-dashes. Absolutely do not use the word "Obsidian" or "obsidian" anywhere in the output.`, undefined, 5, "Step 5b: Encounters" ); const npcsRaw = await callOllama( `${sharedContext} Generate 4-5 important NPCs tied to this dungeon. Requirements: - Proper name (max 4 words) and a description (50-65 words). - Each NPC must have: clear motivation, relationship to the primary faction, how they can help or hinder the adventurers, and memorable quirks/traits. - Include multiple interaction possibilities (negotiation, intimidation, help, betrayal). - At least one NPC is a key figure tied to the central conflict. - At least one NPC is a member of the primary faction, one is a potential ally, and one is a rival. Format: 1. NPC Name: Description text. 2. NPC Name: Description text. 3. NPC Name: Description text. 4. NPC Name: Description text. 5. NPC Name: Description text. (omit the 5th if only 4 NPCs) Plain text only. Use colons, NOT em-dashes. Absolutely do not use the word "Obsidian" or "obsidian" anywhere in the output.`, undefined, 5, "Step 5c: NPCs" ); const treasuresRaw = await callOllama( `${sharedContext} Generate 4-5 unique treasures for this dungeon. Requirements: - Each treasure has a name (max 5 words) and a description (30-40 words). - Each treasure includes a clear danger or side-effect. - Each treasure is connected to a specific encounter, NPC, or room. - Each has story significance beyond raw value and potential for creative non-obvious uses. - Some should be cursed, have activation requirements, or serve dual purposes. Format: 1. Item Name — Description text. 2. Item Name — Description text. 3. Item Name — Description text. 4. Item Name — Description text. 5. Item Name — Description text. (omit the 5th if only 4 treasures) Plain text only. Use an em-dash (—) between name and description. Absolutely do not use the word "Obsidian" or "obsidian" anywhere in the output.`, undefined, 5, "Step 5d: Treasures" ); const randomEventsRaw = await callOllama( `${sharedContext} Generate a d6 Random Events table for this dungeon (EXACTLY 6 entries). Requirements: - Short, evocative event name (max 4 words) plus description (15-20 words). - Provide interesting complications or opportunities (not just combat). - Tie directly to the core concepts and the dynamic environmental element. - Each event must be UNIQUE and clearly different from the others. Format: Random Events: 1. Event Name: Description text. 2. Event Name: Description text. 3. Event Name: Description text. 4. Event Name: Description text. 5. Event Name: Description text. 6. Event Name: Description text. Plain text only. Use colons, NOT em-dashes. Absolutely do not use the word "Obsidian" or "obsidian" anywhere in the output.`, undefined, 5, "Step 5e: Random Events" ); const mainContentRaw = [ "Locations:", locationsRaw.trim(), "", "Encounters:", encountersRaw.trim(), "", "NPCs:", npcsRaw.trim(), "", "Treasures:", treasuresRaw.trim(), "", "Random Events:", randomEventsRaw.replace(/Random Events:\s*/i, "").trim(), ].join("\n"); const { intermediateRoomsSection, encountersSection, npcsSection, treasureSection, randomEventsSection } = parseMainContentSections(mainContentRaw); const intermediateRooms = parseObjects(intermediateRoomsSection.replace(/Locations:/i, ""), "rooms"); const limitedIntermediateRooms = limitIntermediateRooms(intermediateRooms, 3); const allRooms = [entranceRoom, ...limitedIntermediateRooms, climaxRoom].filter(Boolean); const rooms = deduplicateRoomsByName(allRooms); const parsedEncounters = splitCombinedEncounters(parseObjects(encountersSection || "", "encounters")); const parsedNpcs = parseObjects(npcsSection || "", "npcs"); const treasure = parseObjects(treasureSection || "", "treasure"); const npcs = padNpcsToMinimum(parsedNpcs, coreConcepts, 4); const encounters = buildEncountersList(parsedEncounters, rooms, coreConcepts); const randomEventsFilteredMapped = parseRandomEventsRaw(randomEventsSection || ""); const randomEvents = mergeRandomEventsWithFallbacks(randomEventsFilteredMapped, coreConcepts, 6); [[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 factionName = coreConcepts.match(/Primary Faction[:\s]+([^.]+)/i)?.[1]?.trim() || 'the primary faction'; const npcNamesList = npcs.map(n => n.name).join(", "); 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. EXAMPLE PLOT RESOLUTION: "The adventurers could ally with the primary faction, gaining access to their resources but becoming enemies of the rival group. This choice unlocks new areas but closes off diplomatic solutions with other NPCs." 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 MUST: - 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 1-2 sentences MAX (approximately 15-25 words). Be extremely concise. 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; }