Compare commits
4 Commits
2026-01-19
...
2026-02-16
| Author | SHA1 | Date | |
|---|---|---|---|
| 07128c3529 | |||
| 5588108cb6 | |||
| e66df13edd | |||
| 96223b81e6 |
@@ -12,10 +12,27 @@ function cleanText(str) {
|
||||
}
|
||||
|
||||
function parseList(raw) {
|
||||
return raw
|
||||
.split(/\n?\d+[).]\s+/)
|
||||
.map(line => cleanText(line))
|
||||
if (!raw) return [];
|
||||
|
||||
// Match all numbered items using a regex that captures the content
|
||||
// This handles both "1. Title" and "1) Title" formats, and works even if multiple titles are on one line
|
||||
// The regex captures everything after the number until the next number pattern or end of string
|
||||
// Using [\s\S] to match any character including newlines, but stop at the next number pattern
|
||||
const NUMBERED_ITEM_REGEX = /\d+[).]\s+([\s\S]+?)(?=\s*\d+[).]\s+|$)/g;
|
||||
|
||||
const items = Array.from(raw.matchAll(NUMBERED_ITEM_REGEX))
|
||||
.map(match => match[1].trim())
|
||||
.filter(Boolean)
|
||||
.map(cleanText)
|
||||
.filter(Boolean);
|
||||
|
||||
// Fallback: if regex didn't work, try the old method
|
||||
return items.length > 0
|
||||
? items
|
||||
: raw
|
||||
.split(/\n?\d+[).]\s+/)
|
||||
.map(line => cleanText(line))
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function parseObjects(raw, type = "rooms") {
|
||||
@@ -47,6 +64,18 @@ function parseObjects(raw, type = "rooms") {
|
||||
return null;
|
||||
}
|
||||
// For other types, use original logic
|
||||
if (type === "treasure") {
|
||||
const parts = entry.split(/[—]/);
|
||||
if (parts.length >= 2) {
|
||||
const cleanName = parts[0].trim();
|
||||
if (cleanName.toLowerCase().includes('treasure name') || cleanName.toLowerCase().includes('actual ')) {
|
||||
return null;
|
||||
}
|
||||
let desc = parts.slice(1).join(' ').trim();
|
||||
desc = desc.replace(/^description\s*:?\s*/i, '').trim();
|
||||
return { name: cleanName, description: desc };
|
||||
}
|
||||
}
|
||||
const [name, ...descParts] = entry.split(/[-–—:]/);
|
||||
const cleanName = name.trim();
|
||||
// Skip placeholder names
|
||||
@@ -56,7 +85,8 @@ function parseObjects(raw, type = "rooms") {
|
||||
cleanName.toLowerCase().includes('actual ')) {
|
||||
return null;
|
||||
}
|
||||
const desc = descParts.join(" ").trim();
|
||||
let desc = descParts.join(" ").trim();
|
||||
if (type === "npcs") desc = desc.replace(/^description\s*:?\s*/i, '').trim();
|
||||
const obj = { name: cleanName };
|
||||
if (type === "rooms") return { ...obj, description: desc };
|
||||
if (type === "npcs") return { ...obj, trait: desc };
|
||||
@@ -67,6 +97,18 @@ function parseObjects(raw, type = "rooms") {
|
||||
}
|
||||
|
||||
const parseEncounterText = (text, idx) => {
|
||||
// Handle "Encounter N Name Room Name Details" format
|
||||
const encounterMatch = text.match(/Encounter\s+(\d+)\s+(.+?)\s+(?:Room Name|Location)\s+(.+?)\s+Details\s+(.+)/i);
|
||||
if (encounterMatch) {
|
||||
const [, , name, location, details] = encounterMatch;
|
||||
return { name: name.trim(), details: `${location.trim()}: ${details.trim()}` };
|
||||
}
|
||||
// Handle "Encounter N Name: Location: Details" format
|
||||
const colonFormat = text.match(/Encounter\s+\d+\s+(.+?):\s*(.+?):\s*(.+)/i);
|
||||
if (colonFormat) {
|
||||
const [, name, location, details] = colonFormat;
|
||||
return { name: name.trim(), details: `${location.trim()}: ${details.trim()}` };
|
||||
}
|
||||
const match = text.match(/^(\d+)\s+(.+?)(?::\s*(.+))?$/);
|
||||
if (match) {
|
||||
const [, , name, details] = match;
|
||||
@@ -75,7 +117,7 @@ const parseEncounterText = (text, idx) => {
|
||||
const colonSplit = text.split(/[:]/);
|
||||
if (colonSplit.length > 1) {
|
||||
return {
|
||||
name: colonSplit[0].replace(/^\d+\s+/, "").trim(),
|
||||
name: colonSplit[0].replace(/^\d+\s+|Encounter\s+\d+\s+/i, "").trim(),
|
||||
details: colonSplit.slice(1).join(":").trim()
|
||||
};
|
||||
}
|
||||
@@ -86,17 +128,18 @@ const parseEncounterText = (text, idx) => {
|
||||
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() };
|
||||
return { name: `Encounter ${idx + 1}`, details: text.replace(/^\d+\s+|Encounter\s+\d+\s+/i, "").trim() };
|
||||
};
|
||||
|
||||
const splitCombinedEncounters = (encounters) => {
|
||||
const shouldSplit = encounters.length === 1 && (encounters[0].name === "1" || encounters[0].details.match(/\d+\s+[A-Z]/));
|
||||
if (encounters.length === 0) return [];
|
||||
const shouldSplit = encounters.length === 1 && (encounters[0].name === "1" || encounters[0].details?.match(/\d+\s+[A-Z]/) || encounters[0].details?.includes('Encounter'));
|
||||
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);
|
||||
const split = combinedText.split(/(?=Encounter\s+\d+|\d+\s+[A-Z][a-z])/i).filter(Boolean);
|
||||
return (split.length > 1 || (split.length === 1 && combinedText.length > 100))
|
||||
? split.map(parseEncounterText).filter(e => e?.name && e?.details?.length > 10)
|
||||
? split.map((text, idx) => parseEncounterText(text, idx)).filter(e => e?.name && e?.details?.length > 10)
|
||||
: encounters;
|
||||
};
|
||||
|
||||
@@ -405,6 +448,207 @@ function validateNarrativeCoherence(dungeonData) {
|
||||
return issues;
|
||||
}
|
||||
|
||||
function fixStructureIssues(dungeonData) {
|
||||
const fixes = [];
|
||||
|
||||
// Fix missing or invalid room names
|
||||
if (dungeonData.rooms) {
|
||||
dungeonData.rooms.forEach((room, i) => {
|
||||
if (!room.name || !room.name.trim()) {
|
||||
// Extract name from description if possible
|
||||
const desc = room.description || '';
|
||||
const nameMatch = desc.match(/^([A-Z][^.!?]{5,30}?)(?:\s|\.|:)/);
|
||||
if (nameMatch) {
|
||||
room.name = nameMatch[1].trim();
|
||||
fixes.push(`Extracted room name from description: "${room.name}"`);
|
||||
} else {
|
||||
room.name = `Room ${i + 1}`;
|
||||
fixes.push(`Added default name for room ${i + 1}`);
|
||||
}
|
||||
}
|
||||
// Truncate overly long room names
|
||||
const words = room.name.split(/\s+/);
|
||||
if (words.length > 6) {
|
||||
const original = room.name;
|
||||
room.name = words.slice(0, 6).join(' ');
|
||||
fixes.push(`Truncated room name: "${original}" -> "${room.name}"`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Fix missing or invalid encounter names
|
||||
if (dungeonData.encounters) {
|
||||
dungeonData.encounters.forEach((encounter, i) => {
|
||||
if (!encounter.name || !encounter.name.trim()) {
|
||||
// Extract name from details if possible
|
||||
const details = encounter.details || '';
|
||||
const nameMatch = details.match(/^([^:]+):\s*(.+)$/);
|
||||
if (nameMatch) {
|
||||
encounter.name = nameMatch[1].trim();
|
||||
encounter.details = nameMatch[2].trim();
|
||||
fixes.push(`Extracted encounter name from details: "${encounter.name}"`);
|
||||
} else {
|
||||
encounter.name = `Encounter ${i + 1}`;
|
||||
fixes.push(`Added default name for encounter ${i + 1}`);
|
||||
}
|
||||
}
|
||||
// Truncate overly long encounter names
|
||||
const words = encounter.name.split(/\s+/);
|
||||
if (words.length > 6) {
|
||||
const original = encounter.name;
|
||||
encounter.name = words.slice(0, 6).join(' ');
|
||||
fixes.push(`Truncated encounter name: "${original}" -> "${encounter.name}"`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Fix missing or invalid NPC names
|
||||
if (dungeonData.npcs) {
|
||||
dungeonData.npcs.forEach((npc, i) => {
|
||||
if (!npc.name || !npc.name.trim()) {
|
||||
// Extract name from trait if possible
|
||||
const trait = npc.trait || '';
|
||||
const nameMatch = trait.match(/^([A-Z][a-z]+(?:\s+[A-Z][a-z]+){0,2})(?:\s|:)/);
|
||||
if (nameMatch) {
|
||||
npc.name = nameMatch[1].trim();
|
||||
fixes.push(`Extracted NPC name from trait: "${npc.name}"`);
|
||||
} else {
|
||||
npc.name = `NPC ${i + 1}`;
|
||||
fixes.push(`Added default name for NPC ${i + 1}`);
|
||||
}
|
||||
}
|
||||
// Truncate overly long NPC names
|
||||
const words = npc.name.split(/\s+/);
|
||||
if (words.length > 4) {
|
||||
const original = npc.name;
|
||||
npc.name = words.slice(0, 4).join(' ');
|
||||
fixes.push(`Truncated NPC name: "${original}" -> "${npc.name}"`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return fixes;
|
||||
}
|
||||
|
||||
function fixMissingContent(dungeonData) {
|
||||
const fixes = [];
|
||||
|
||||
// Pad NPCs if needed
|
||||
if (!dungeonData.npcs || dungeonData.npcs.length < 4) {
|
||||
if (!dungeonData.npcs) dungeonData.npcs = [];
|
||||
const factionName = dungeonData.coreConcepts?.match(/Primary Faction[:\s]+([^.]+)/i)?.[1]?.trim() || 'the primary faction';
|
||||
while (dungeonData.npcs.length < 4) {
|
||||
dungeonData.npcs.push({
|
||||
name: `NPC ${dungeonData.npcs.length + 1}`,
|
||||
trait: `A member of ${factionName.toLowerCase()} with unknown motives.`
|
||||
});
|
||||
fixes.push(`Added fallback NPC ${dungeonData.npcs.length}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Pad encounters if needed
|
||||
if (!dungeonData.encounters || dungeonData.encounters.length < 6) {
|
||||
if (!dungeonData.encounters) dungeonData.encounters = [];
|
||||
if (dungeonData.encounters.length > 0 && dungeonData.rooms && dungeonData.rooms.length > 0) {
|
||||
const dynamicElement = dungeonData.coreConcepts?.match(/Dynamic Element[:\s]+([^.]+)/i)?.[1]?.trim() || 'strange occurrences';
|
||||
const conflict = dungeonData.coreConcepts?.match(/Central Conflict[:\s]+([^.]+)/i)?.[1]?.trim() || 'a threat';
|
||||
while (dungeonData.encounters.length < 6) {
|
||||
const roomIndex = dungeonData.encounters.length % dungeonData.rooms.length;
|
||||
const roomName = dungeonData.rooms[roomIndex]?.name || 'Unknown Location';
|
||||
const fallbackNames = [
|
||||
`${roomName} Guardian`,
|
||||
`${roomName} Threat`,
|
||||
`${roomName} Challenge`,
|
||||
`${dynamicElement.split(' ')[0]} Manifestation`,
|
||||
`${conflict.split(' ')[0]} Encounter`,
|
||||
`${roomName} Hazard`
|
||||
];
|
||||
dungeonData.encounters.push({
|
||||
name: fallbackNames[dungeonData.encounters.length % fallbackNames.length],
|
||||
details: `${roomName}: An encounter related to ${dynamicElement.toLowerCase()} occurs here.`
|
||||
});
|
||||
fixes.push(`Added fallback encounter: "${dungeonData.encounters[dungeonData.encounters.length - 1].name}"`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pad treasure if needed
|
||||
if (!dungeonData.treasure || dungeonData.treasure.length < 4) {
|
||||
if (!dungeonData.treasure) dungeonData.treasure = [];
|
||||
while (dungeonData.treasure.length < 4) {
|
||||
dungeonData.treasure.push({
|
||||
name: `Treasure ${dungeonData.treasure.length + 1}`,
|
||||
description: `A mysterious item found in the dungeon.`
|
||||
});
|
||||
fixes.push(`Added fallback treasure ${dungeonData.treasure.length}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Pad random events if needed
|
||||
if (!dungeonData.randomEvents || dungeonData.randomEvents.length < 6) {
|
||||
if (!dungeonData.randomEvents) dungeonData.randomEvents = [];
|
||||
if (dungeonData.randomEvents.length > 0 && dungeonData.coreConcepts) {
|
||||
const dynamicElement = dungeonData.coreConcepts.match(/Dynamic Element[:\s]+([^.]+)/i)?.[1]?.trim() || 'strange occurrences';
|
||||
const conflict = dungeonData.coreConcepts.match(/Central Conflict[:\s]+([^.]+)/i)?.[1]?.trim() || 'a mysterious threat';
|
||||
const fallbackEvents = [
|
||||
{ name: 'Environmental Shift', description: `The ${dynamicElement.toLowerCase()} causes unexpected changes in the environment.` },
|
||||
{ name: 'Conflict Manifestation', description: `A sign of ${conflict.toLowerCase()} appears, requiring immediate attention.` },
|
||||
{ name: 'Dungeon Shift', description: `The dungeon shifts, revealing a previously hidden passage or danger.` },
|
||||
{ name: 'Faction Messenger', description: `An NPC from the primary faction appears with urgent information.` },
|
||||
{ name: 'Power Fluctuation', description: `The power source fluctuates, creating temporary hazards or opportunities.` },
|
||||
{ name: 'Echoes of the Past', description: `Echoes of past events manifest, providing clues or complications.` }
|
||||
];
|
||||
while (dungeonData.randomEvents.length < 6) {
|
||||
dungeonData.randomEvents.push(fallbackEvents[dungeonData.randomEvents.length % fallbackEvents.length]);
|
||||
fixes.push(`Added fallback random event: "${dungeonData.randomEvents[dungeonData.randomEvents.length - 1].name}"`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pad plot resolutions if needed
|
||||
if (!dungeonData.plotResolutions || dungeonData.plotResolutions.length < 4) {
|
||||
if (!dungeonData.plotResolutions) dungeonData.plotResolutions = [];
|
||||
while (dungeonData.plotResolutions.length < 4) {
|
||||
dungeonData.plotResolutions.push(`The adventurers could resolve the central conflict through decisive action.`);
|
||||
fixes.push(`Added fallback plot resolution ${dungeonData.plotResolutions.length}`);
|
||||
}
|
||||
}
|
||||
|
||||
return fixes;
|
||||
}
|
||||
|
||||
function fixNarrativeCoherence(dungeonData) {
|
||||
const fixes = [];
|
||||
|
||||
// Fix encounters referencing unknown locations
|
||||
if (dungeonData.encounters && dungeonData.rooms) {
|
||||
const roomNames = dungeonData.rooms.map(r => r.name.trim().toLowerCase());
|
||||
dungeonData.encounters.forEach(encounter => {
|
||||
if (!encounter.details) return;
|
||||
const locationMatch = encounter.details.match(/^([^:]+):/);
|
||||
if (locationMatch) {
|
||||
const locName = locationMatch[1].trim().toLowerCase();
|
||||
// Check if location matches any room name (fuzzy match)
|
||||
const matches = roomNames.some(rn =>
|
||||
locName === rn ||
|
||||
locName.includes(rn) ||
|
||||
rn.includes(locName) ||
|
||||
locName.split(/\s+/).some(word => rn.includes(word))
|
||||
);
|
||||
if (!matches && roomNames.length > 0) {
|
||||
// Assign to a random room
|
||||
const roomIdx = Math.floor(Math.random() * roomNames.length);
|
||||
const roomName = dungeonData.rooms[roomIdx].name;
|
||||
encounter.details = encounter.details.replace(/^[^:]+:\s*/, `${roomName}: `);
|
||||
fixes.push(`Fixed unknown location in encounter "${encounter.name}" to "${roomName}"`);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return fixes;
|
||||
}
|
||||
|
||||
function validateAndFixContent(dungeonData) {
|
||||
const allFixes = [];
|
||||
const allIssues = [];
|
||||
@@ -413,6 +657,10 @@ function validateAndFixContent(dungeonData) {
|
||||
const nameFixes = validateNameConsistency(dungeonData);
|
||||
allFixes.push(...nameFixes);
|
||||
|
||||
// Fix structure issues (missing names, too long names)
|
||||
const structureFixes = fixStructureIssues(dungeonData);
|
||||
allFixes.push(...structureFixes);
|
||||
|
||||
// Standardize encounter locations and add missing ones
|
||||
if (dungeonData.encounters && dungeonData.rooms) {
|
||||
const roomNames = dungeonData.rooms.map(r => r.name.trim());
|
||||
@@ -432,7 +680,15 @@ function validateAndFixContent(dungeonData) {
|
||||
allFixes.push(...locationResult.fixes);
|
||||
}
|
||||
|
||||
// Run content validation
|
||||
// Fix narrative coherence issues
|
||||
const coherenceFixes = fixNarrativeCoherence(dungeonData);
|
||||
allFixes.push(...coherenceFixes);
|
||||
|
||||
// Fix missing content (pad arrays)
|
||||
const contentFixes = fixMissingContent(dungeonData);
|
||||
allFixes.push(...contentFixes);
|
||||
|
||||
// Run content validation (for reporting remaining issues)
|
||||
const completenessIssues = validateContentCompleteness(dungeonData);
|
||||
const qualityIssues = validateContentQuality(dungeonData);
|
||||
const structureIssues = validateContentStructure(dungeonData);
|
||||
@@ -446,7 +702,7 @@ function validateAndFixContent(dungeonData) {
|
||||
}
|
||||
|
||||
if (allIssues.length > 0) {
|
||||
console.log("\n[Validation] Content quality issues found:");
|
||||
console.log("\n[Validation] Content quality issues found (not auto-fixable):");
|
||||
allIssues.forEach(issue => console.warn(` ⚠ ${issue}`));
|
||||
} else {
|
||||
console.log("\n[Validation] Content quality checks passed");
|
||||
@@ -457,24 +713,24 @@ function validateAndFixContent(dungeonData) {
|
||||
|
||||
export async function generateDungeon() {
|
||||
// Step 1: Titles
|
||||
const generatedTitlesRaw = await callOllama(
|
||||
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.`,
|
||||
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)];
|
||||
const titlesList = parseList(generatedTitles);
|
||||
const title = titlesList[Math.floor(Math.random() * titlesList.length)];
|
||||
console.log("Selected title:", title);
|
||||
|
||||
// Step 2: Core Concepts
|
||||
@@ -494,7 +750,7 @@ Example:
|
||||
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.
|
||||
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:
|
||||
@@ -506,8 +762,11 @@ Output two sections labeled "Description:" and "Hooks & Rumors:". Use a numbered
|
||||
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 || "");
|
||||
let flavor = cleanText(flavorSection.replace(/Description[:\n]*/i, ""));
|
||||
const words = flavor.split(/\s+/);
|
||||
if (words.length > 60) flavor = words.slice(0, 60).join(' ') + '...';
|
||||
let hooksRumors = parseList(hooksSection || "");
|
||||
hooksRumors = hooksRumors.map(h => h.replace(/^[^:]+:\s*/, '').trim());
|
||||
console.log("Flavor Text:", flavor);
|
||||
console.log("Hooks & Rumors:", hooksRumors);
|
||||
|
||||
@@ -632,12 +891,15 @@ EXAMPLE NPC:
|
||||
EXAMPLE TREASURE:
|
||||
"Whispering Blade — This dagger amplifies the wielder's voice to a deafening roar when drawn. Found in the Guardian Golem's chamber, it was used to command the construct. The blade is cursed: each use permanently reduces the wielder's hearing. Can be used to shatter glass or stun enemies, but the curse cannot be removed."
|
||||
|
||||
- **Strictly 1 Random Events Table:** A d6 table (exactly 6 entries) with random events/wandering encounters. Each entry MUST:
|
||||
- **Strictly 1 Random Events Table:** A d6 table (EXACTLY 6 entries, no more, no less) with random events/wandering encounters. Each entry MUST:
|
||||
- Have a short, evocative event name (max 4 words)
|
||||
- Provide interesting complications or opportunities (not just combat)
|
||||
- Tie to the core concepts and dynamic element
|
||||
- Add replayability and surprise
|
||||
- Be 15-20 words maximum
|
||||
Format as numbered 1-6 list under "Random Events:" label.
|
||||
- Description should be 15-20 words maximum
|
||||
- Be UNIQUE and DIFFERENT from each other (no duplicates or generic placeholders)
|
||||
- Be SPECIFIC to this dungeon's theme, conflict, and dynamic element
|
||||
Format as numbered 1-6 list under "Random Events:" label. Each event must be formatted as "Event Name: Description text" using colons, NOT em-dashes.
|
||||
|
||||
CRITICAL: Each item must be on its own numbered line. DO NOT combine multiple items into a single numbered entry.
|
||||
|
||||
@@ -668,31 +930,199 @@ Treasures:
|
||||
4. Actual Item Name — Description text.
|
||||
|
||||
Random Events:
|
||||
1. Event description.
|
||||
2. Event description.
|
||||
3. Event description.
|
||||
4. Event description.
|
||||
5. Event description.
|
||||
6. Event description.
|
||||
1. Event Name: Event description.
|
||||
2. Event Name: Event description.
|
||||
3. Event Name: Event description.
|
||||
4. Event Name: Event description.
|
||||
5. Event Name: Event description.
|
||||
6. Event Name: Event description.
|
||||
|
||||
CRITICAL: Every name must be unique and creative. Never use generic placeholders like "Location Name", "NPC Name", "Encounter Name", or "Treasure Name". Use actual descriptive names that fit the dungeon's theme.
|
||||
|
||||
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.`,
|
||||
|
||||
CRITICAL: Location name matching - When writing encounters, the location name in the encounter details MUST exactly match one of the room names you've created (Entrance Room, Climax Room, or one of the 3 Locations). Double-check that every encounter location matches an actual room name.
|
||||
|
||||
CRITICAL: Avoid vague language - Do not use words like "some", "various", "several", "many", "few", "things", "stuff", "items", or "objects" without specific details. Be concrete and specific in all descriptions.
|
||||
|
||||
CRITICAL: All names required - Every room, encounter, NPC, and treasure MUST have a name. Do not leave names blank or use placeholders. If you cannot think of a name, create one based on the dungeon's theme.
|
||||
|
||||
CRITICAL: You MUST output exactly five separate sections with these exact labels on their own lines:
|
||||
"Locations:"
|
||||
"Encounters:"
|
||||
"NPCs:"
|
||||
"Treasures:"
|
||||
"Random Events:"
|
||||
|
||||
Each section must start with its label on its own line, followed by numbered items. Do NOT combine sections. Do NOT embed encounters in location descriptions. Each item must be on its own numbered line. 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);
|
||||
let [intermediateRoomsSection, encountersSection, npcsSection, treasureSection, randomEventsSection] = mainContentRaw.split(/Encounters:|NPCs:|Treasures?:|Random Events:/i);
|
||||
|
||||
// Ensure random events section is properly extracted (handle case where label might be missing)
|
||||
if (!randomEventsSection && mainContentRaw.toLowerCase().includes('random')) {
|
||||
const randomMatch = mainContentRaw.match(/Random Events?[:\s]*\n?([^]*?)(?=Locations?:|Encounters?:|NPCs?:|Treasures?:|$)/i);
|
||||
if (randomMatch) {
|
||||
randomEventsSection = randomMatch[1];
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure NPCs section is properly extracted
|
||||
if (!npcsSection && mainContentRaw.toLowerCase().includes('npc')) {
|
||||
const npcMatch = mainContentRaw.match(/NPCs?[:\s]*\n?([^]*?)(?=Treasures?:|Random Events?:|Locations?:|Encounters?:|$)/i);
|
||||
if (npcMatch) {
|
||||
npcsSection = npcMatch[1];
|
||||
}
|
||||
}
|
||||
|
||||
// If sections are missing, try to extract from combined output
|
||||
if (!encountersSection && intermediateRoomsSection.includes('Encounter')) {
|
||||
const encounterMatches = intermediateRoomsSection.match(/Encounter\s+\d+[^]*?(?=Encounter\s+\d+|NPCs?:|Treasures?:|Random Events?:|Location \d+|$)/gi);
|
||||
if (encounterMatches && encounterMatches.length > 0) {
|
||||
encountersSection = encounterMatches.map((m, i) => {
|
||||
// Convert "Encounter N Name Room Name Location Details" to "N. Name: Location: Details"
|
||||
const match = m.match(/Encounter\s+(\d+)\s+(.+?)\s+(?:Room Name|Location)\s+(.+?)\s+Details\s+(.+)/i);
|
||||
if (match) {
|
||||
const [, num, name, location, details] = match;
|
||||
return `${num}. ${name.trim()}: ${location.trim()}: ${details.trim().substring(0, 200)}`;
|
||||
}
|
||||
// Try format without "Room Name"
|
||||
const simpleMatch = m.match(/Encounter\s+(\d+)\s+(.+?)\s+([A-Z][^:]+?)\s+Details\s+(.+)/i);
|
||||
if (simpleMatch) {
|
||||
const [, num, name, location, details] = simpleMatch;
|
||||
return `${num}. ${name.trim()}: ${location.trim()}: ${details.trim().substring(0, 200)}`;
|
||||
}
|
||||
return `${i + 1}. ${m.trim()}`;
|
||||
}).join('\n');
|
||||
intermediateRoomsSection = intermediateRoomsSection.replace(/Encounter\s+\d+[^]*?(?=Encounter\s+\d+|NPCs?:|Treasures?:|Random Events?:|Location \d+|$)/gi, '');
|
||||
}
|
||||
}
|
||||
|
||||
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 || "");
|
||||
|
||||
// Deduplicate rooms by name (case-insensitive), keeping first occurrence
|
||||
const allRooms = [entranceRoom, ...limitedIntermediateRooms, climaxRoom].filter(Boolean);
|
||||
const seenNames = new Set();
|
||||
const rooms = allRooms.filter(room => {
|
||||
if (!room || !room.name) return false;
|
||||
const nameLower = room.name.toLowerCase().trim();
|
||||
if (seenNames.has(nameLower)) {
|
||||
console.warn(`Duplicate room name detected: "${room.name}", skipping duplicate`);
|
||||
return false;
|
||||
}
|
||||
seenNames.add(nameLower);
|
||||
return true;
|
||||
});
|
||||
let encounters = splitCombinedEncounters(parseObjects(encountersSection || "", "encounters"));
|
||||
let npcs = parseObjects(npcsSection || "", "npcs");
|
||||
const treasure = parseObjects(treasureSection || "", "treasure");
|
||||
|
||||
// Pad NPCs to at least 4 if needed (only if we have some NPCs already)
|
||||
if (npcs.length > 0 && npcs.length < 4) {
|
||||
const factionName = coreConcepts.match(/Primary Faction[:\s]+([^.]+)/i)?.[1]?.trim() || 'the primary faction';
|
||||
while (npcs.length < 4) {
|
||||
npcs.push({
|
||||
name: `NPC ${npcs.length + 1}`,
|
||||
trait: `A member of ${factionName.toLowerCase()} with unknown motives.`
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Pad encounters to exactly 6 (only pad if we have at least 1 real encounter)
|
||||
if (encounters.length > 0 && encounters.length < 6) {
|
||||
const dynamicElement = coreConcepts.match(/Dynamic Element[:\s]+([^.]+)/i)?.[1]?.trim() || 'strange occurrences';
|
||||
const conflict = coreConcepts.match(/Central Conflict[:\s]+([^.]+)/i)?.[1]?.trim() || 'a threat';
|
||||
while (encounters.length < 6) {
|
||||
const roomIndex = encounters.length % rooms.length;
|
||||
const roomName = rooms[roomIndex]?.name || 'Unknown Location';
|
||||
// Use more descriptive fallback names based on room and theme
|
||||
const fallbackNames = [
|
||||
`${roomName} Guardian`,
|
||||
`${roomName} Threat`,
|
||||
`${roomName} Challenge`,
|
||||
`${dynamicElement.split(' ')[0]} Manifestation`,
|
||||
`${conflict.split(' ')[0]} Encounter`,
|
||||
`${roomName} Hazard`
|
||||
];
|
||||
encounters.push({
|
||||
name: fallbackNames[encounters.length % fallbackNames.length],
|
||||
details: `An encounter related to ${dynamicElement.toLowerCase()} occurs here.`
|
||||
});
|
||||
}
|
||||
} else if (encounters.length === 0) {
|
||||
// If no encounters at all, create 6 basic ones
|
||||
const dynamicElement = coreConcepts.match(/Dynamic Element[:\s]+([^.]+)/i)?.[1]?.trim() || 'strange occurrences';
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const roomIndex = i % rooms.length;
|
||||
const roomName = rooms[roomIndex]?.name || 'Unknown Location';
|
||||
encounters.push({
|
||||
name: `${roomName} Encounter`,
|
||||
details: `An encounter related to ${dynamicElement.toLowerCase()} occurs here.`
|
||||
});
|
||||
}
|
||||
}
|
||||
let randomEvents = parseList(randomEventsSection || "");
|
||||
// Parse events into objects with name and description
|
||||
randomEvents = randomEvents
|
||||
.filter(e =>
|
||||
e &&
|
||||
e.toLowerCase() !== 'a random event occurs' &&
|
||||
e.toLowerCase() !== 'a random event occurs.' &&
|
||||
!e.toLowerCase().includes('placeholder') &&
|
||||
e.length > 10
|
||||
)
|
||||
.map((e, index) => {
|
||||
// Strip numbered prefixes like "Event 1:", "Random Event:", etc.
|
||||
let cleaned = e.replace(/^(Event\s+\d+[:\s]+|Random\s+Event[:\s]+|Random\s+Events?[:\s]+)/i, '').trim();
|
||||
|
||||
// Parse "Event Name: Description" format
|
||||
const colonMatch = cleaned.match(/^([^:]+):\s*(.+)$/);
|
||||
if (colonMatch) {
|
||||
const name = colonMatch[1].trim();
|
||||
const description = colonMatch[2].trim();
|
||||
// Skip if name looks like a placeholder
|
||||
if (name.toLowerCase().includes('event name') || name.toLowerCase().includes('placeholder')) {
|
||||
return null;
|
||||
}
|
||||
return { name, description };
|
||||
}
|
||||
|
||||
// Fallback: if no colon, use first few words as name
|
||||
const words = cleaned.split(/\s+/);
|
||||
if (words.length > 3) {
|
||||
return {
|
||||
name: words.slice(0, 2).join(' '),
|
||||
description: words.slice(2).join(' ')
|
||||
};
|
||||
}
|
||||
|
||||
// Last resort: use as description with generic name
|
||||
return { name: `Event ${index + 1}`, description: cleaned };
|
||||
})
|
||||
.filter(Boolean); // Remove null entries
|
||||
randomEvents = randomEvents.slice(0, 6);
|
||||
|
||||
// Generate context-aware fallbacks if needed (only if we have some events already)
|
||||
if (randomEvents.length > 0 && randomEvents.length < 6) {
|
||||
const dynamicElement = coreConcepts.match(/Dynamic Element[:\s]+([^.]+)/i)?.[1]?.trim() || 'strange occurrences';
|
||||
const conflict = coreConcepts.match(/Central Conflict[:\s]+([^.]+)/i)?.[1]?.trim() || 'a mysterious threat';
|
||||
const fallbackEvents = [
|
||||
{ name: 'Environmental Shift', description: `The ${dynamicElement.toLowerCase()} causes unexpected changes in the environment.` },
|
||||
{ name: 'Conflict Manifestation', description: `A sign of ${conflict.toLowerCase()} appears, requiring immediate attention.` },
|
||||
{ name: 'Dungeon Shift', description: `The dungeon shifts, revealing a previously hidden passage or danger.` },
|
||||
{ name: 'Faction Messenger', description: `An NPC from the primary faction appears with urgent information.` },
|
||||
{ name: 'Power Fluctuation', description: `The power source fluctuates, creating temporary hazards or opportunities.` },
|
||||
{ name: 'Echoes of the Past', description: `Echoes of past events manifest, providing clues or complications.` }
|
||||
];
|
||||
while (randomEvents.length < 6) {
|
||||
randomEvents.push(fallbackEvents[randomEvents.length % fallbackEvents.length]);
|
||||
}
|
||||
}
|
||||
|
||||
[[encounters, 6, 'encounters'], [npcs, 4, 'NPCs'], [treasure, 4, 'treasures'], [randomEvents, 6, 'random events']]
|
||||
.filter(([arr, expected]) => arr.length < expected && arr.length > 0)
|
||||
|
||||
@@ -63,8 +63,8 @@ export function dungeonTemplate(data) {
|
||||
padding: 0;
|
||||
font-family: ${bodyFont};
|
||||
color: #1a1a1a;
|
||||
font-size: 0.75em;
|
||||
line-height: 1.4em;
|
||||
font-size: 0.7em;
|
||||
line-height: 1.35em;
|
||||
}
|
||||
.content-page {
|
||||
height: 100vh;
|
||||
@@ -91,7 +91,7 @@ export function dungeonTemplate(data) {
|
||||
font-family: ${quoteFont};
|
||||
margin: 0.3em 0 0.6em;
|
||||
font-size: 0.85em;
|
||||
line-height: 1.4em;
|
||||
line-height: 1.35em;
|
||||
}
|
||||
.columns {
|
||||
display: grid;
|
||||
@@ -102,7 +102,7 @@ export function dungeonTemplate(data) {
|
||||
.col {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.3em;
|
||||
gap: 0.25em;
|
||||
overflow-wrap: break-word;
|
||||
word-break: normal;
|
||||
hyphens: auto;
|
||||
@@ -110,7 +110,7 @@ export function dungeonTemplate(data) {
|
||||
.section-block {
|
||||
break-inside: avoid;
|
||||
page-break-inside: avoid;
|
||||
margin-bottom: 0.4em;
|
||||
margin-bottom: 0.3em;
|
||||
}
|
||||
h2 {
|
||||
font-family: ${headingFont};
|
||||
@@ -129,29 +129,29 @@ export function dungeonTemplate(data) {
|
||||
page-break-inside: avoid;
|
||||
}
|
||||
.room h3 {
|
||||
margin: 0.15em 0 0.08em;
|
||||
font-size: 0.95em;
|
||||
margin: 0.08em 0 0.03em;
|
||||
font-size: 0.9em;
|
||||
font-weight: bold;
|
||||
color: #1a1a1a;
|
||||
}
|
||||
.room p {
|
||||
margin: 0 0 0.35em;
|
||||
font-size: 0.9em;
|
||||
margin: 0 0 0.15em;
|
||||
font-size: 0.8em;
|
||||
font-weight: normal;
|
||||
line-height: 1.35em;
|
||||
line-height: 1.25em;
|
||||
}
|
||||
.encounter, .npc, .treasure, .plot-resolution {
|
||||
margin: 0 0 0.35em;
|
||||
margin: 0 0 0.25em;
|
||||
break-inside: avoid;
|
||||
page-break-inside: avoid;
|
||||
font-size: 0.9em;
|
||||
line-height: 1.35em;
|
||||
font-size: 0.85em;
|
||||
line-height: 1.3em;
|
||||
}
|
||||
.random-events {
|
||||
margin: 0.2em 0;
|
||||
break-inside: avoid;
|
||||
page-break-inside: avoid;
|
||||
font-size: 0.9em;
|
||||
font-size: 0.85em;
|
||||
}
|
||||
.random-events table {
|
||||
margin-top: 0.15em;
|
||||
@@ -228,8 +228,8 @@ export function dungeonTemplate(data) {
|
||||
}
|
||||
li {
|
||||
margin: 0.08em 0;
|
||||
font-size: 0.9em;
|
||||
line-height: 1.35em;
|
||||
font-size: 0.85em;
|
||||
line-height: 1.3em;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
@@ -252,14 +252,54 @@ export function dungeonTemplate(data) {
|
||||
${data.randomEvents && data.randomEvents.length > 0 ? `
|
||||
<div class="section-block random-events">
|
||||
<h2>Random Events (d6)</h2>
|
||||
<table>
|
||||
<table class="encounters-table">
|
||||
<tbody>
|
||||
${data.randomEvents.map((event, index) => `
|
||||
${data.randomEvents.map((event, index) => {
|
||||
// Handle both object format {name, description} and string format
|
||||
let eventName = '';
|
||||
let eventDesc = '';
|
||||
if (typeof event === 'object' && event.name && event.description) {
|
||||
eventName = event.name;
|
||||
eventDesc = event.description;
|
||||
} else if (typeof event === 'string') {
|
||||
// Try to parse "Event Name: Description" format
|
||||
const colonMatch = event.match(/^([^:]+):\s*(.+)$/);
|
||||
if (colonMatch) {
|
||||
eventName = colonMatch[1].trim();
|
||||
eventDesc = colonMatch[2].trim();
|
||||
} else {
|
||||
// Fallback: use first few words as name, rest as description
|
||||
const words = event.split(/\s+/);
|
||||
if (words.length > 3) {
|
||||
eventName = words.slice(0, 2).join(' ');
|
||||
eventDesc = words.slice(2).join(' ');
|
||||
} else {
|
||||
eventName = `Event ${index + 1}`;
|
||||
eventDesc = event;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
eventName = `Event ${index + 1}`;
|
||||
eventDesc = String(event || '');
|
||||
}
|
||||
// Truncate description to prevent overflow (similar to encounters)
|
||||
if (eventDesc.length > 200) {
|
||||
eventDesc = eventDesc.substring(0, 197).trim();
|
||||
const lastPeriod = eventDesc.lastIndexOf('.');
|
||||
if (lastPeriod > 150) {
|
||||
eventDesc = eventDesc.substring(0, lastPeriod + 1);
|
||||
} else {
|
||||
eventDesc += '...';
|
||||
}
|
||||
}
|
||||
return `
|
||||
<tr>
|
||||
<td>${index + 1}</td>
|
||||
<td>${escapeHtml(event)}</td>
|
||||
<td><strong>${escapeHtml(eventName)}</strong></td>
|
||||
<td>${escapeHtml(eventDesc)}</td>
|
||||
</tr>
|
||||
`).join('')}
|
||||
`;
|
||||
}).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@@ -268,12 +308,30 @@ export function dungeonTemplate(data) {
|
||||
${data.rooms && data.rooms.length > 0 ? `
|
||||
<div class="section-block">
|
||||
<h2>Locations</h2>
|
||||
${data.rooms.map(room => `
|
||||
${data.rooms.map(room => {
|
||||
let desc = room.description || '';
|
||||
// Truncate to 1 sentence max to prevent overflow
|
||||
const sentences = desc.match(/[^.!?]+[.!?]+/g) || [desc];
|
||||
if (sentences.length > 1) {
|
||||
desc = sentences.slice(0, 1).join(' ').trim();
|
||||
}
|
||||
// Also limit by character count (~100 chars for tighter fit)
|
||||
if (desc.length > 100) {
|
||||
desc = desc.substring(0, 97).trim();
|
||||
const lastPeriod = desc.lastIndexOf('.');
|
||||
if (lastPeriod > 70) {
|
||||
desc = desc.substring(0, lastPeriod + 1);
|
||||
} else {
|
||||
desc += '...';
|
||||
}
|
||||
}
|
||||
return `
|
||||
<div class="room">
|
||||
<h3>${escapeHtml(room.name)}</h3>
|
||||
<p>${escapeHtml(room.description)}</p>
|
||||
<p>${escapeHtml(desc)}</p>
|
||||
</div>
|
||||
`).join('')}
|
||||
`;
|
||||
}).join('')}
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
@@ -287,7 +345,20 @@ export function dungeonTemplate(data) {
|
||||
${data.encounters.map((encounter, index) => {
|
||||
// Truncate details to 4 sentences max to prevent overflow
|
||||
let details = encounter.details || '';
|
||||
// Keep location prefix in details (format: "Location Name: details")
|
||||
// Remove encounter name if it appears at start
|
||||
if (details.toLowerCase().startsWith(encounter.name.toLowerCase())) {
|
||||
details = details.substring(encounter.name.length).replace(/^:\s*/, '').trim();
|
||||
}
|
||||
// Remove location prefix if present (format: "Location Name: description")
|
||||
// Handle multiple colons - strip the first one that looks like a location
|
||||
const locationMatch = details.match(/^([^:]+):\s*(.+)$/);
|
||||
if (locationMatch) {
|
||||
const potentialLocation = locationMatch[1].trim();
|
||||
// If it looks like a location name (capitalized, not too long), remove it
|
||||
if (potentialLocation.length > 3 && potentialLocation.length < 50 && /^[A-Z]/.test(potentialLocation)) {
|
||||
details = locationMatch[2].trim();
|
||||
}
|
||||
}
|
||||
// Split into sentences and keep only first 4
|
||||
const sentences = details.match(/[^.!?]+[.!?]+/g) || [details];
|
||||
if (sentences.length > 4) {
|
||||
@@ -316,28 +387,44 @@ export function dungeonTemplate(data) {
|
||||
</table>
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
|
||||
<div class="col">
|
||||
|
||||
${data.treasure && data.treasure.length > 0 ? `
|
||||
<div class="section-block">
|
||||
<h2>Treasure</h2>
|
||||
${data.treasure.map(item => `
|
||||
<div class="treasure">
|
||||
${typeof item === 'object' && item.name ? `<strong>${escapeHtml(item.name)}</strong> — ${escapeHtml(item.description)}` : escapeHtml(item)}
|
||||
</div>
|
||||
`).join('')}
|
||||
${data.treasure.map(item => {
|
||||
if (typeof item === 'object' && item.name && item.description) {
|
||||
return `<div class="treasure"><strong>${escapeHtml(item.name)}</strong> — ${escapeHtml(item.description)}</div>`;
|
||||
} else if (typeof item === 'string') {
|
||||
// Handle string format "Name — Description"
|
||||
const parts = item.split(/[—–-]/);
|
||||
if (parts.length >= 2) {
|
||||
return `<div class="treasure"><strong>${escapeHtml(parts[0].trim())}</strong> — ${escapeHtml(parts.slice(1).join(' ').trim())}</div>`;
|
||||
}
|
||||
return `<div class="treasure">${escapeHtml(item)}</div>`;
|
||||
}
|
||||
return '';
|
||||
}).filter(Boolean).join('')}
|
||||
</div>
|
||||
` : ''}
|
||||
|
||||
</div>
|
||||
|
||||
<div class="col">
|
||||
${data.npcs && data.npcs.length > 0 ? `
|
||||
<div class="section-block">
|
||||
<h2>NPCs</h2>
|
||||
${data.npcs.map(npc => `
|
||||
<div class="npc">
|
||||
<strong>${escapeHtml(npc.name)}</strong>: ${escapeHtml(npc.trait)}
|
||||
</div>
|
||||
`).join('')}
|
||||
${data.npcs.map(npc => {
|
||||
if (typeof npc === 'object' && npc.name && npc.trait) {
|
||||
return `<div class="npc"><strong>${escapeHtml(npc.name)}</strong>: ${escapeHtml(npc.trait)}</div>`;
|
||||
} else if (typeof npc === 'string') {
|
||||
// Handle string format "Name: Description"
|
||||
const parts = npc.split(/:/);
|
||||
if (parts.length >= 2) {
|
||||
return `<div class="npc"><strong>${escapeHtml(parts[0].trim())}</strong>: ${escapeHtml(parts.slice(1).join(':').trim())}</div>`;
|
||||
}
|
||||
return `<div class="npc">${escapeHtml(npc)}</div>`;
|
||||
}
|
||||
return '';
|
||||
}).filter(Boolean).join('')}
|
||||
</div>
|
||||
` : ''}
|
||||
|
||||
@@ -345,19 +432,19 @@ export function dungeonTemplate(data) {
|
||||
<div class="section-block">
|
||||
<h2>Plot Resolutions</h2>
|
||||
${data.plotResolutions.map(resolution => {
|
||||
// Truncate to 3 sentences max to prevent overflow
|
||||
// Truncate to 1 sentence max to prevent overflow (more aggressive)
|
||||
let text = resolution || '';
|
||||
// Split into sentences and keep only first 3
|
||||
// Split into sentences and keep only first 1
|
||||
const sentences = text.match(/[^.!?]+[.!?]+/g) || [text];
|
||||
if (sentences.length > 3) {
|
||||
text = sentences.slice(0, 3).join(' ').trim();
|
||||
if (sentences.length > 1) {
|
||||
text = sentences.slice(0, 1).join(' ').trim();
|
||||
}
|
||||
// Also limit by character count as fallback (max ~200 chars)
|
||||
if (text.length > 200) {
|
||||
text = text.substring(0, 197).trim();
|
||||
// Also limit by character count as fallback (max ~120 chars for tighter fit)
|
||||
if (text.length > 120) {
|
||||
text = text.substring(0, 117).trim();
|
||||
// Try to end at a sentence boundary
|
||||
const lastPeriod = text.lastIndexOf('.');
|
||||
if (lastPeriod > 150) {
|
||||
if (lastPeriod > 90) {
|
||||
text = text.substring(0, lastPeriod + 1);
|
||||
} else {
|
||||
text += '...';
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"test:integration": "node --test test/integration.test.js",
|
||||
"lint": "eslint .",
|
||||
"start": "node index.js"
|
||||
},
|
||||
|
||||
91
test/integration.test.js
Normal file
91
test/integration.test.js
Normal file
@@ -0,0 +1,91 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert";
|
||||
import { generateDungeon } from "../dungeonGenerator.js";
|
||||
import { generatePDF } from "../generatePDF.js";
|
||||
import fs from "fs/promises";
|
||||
import path from "path";
|
||||
|
||||
const OLLAMA_API_URL = process.env.OLLAMA_API_URL;
|
||||
|
||||
test("Integration tests", { skip: !OLLAMA_API_URL }, async (t) => {
|
||||
let dungeonData;
|
||||
|
||||
await t.test("Generate dungeon", async () => {
|
||||
dungeonData = await generateDungeon();
|
||||
assert(dungeonData, "Dungeon data should be generated");
|
||||
});
|
||||
|
||||
await t.test("Title is 2-4 words, no colons", () => {
|
||||
assert(dungeonData.title, "Title should exist");
|
||||
const words = dungeonData.title.split(/\s+/);
|
||||
assert(words.length >= 2 && words.length <= 4, `Title should be 2-4 words, got ${words.length}: "${dungeonData.title}"`);
|
||||
assert(!dungeonData.title.includes(":"), `Title should not contain colons: "${dungeonData.title}"`);
|
||||
});
|
||||
|
||||
await t.test("Flavor text is ≤60 words", () => {
|
||||
assert(dungeonData.flavor, "Flavor text should exist");
|
||||
const words = dungeonData.flavor.split(/\s+/);
|
||||
assert(words.length <= 60, `Flavor text should be ≤60 words, got ${words.length}`);
|
||||
});
|
||||
|
||||
await t.test("Hooks have no title prefixes", () => {
|
||||
assert(dungeonData.hooksRumors, "Hooks should exist");
|
||||
dungeonData.hooksRumors.forEach((hook, i) => {
|
||||
assert(!hook.match(/^[^:]+:\s/), `Hook ${i + 1} should not have title prefix: "${hook}"`);
|
||||
});
|
||||
});
|
||||
|
||||
await t.test("Exactly 6 random events", () => {
|
||||
assert(dungeonData.randomEvents, "Random events should exist");
|
||||
assert.strictEqual(dungeonData.randomEvents.length, 6, `Should have exactly 6 random events, got ${dungeonData.randomEvents.length}`);
|
||||
});
|
||||
|
||||
await t.test("Encounter details don't include encounter name", () => {
|
||||
assert(dungeonData.encounters, "Encounters should exist");
|
||||
dungeonData.encounters.forEach((encounter) => {
|
||||
if (encounter.details) {
|
||||
const detailsLower = encounter.details.toLowerCase();
|
||||
const nameLower = encounter.name.toLowerCase();
|
||||
assert(!detailsLower.startsWith(nameLower), `Encounter "${encounter.name}" details should not start with encounter name: "${encounter.details}"`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
await t.test("Treasure uses em-dash format, no 'description' text", () => {
|
||||
assert(dungeonData.treasure, "Treasure should exist");
|
||||
dungeonData.treasure.forEach((item, i) => {
|
||||
if (typeof item === "object" && item.description) {
|
||||
assert(!item.description.toLowerCase().startsWith("description"), `Treasure ${i + 1} description should not start with 'description': "${item.description}"`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
await t.test("NPCs have no 'description' text", () => {
|
||||
assert(dungeonData.npcs, "NPCs should exist");
|
||||
dungeonData.npcs.forEach((npc, i) => {
|
||||
if (npc.trait) {
|
||||
assert(!npc.trait.toLowerCase().startsWith("description"), `NPC ${i + 1} trait should not start with 'description': "${npc.trait}"`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
await t.test("PDF fits on one page", async () => {
|
||||
const testPdfPath = path.join(process.cwd(), "test-output.pdf");
|
||||
try {
|
||||
await generatePDF(dungeonData, testPdfPath);
|
||||
const pdfBuffer = await fs.readFile(testPdfPath);
|
||||
// Check PDF page count by counting "%%EOF" markers (rough estimate)
|
||||
const pdfText = pdfBuffer.toString("binary");
|
||||
const pageCount = (pdfText.match(/\/Type\s*\/Page[^s]/g) || []).length;
|
||||
// Should be 1 page for content, or 2 if map exists
|
||||
const expectedPages = dungeonData.map ? 2 : 1;
|
||||
assert(pageCount <= expectedPages, `PDF should have ≤${expectedPages} page(s), got ${pageCount}`);
|
||||
} finally {
|
||||
try {
|
||||
await fs.unlink(testPdfPath);
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user