awacke1 commited on
Commit
5ead6ab
·
verified ·
1 Parent(s): edaf0c0

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +233 -112
index.html CHANGED
@@ -3,7 +3,7 @@
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>Choose Your Own Procedural Adventure (Stable Base)</title>
7
  <style>
8
  body{font-family:'Courier New',monospace;background-color:#222;color:#eee;margin:0;padding:0;overflow:hidden;display:flex;flex-direction:column;height:100vh}
9
  #game-container{display:flex;flex-grow:1;overflow:hidden}
@@ -32,7 +32,14 @@
32
  .choice-button:disabled{background-color:#444;color:#888;cursor:not-allowed;border-color:#666;opacity:0.7}
33
  .roll-success{color:#7f7;border-left:3px solid #4a4;padding-left:8px;margin-bottom:1em;font-size:0.9em}
34
  .roll-failure{color:#f77;border-left:3px solid #a44;padding-left:8px;margin-bottom:1em;font-size:0.9em}
35
- .xp-gain{color:#7af;font-style:italic;font-size:0.9em;display:block;margin-top:0.5em;} /* Style for XP messages */
 
 
 
 
 
 
 
36
  </style>
37
  </head>
38
  <body>
@@ -47,7 +54,7 @@
47
  <div id="stats-inventory-container">
48
  <div id="stats-display"></div>
49
  <div id="inventory-display"></div>
50
- </div>
51
  <div id="choices-container">
52
  <h3>What will you do?</h3>
53
  <div id="choices"></div>
@@ -73,6 +80,7 @@
73
  const choicesElement = document.getElementById('choices');
74
  const statsElement = document.getElementById('stats-display');
75
  const inventoryElement = document.getElementById('inventory-display');
 
76
 
77
  let scene, camera, renderer;
78
  let currentAssemblyGroup = null;
@@ -81,19 +89,18 @@
81
  const woodMaterial = new THREE.MeshStandardMaterial({ color: 0x8B4513, roughness: 0.7, metalness: 0 });
82
  const darkWoodMaterial = new THREE.MeshStandardMaterial({ color: 0x5C3D20, roughness: 0.7, metalness: 0 });
83
  const leafMaterial = new THREE.MeshStandardMaterial({ color: 0x2E8B57, roughness: 0.6, metalness: 0 });
 
 
84
  const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x556B2F, roughness: 0.9, metalness: 0 });
85
  const metalMaterial = new THREE.MeshStandardMaterial({ color: 0xaaaaaa, metalness: 0.8, roughness: 0.3 });
86
  const templeMaterial = new THREE.MeshStandardMaterial({ color: 0xA99B78, roughness: 0.7, metalness: 0.1 });
87
  const errorMaterial = new THREE.MeshStandardMaterial({ color: 0xffa500, roughness: 0.5 });
88
  const gameOverMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000, roughness: 0.5 });
89
- // Added materials for forest variation from previous step, keep them
90
- const pineLeafMaterial = new THREE.MeshStandardMaterial({ color: 0x1A5A2A, roughness: 0.7, metalness: 0 });
91
- const gnarledWoodMaterial = new THREE.MeshStandardMaterial({ color: 0x6B4F3A, roughness: 0.85, metalness: 0 });
92
 
93
  function initThreeJS() {
 
94
  if (!sceneContainer) { console.error("Scene container not found!"); return; }
95
- scene = new THREE.Scene();
96
- scene.background = new THREE.Color(0x222222);
97
  const width = sceneContainer.clientWidth; const height = sceneContainer.clientHeight;
98
  camera = new THREE.PerspectiveCamera(75, (width / height) || 1, 0.1, 1000);
99
  camera.position.set(0, 2.5, 7); camera.lookAt(0, 0.5, 0);
@@ -116,17 +123,20 @@
116
  }
117
 
118
  function onWindowResize() {
119
- if (!renderer || !camera || !sceneContainer) return;
 
120
  const width = sceneContainer.clientWidth; const height = sceneContainer.clientHeight;
121
  if (width > 0 && height > 0) { camera.aspect = width / height; camera.updateProjectionMatrix(); renderer.setSize(width, height); }
122
  }
123
 
124
  function animate() {
 
125
  requestAnimationFrame(animate);
126
  if (renderer && scene && camera) { renderer.render(scene, camera); }
127
  }
128
 
129
  function createMesh(geometry, material, position = { x: 0, y: 0, z: 0 }, rotation = { x: 0, y: 0, z: 0 }, scale = { x: 1, y: 1, z: 1 }) {
 
130
  const mesh = new THREE.Mesh(geometry, material);
131
  mesh.position.set(position.x, position.y, position.z); mesh.rotation.set(rotation.x, rotation.y, rotation.z); mesh.scale.set(scale.x, scale.y, scale.z);
132
  mesh.castShadow = true; mesh.receiveShadow = true;
@@ -134,77 +144,89 @@
134
  }
135
 
136
  function createGroundPlane(material = groundMaterial, size = 20) {
137
- const groundGeo = new THREE.PlaneGeometry(size, size);
 
138
  const ground = new THREE.Mesh(groundGeo, material);
139
  ground.rotation.x = -Math.PI / 2; ground.position.y = -0.05;
140
  ground.receiveShadow = true; ground.castShadow = false;
141
  return ground;
142
  }
143
 
144
- // --- Procedural Generation Functions (Using simpler, non-parameterized versions first) ---
145
- function createDefaultAssembly() { const group = new THREE.Group(); const sphereGeo = new THREE.SphereGeometry(0.5, 16, 16); group.add(createMesh(sphereGeo, stoneMaterial, { x: 0, y: 0.5, z: 0 })); group.add(createGroundPlane()); return group; }
146
- function createCityGatesAssembly() { const group = new THREE.Group(); const gh=4, gw=1.5, gd=0.8, ah=1, aw=3; const tlGeo = new THREE.BoxGeometry(gw, gh, gd); group.add(createMesh(tlGeo, stoneMaterial, { x:-(aw/2+gw/2), y:gh/2, z:0 })); const trGeo = new THREE.BoxGeometry(gw, gh, gd); group.add(createMesh(trGeo, stoneMaterial, { x:(aw/2+gw/2), y:gh/2, z:0 })); const aGeo = new THREE.BoxGeometry(aw, ah, gd); group.add(createMesh(aGeo, stoneMaterial, { x:0, y:gh-ah/2, z:0 })); const cs=0.4; const cg = new THREE.BoxGeometry(cs, cs, gd*1.1); for(let i=-1; i<=1; i+=2){ group.add(createMesh(cg.clone(), stoneMaterial, { x:-(aw/2+gw/2)+i*cs*0.7, y:gh+cs/2, z:0 })); group.add(createMesh(cg.clone(), stoneMaterial, { x:(aw/2+gw/2)+i*cs*0.7, y:gh+cs/2, z:0 })); } group.add(createMesh(cg.clone(), stoneMaterial, { x:0, y:gh+ah-cs/2, z:0 })); group.add(createGroundPlane(stoneMaterial)); return group; }
147
- function createWeaponsmithAssembly() { const group = new THREE.Group(); const bw=3, bh=2.5, bd=3.5; const bGeo = new THREE.BoxGeometry(bw, bh, bd); group.add(createMesh(bGeo, darkWoodMaterial, { x:0, y:bh/2, z:0 })); const ch=3.5; const cGeo = new THREE.CylinderGeometry(0.3, 0.4, ch, 8); group.add(createMesh(cGeo, stoneMaterial, { x:bw*0.3, y:ch/2, z:-bd*0.3 })); group.add(createGroundPlane()); return group; }
148
- function createTempleAssembly() { const group = new THREE.Group(); const bs=5, bsh=0.5, ch=3, cr=0.25, rh=0.5; const bGeo = new THREE.BoxGeometry(bs, bsh, bs); group.add(createMesh(bGeo, templeMaterial, { x:0, y:bsh/2, z:0 })); const cGeo = new THREE.CylinderGeometry(cr, cr, ch, 12); const cPos = [{x:-bs/3, z:-bs/3}, {x:bs/3, z:-bs/3}, {x:-bs/3, z:bs/3}, {x:bs/3, z:bs/3}]; cPos.forEach(p=>group.add(createMesh(cGeo.clone(), templeMaterial, { x:p.x, y:bsh+ch/2, z:p.z }))); const rGeo = new THREE.BoxGeometry(bs*0.9, rh, bs*0.9); group.add(createMesh(rGeo, templeMaterial, { x:0, y:bsh+ch+rh/2, z:0 })); group.add(createGroundPlane()); return group; }
149
- function createResistanceMeetingAssembly() { const group = new THREE.Group(); const tw=2, th=0.8, td=1, tt=0.1; const ttg = new THREE.BoxGeometry(tw, tt, td); group.add(createMesh(ttg, woodMaterial, { x:0, y:th-tt/2, z:0 })); const lh=th-tt, ls=0.1; const lg=new THREE.BoxGeometry(ls, lh, ls); const lofW=tw/2-ls*1.5; const lofD=td/2-ls*1.5; group.add(createMesh(lg, woodMaterial, { x:-lofW, y:lh/2, z:-lofD })); group.add(createMesh(lg.clone(), woodMaterial, { x:lofW, y:lh/2, z:-lofD })); group.add(createMesh(lg.clone(), woodMaterial, { x:-lofW, y:lh/2, z:lofD })); group.add(createMesh(lg.clone(), woodMaterial, { x:lofW, y:lh/2, z:lofD })); const ss=0.4; const sg=new THREE.BoxGeometry(ss, ss*0.8, ss); group.add(createMesh(sg, darkWoodMaterial, { x:-tw*0.6, y:ss*0.4, z:0 })); group.add(createMesh(sg.clone(), darkWoodMaterial, { x:tw*0.6, y:ss*0.4, z:0 })); group.add(createGroundPlane(stoneMaterial)); return group; }
150
- function createForestAssembly(params = {}) { // Kept params for potential future use, but using defaults now
151
- const group = new THREE.Group(); const tc=10, a=10; // Use fixed values
152
- const cT=(x,z)=>{ const tg=new THREE.Group(); const th=Math.random()*1.5+2; const tr=Math.random()*0.1+0.1; const tGeo=new THREE.CylinderGeometry(tr*0.7, tr, th, 8); tg.add(createMesh(tGeo, woodMaterial, {x:0, y:th/2, z:0})); const fr=th*0.4+0.2; const fGeo=new THREE.SphereGeometry(fr, 8, 6); tg.add(createMesh(fGeo, leafMaterial, {x:0, y:th*0.9, z:0})); tg.position.set(x,0,z); return tg; };
153
- for(let i=0; i<tc; i++){ const x=(Math.random()-0.5)*a; const z=(Math.random()-0.5)*a; if(Math.sqrt(x*x+z*z)>1.0) group.add(cT(x,z)); } group.add(createGroundPlane(groundMaterial, a*1.1)); return group;
154
- }
155
- function createRoadAmbushAssembly() { const group = new THREE.Group(); const a=12; const fg = createForestAssembly(); group.add(fg); const rw=3, rl=a*1.2; const rGeo=new THREE.PlaneGeometry(rw, rl); const rMat=new THREE.MeshStandardMaterial({color:0x966F33, roughness:0.9}); const r=createMesh(rGeo, rMat, {x:0, y:0.01, z:0}, {x:-Math.PI/2}); r.receiveShadow=true; group.add(r); const rkGeo=new THREE.SphereGeometry(0.5, 5, 4); const rkMat=new THREE.MeshStandardMaterial({color:0x666666, roughness:0.8}); group.add(createMesh(rkGeo, rkMat, {x:rw*0.7, y:0.25, z:1}, {y:Math.random()*Math.PI})); group.add(createMesh(rkGeo.clone().scale(0.8,0.8,0.8), rkMat, {x:-rw*0.8, y:0.2, z:-2}, {y:Math.random()*Math.PI})); return group; }
156
- function createForestEdgeAssembly() { const group = new THREE.Group(); const a=15; const fg = createForestAssembly(); const ttr=[]; fg.children.forEach(c => { if(c.type === 'Group' && c.position.x > 0) ttr.push(c); }); ttr.forEach(t => fg.remove(t)); group.add(fg); return group; }
157
- function createPrisonerCellAssembly() { const group = new THREE.Group(); const cs=3, wh=2.5, wt=0.2, br=0.05, bsp=0.25; const cfMat=stoneMaterial.clone(); cfMat.color.setHex(0x555555); group.add(createGroundPlane(cfMat, cs)); const wbGeo=new THREE.BoxGeometry(cs, wh, wt); group.add(createMesh(wbGeo, stoneMaterial, {x:0, y:wh/2, z:-cs/2})); const wsGeo=new THREE.BoxGeometry(wt, wh, cs); group.add(createMesh(wsGeo, stoneMaterial, {x:-cs/2, y:wh/2, z:0})); group.add(createMesh(wsGeo.clone(), stoneMaterial, {x:cs/2, y:wh/2, z:0})); const bGeo=new THREE.CylinderGeometry(br, br, wh, 8); const nb=Math.floor(cs/bsp); for(let i=0; i<nb; i++){ const xp=-cs/2+(i+0.5)*bsp; group.add(createMesh(bGeo.clone(), metalMaterial, {x:xp, y:wh/2, z:cs/2})); } return group; }
158
- function createGameOverAssembly() { const group = new THREE.Group(); const boxGeo = new THREE.BoxGeometry(2, 2, 2); group.add(createMesh(boxGeo, gameOverMaterial, { x: 0, y: 1, z: 0 })); group.add(createGroundPlane(stoneMaterial.clone().set({color: 0x333333}))); return group; }
159
- function createErrorAssembly() { const group = new THREE.Group(); const coneGeo = new THREE.ConeGeometry( 0.8, 1.5, 8 ); group.add(createMesh(coneGeo, errorMaterial, { x: 0, y: 0.75, z: 0 })); group.add(createGroundPlane()); return group; }
 
 
 
 
 
 
160
 
161
  // --- Game Data ---
162
- const itemsData = { "Flaming Sword":{type:"weapon", description:"A fiery blade"}, "Whispering Bow":{type:"weapon", description:"A silent bow"}, "Guardian Shield":{type:"armor", description:"A protective shield"}, "Healing Light Spell":{type:"spell", description:"Mends minor wounds"}, "Shield of Faith Spell":{type:"spell", description:"Temporary shield"}, "Binding Runes Scroll":{type:"spell", description:"Binds an enemy"}, "Secret Tunnel Map":{type:"quest", description:"Shows a hidden path"}, "Poison Daggers":{type:"weapon", description:"Daggers with poison"}, "Master Key":{type:"quest", description:"Unlocks many doors"}, "Crude Dagger":{type:"weapon", description:"A roughly made dagger."}, "Scout's Pouch":{type:"quest", description:"Contains odds and ends."}, "Healing Poultice":{type:"spell", description:"Soothes wounds, heals 5 HP."} };
163
- const gameData = { // Using the expanded game data with ~20 pages and checks
164
- "1": { title: "The Crossroads", content: `<p>Dust swirls... Which path calls to you?</p>`, options: [ { text: "Enter the Shadowwood Forest (North)", next: 5 }, { text: "Head towards the Rolling Hills (East)", next: 2 }, { text: "Investigate the Coastal Cliffs (West)", next: 3 } ], illustration: "crossroads-signpost-sunny" },
165
- "2": { title: "Rolling Hills", content: `<p>Verdant hills stretch before you...</p>`, options: [ { text: "Follow the narrow path", next: 4 }, { text: "Head back to the crossroads", next: 1 } ], illustration: "rolling-green-hills-shepherd-distance" },
166
  "3": { title: "Coastal Cliffs Edge", content: `<p>You stand atop windswept cliffs...</p>`, options: [ { text: "Attempt the precarious descent (Dexterity Check)", check: { stat: 'dexterity', dc: 12, onFailure: 31 }, next: 30 }, { text: "Scan the cliff face for easier routes (Wisdom Check)", check: { stat: 'wisdom', dc: 11, onFailure: 32 }, next: 33 }, { text: "Return to the crossroads", next: 1 } ], illustration: "windy-sea-cliffs-crashing-waves-path-down" },
167
  "4": { title: "Hill Path Overlook", content: `<p>The path crests a hill... you see a small, overgrown shrine...</p>`, options: [ { text: "Investigate the overgrown shrine", next: 40 }, { text: "Continue towards the badlands", next: 41 }, { text: "Go back", next: 2 } ], illustration: "hilltop-view-overgrown-shrine-wildflowers" },
168
- "5": { title: "Shadowwood Entrance", content: `<p>Sunlight struggles to pierce the dense canopy... How do you proceed?</p>`, options: [ { text: "Follow the main, albeit overgrown, path", next: 6 }, { text: "Try to navigate through the lighter undergrowth", next: 7 }, { text: "Look for animal trails or signs of passage (Wisdom Check)", check: { stat: 'wisdom', dc: 10, onFailure: 6 }, next: 8 } ], illustration: "dark-forest-entrance-gnarled-roots-filtered-light" },
169
- "6": { title: "Overgrown Forest Path", content: `<p>The path is barely visible... You hear a twig snap nearby!</p>`, options: [ { text: "Ready your weapon and investigate", next: 10 }, { text: "Attempt to hide quietly (Dexterity Check)", check: { stat: 'dexterity', dc: 11, onFailure: 10 }, next: 11 }, { text: "Call out cautiously", next: 10 } ], illustration: "overgrown-forest-path-glowing-fungi-vines" },
170
  "7": { title: "Tangled Undergrowth", content: `<p>Pushing through ferns... You stumble upon a small clearing containing a moss-covered, weathered stone statue...</p>`, options: [ { text: "Examine the statue closely (Intelligence Check)", check: { stat: 'intelligence', dc: 13, onFailure: 71 }, next: 70 }, { text: "Ignore the statue and press on", next: 72 }, { text: "Leave a small offering (if possible)", next: 73 } ], illustration: "forest-clearing-mossy-statue-weathered-stone" },
171
- "8": { title: "Hidden Game Trail", content: `<p>Your sharp eyes spot a faint trail... It leads towards a ravine spanned by a rickety rope bridge.</p><p class="xp-gain">(+20 XP)</p>`, options: [ { text: "Risk crossing the rope bridge (Dexterity Check)", check: { stat: 'dexterity', dc: 10, onFailure: 81 }, next: 80 }, { text: "Search for another way across the ravine", next: 82 } ], illustration: "narrow-game-trail-forest-rope-bridge-ravine", reward: { xp: 20 } },
172
  "10": { title: "Goblin Ambush!", content: `<p>Two scraggly goblins leap out, brandishing crude spears!</p>`, options: [ { text: "Fight the goblins!", next: 12 }, { text: "Attempt to dodge past them (Dexterity Check)", check: { stat: 'dexterity', dc: 13, onFailure: 101 }, next: 13 } ], illustration: "two-goblins-ambush-forest-path-spears" },
173
- "11": { title: "Hidden Evasion", content: `<p>You melt into the shadows as the goblins blunder past.</p><p class="xp-gain">(+30 XP)</p>`, options: [ { text: "Continue cautiously", next: 14 } ], illustration: "forest-shadows-hiding-goblins-walking-past", reward: { xp: 30 } },
174
- "12": { title: "Ambush Victory!", content: `<p>You defeat the goblins! Found a Crude Dagger.</p><p class="xp-gain">(+50 XP)</p>`, options: [ { text: "Press onward", next: 14 } ], illustration: "defeated-goblins-forest-path-loot", reward: { xp: 50, addItem: "Crude Dagger" } },
175
- "13": { title: "Daring Escape", content: `<p>With surprising agility, you tumble past the goblins!</p><p class="xp-gain">(+25 XP)</p>`, options: [ { text: "Keep running!", next: 14 } ], illustration: "blurred-motion-running-past-goblins-forest", reward: { xp: 25 } },
176
- "14": { title: "Forest Stream Crossing", content: `<p>The path leads to a clear, shallow stream...</p>`, options: [ { text: "Wade across the stream", next: 16 }, { text: "Look for a drier crossing point (fallen log?)", next: 15 } ], illustration: "forest-stream-crossing-dappled-sunlight-stones"},
177
  "15": { title: "Log Bridge", content: `<p>Further upstream, a large, mossy log spans the stream.</p>`, options: [ { text: "Cross carefully on the log (Dexterity Check)", check: { stat: 'dexterity', dc: 9, onFailure: 151 }, next: 16 }, { text: "Go back and wade instead", next: 14 } ], illustration: "mossy-log-bridge-over-forest-stream" },
178
  "151": { title: "Splash!", content: `<p>You slip on the mossy log and tumble into the cold stream! You're soaked but unharmed.</p>`, options: [ { text: "Shake yourself off and continue", next: 16 } ], illustration: "character-splashing-into-stream-from-log" },
179
  "16": { title: "Edge of the Woods", content: `<p>You emerge from the Shadowwood... Before you lie rocky foothills...</p>`, options: [ { text: "Begin the ascent into the foothills", next: 17 }, { text: "Scan the fortress from afar (Wisdom Check)", check: { stat: 'wisdom', dc: 14, onFailure: 17 }, next: 18 } ], illustration: "forest-edge-view-rocky-foothills-distant-mountain-fortress" },
180
  "17": { title: "Rocky Foothills Path", content: `<p>The climb is arduous... The fortress looms larger now.</p>`, options: [ { text: "Continue the direct ascent", next: 19 }, { text: "Look for signs of a hidden trail (Wisdom Check)", check: { stat: 'wisdom', dc: 15, onFailure: 19 }, next: 20 } ], illustration: "climbing-rocky-foothills-path-fortress-closer" },
181
- "18": { title: "Distant Observation", content: `<p>You notice what might be a less-guarded approach along the western ridge...</p><p class="xp-gain">(+30 XP)</p>`, options: [ { text: "Take the main path into the foothills", next: 17 }, { text: "Attempt the western ridge approach", next: 21 } ], illustration: "zoomed-view-mountain-fortress-western-ridge", reward: { xp: 30 } },
182
  "19": { title: "Blocked Pass", content: `<p>The main path is blocked by a recent rockslide!</p>`, options: [ { text: "Try to climb over (Strength Check)", check: { stat: 'strength', dc: 14, onFailure: 191 }, next: 190 }, { text: "Search for another way around", next: 192 } ], illustration: "rockslide-blocking-mountain-path-boulders" },
183
- "20": { title: "Goat Trail", content: `<p>You discover a narrow trail barely wide enough for a mountain goat...</p><p class="xp-gain">(+40 XP)</p>`, options: [ { text: "Follow the precarious goat trail", next: 22 } ], illustration: "narrow-goat-trail-mountainside-fortress-view", reward: { xp: 40 } },
184
- "30": { title: "Hidden Cove", content: `<p>Your careful descent brings you to a secluded cove. A dark cave entrance is visible...</p><p class="xp-gain">(+25 XP)</p>`, options: [ { text: "Explore the dark cave", next: 35 } ], illustration: "hidden-cove-beach-dark-cave-entrance", reward: { xp: 25 } },
185
  "31": { title: "Tumbled Down", content: `<p>You lose your footing... landing hard... You lose 5 HP. A dark cave entrance beckons.</p>`, options: [ { text: "Gingerly explore the dark cave", next: 35 } ], illustration: "character-fallen-at-bottom-of-cliff-path-cove", hpLoss: 5 },
186
  "32": { title: "No Easier Path", content: `<p>You scan the cliffs intently but find no obviously easier routes.</p>`, options: [ { text: "Attempt the precarious descent (Dexterity Check)", check: { stat: 'dexterity', dc: 12, onFailure: 31 }, next: 30 }, { text: "Return to crossroads", next: 1} ], illustration: "scanning-sea-cliffs-no-other-paths-visible" },
187
- "33": { title: "Smuggler's Steps?", content: `<p>Your keen eyes spot a series of barely visible handholds and steps carved into the rock...</p><p class="xp-gain">(+15 XP)</p>`, options: [ { text: "Use the hidden steps (Easier Dex Check)", check: { stat: 'dexterity', dc: 8, onFailure: 31 }, next: 30 } ], illustration: "close-up-handholds-carved-in-cliff-face", reward: { xp: 15 } },
188
- "35": { title: "Dark Cave", content: `<p>The cave smells of salt and decay...</p>`, options: [{ text: "Press deeper into the darkness (End)", next: 99 } ], illustration: "dark-cave-entrance-dripping-water" },
189
  "40": { title: "Overgrown Shrine", content: `<p>Wildflowers grow thick around a small stone shrine...</p>`, options: [{ text: "Examine the carvings (Intelligence Check)", check:{stat:'intelligence', dc:11, onFailure: 401}, next: 400 }, { text: "Leave it be", next: 4 } ], illustration: "overgrown-stone-shrine-wildflowers-close" },
190
  "41": { title: "Rocky Badlands", content: `<p>The green hills give way to cracked earth...</p>`, options: [{ text: "Scout ahead (End)", next: 99 } ], illustration: "rocky-badlands-cracked-earth-harsh-sun" },
191
- "70": { title: "Statue Examined", content: `<p>The statue depicts a forgotten nature deity. You notice a small compartment at its base.</p><p class="xp-gain">(+10 XP)</p>`, options: [{text:"Try to open compartment (Strength Check?)", check:{stat:'strength', dc: 10, onFailure: 71}, next: 700}], illustration:"close-up-mossy-statue-compartment", reward:{xp:10}},
192
  "71": { title: "Statue Unyielding", content: `<p>You examine the statue but learn little. It remains an imposing enigma.</p>`, options: [{text:"Press onward", next: 72}], illustration:"forest-clearing-mossy-statue-weathered-stone-shrug"},
193
  "72": { title: "Deeper Woods", content: `<p>Leaving the statue behind, you push further into the increasingly dense woods.</p>`, options: [{text:"Continue", next: 14}], illustration:"dense-forest-undergrowth-shadows" },
194
  "73": { title: "Offering Made", content: `<p>You leave a small token. For a moment, you think you feel a sense of ancient approval.</p>`, options: [{text:"Press onward", next: 72}], illustration:"offering-at-base-of-mossy-statue"},
195
- "80": { title: "Bridge Crossed", content: `<p>You make it across the swaying bridge, your heart pounding.</p><p class="xp-gain">(+15 XP)</p>`, options: [{text:"Continue on the trail", next: 16}], illustration:"view-from-end-of-rope-bridge-forest", reward:{xp:15}},
196
  "81": { title: "Bridge Collapse!", content: `<p>A frayed rope snaps! You plummet into the shallow ravine below, losing 8 HP!</p>`, options: [{text:"Climb out and find another way", next: 82}], illustration:"character-falling-from-broken-rope-bridge", hpLoss:8},
197
- "82": { title: "Ravine Detour", content: `<p>You find a place where the ravine narrows and manage to climb down and back up the other side.</p><p class="xp-gain">(+5 XP)</p>`, options: [{text:"Continue on the trail", next: 16}], illustration:"climbing-out-of-shallow-ravine-forest", reward:{xp:5}},
198
  "101": { title:"Failed Dodge", content:"<p>You try to dodge, but a goblin spear trips you! You take 3 damage.</p>", options:[{text:"Get up and Fight!", next: 12}], illustration:"character-tripped-by-goblin-spear", hpLoss: 3},
199
- "190": { title: "Over the Rocks", content:"<p>With considerable effort, you clamber over the rockslide.</p><p class="xp-gain">(+35 XP)</p>`, options: [{text:"Continue up the path", next: 22}], illustration:"character-climbing-over-boulders", reward: {xp:35} },
200
  "191": { title: "Climb Fails", content:"<p>The boulders are too unstable. You cannot climb them safely.</p>`, options: [{text:"Search for another way around", next: 192}], illustration:"character-slipping-on-rockslide-boulders"},
201
  "192": { title: "Detour Found", content:"<p>After some searching, you find a rough path leading around the rockslide.</p>`, options: [{text:"Continue up the path", next: 22}], illustration:"rough-detour-path-around-rockslide"},
202
  "21": { title: "Western Ridge", content:"<p>The ridge path is narrow and exposed, with strong winds...</p>`, options: [{text:"Proceed carefully (Dexterity Check)", check:{stat:'dexterity', dc: 14, onFailure: 211}, next: 22 } ], illustration:"narrow-windy-mountain-ridge-path" },
203
  "22": { title: "Fortress Approach", content:"<p>You've navigated the treacherous paths and now stand near the outer walls...</p>`, options: [{text:"Look for an unguarded entrance (End of Demo)", next: 99}], illustration:"approaching-dark-fortress-walls-guards"},
204
  "211": {title:"Lost Balance", content:"<p>A strong gust sends you tumbling down a steep slope! (-10 HP)</p>", options:[{text:"Climb back up and find another way", next: 17}], illustration:"character-falling-off-windy-ridge", hpLoss: 10},
205
- "400": {title:"Shrine Secrets", content:"<p>The carvings depict ancient rituals. You find a loose stone revealing a Healing Poultice!</p><p class="xp-gain">(+20 XP)</p>", options:[{text:"Take the poultice and leave", next:4, addItem:"Healing Poultice"}], illustration:"close-up-shrine-carvings-hidden-compartment", reward:{xp:20}},
206
- "401": {title:"Mysterious Carvings", content:"<p>The carvings are worn and indecipherable.</p>", options:[{text:"Leave the shrine", next:4}], illustration:"worn-stone-carvings-shrine"},
207
- "700": {title:"Statue's Gift", content:"<p>The compartment clicks open, revealing a smooth, grey stone that feels strangely warm.</p><p class="xp-gain">(+30 XP)</p>", options:[{text:"Take the stone and press on", next: 72, addItem:"Warm Stone"}], illustration:"hand-holding-warm-grey-stone-statue-base", reward:{xp:30}},
 
 
 
 
 
208
 
209
  "99": { title: "Game Over / To Be Continued...", content: "<p>Your adventure ends here (for now).</p>", options: [{ text: "Restart", next: 1 }], illustration: "game-over-generic", gameOver: true }
210
  };
@@ -214,16 +236,18 @@
214
  currentPageId: 1,
215
  character: {
216
  name: "Hero", race: "Human", alignment: "Neutral Good", class: "Adventurer",
217
- level: 1, xp: 0, xpToNextLevel: 100, availableStatPoints: 0, // Stat points for leveling
218
  stats: { strength: 8, intelligence: 10, wisdom: 10, dexterity: 10, constitution: 10, charisma: 8, hp: 12, maxHp: 12 },
219
- inventory: []
 
220
  }
221
  };
222
 
223
  // --- Game Logic Functions ---
224
  function startGame() {
225
- const defaultChar = { name: "Hero", race: "Human", alignment: "Neutral Good", class: "Adventurer", level: 1, xp: 0, xpToNextLevel: 100, availableStatPoints: 0, stats: { strength: 8, intelligence: 10, wisdom: 10, dexterity: 10, constitution: 10, charisma: 8, hp: 12, maxHp: 12 }, inventory: [] };
226
  gameState = { currentPageId: 1, character: { ...defaultChar } };
 
227
  recalculateMaxHp();
228
  gameState.character.stats.hp = gameState.character.stats.maxHp;
229
  renderPage(gameState.currentPageId);
@@ -235,21 +259,85 @@
235
  char.level++;
236
  char.xp -= char.xpToNextLevel;
237
  char.xpToNextLevel = Math.floor(char.xpToNextLevel * 1.5 + 50);
238
- char.availableStatPoints += 1; // Gain 1 point
239
  recalculateMaxHp();
240
- char.stats.hp = char.stats.maxHp; // Full heal
241
  console.log(`LEVEL UP! Reached Level ${char.level}.`);
242
- // Later, add UI to spend points. For now, they just accumulate.
243
- updateStatsDisplay(); // Update UI to show new level/XP/HP/Points
244
  return true;
245
  }
246
 
247
  function recalculateMaxHp() {
248
  const char = gameState.character;
249
  const conModifier = Math.floor((char.stats.constitution - 10) / 2);
250
- char.stats.maxHp = 8 + (char.level * Math.max(1, 2 + conModifier)); // Recalculate Max HP
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
  }
252
 
 
253
  function handleChoiceClick(choiceData) {
254
  const optionNextPageId = parseInt(choiceData.nextPage);
255
  const itemToAdd = choiceData.addItem;
@@ -259,25 +347,25 @@
259
  const check = choiceData.check;
260
  const effect = choiceData.effect;
261
 
262
- if (isNaN(optionNextPageId) && !check && !effect) { console.error("Invalid choice data:", choiceData); return; }
263
-
264
- // --- Apply direct effects (like resting) ---
265
- if (effect) {
266
- if (effect.hpGain) {
267
- const maxHeal = gameState.character.stats.maxHp - gameState.character.stats.hp;
268
- const actualGain = Math.min(effect.hpGain, maxHeal);
269
- if (actualGain > 0) {
270
- gameState.character.stats.hp += actualGain;
271
- rollResultMessage += `<p class="xp-gain">Rested and recovered ${actualGain} HP.</p>`;
272
- console.log(`Recovered ${actualGain} HP.`);
273
- } else {
274
- rollResultMessage += `<p class="xp-gain">You rest, but gain no HP.</p>`;
275
- }
276
- }
277
- // If effect determines next page, override default
278
- if (effect.setNextPage !== undefined) nextPageId = effect.setNextPage;
279
- // For simple rest, we still want to proceed, so no return here.
280
- }
281
 
282
  // --- Process Stat Check ---
283
  if (check) {
@@ -290,10 +378,10 @@
290
  console.log(`Check: ${check.stat} (DC ${dc}) | Roll: ${roll} + Mod: ${modifier} = ${totalResult}`);
291
 
292
  if (totalResult >= dc) { // Success
293
- nextPageId = optionNextPageId;
294
  rollResultMessage += `<p class="roll-success"><em>Check Success! (${totalResult} vs DC ${dc})</em></p>`;
295
- const marginBonus = Math.max(0, Math.floor(successMargin * 1.0)); // XP per point over DC
296
- const oddsBonus = Math.max(0, Math.floor(dc * 0.5)); // XP for difficulty
297
  const checkBonusXp = marginBonus + oddsBonus;
298
  if (checkBonusXp > 0) { gainedXpThisTurn += checkBonusXp; rollResultMessage += `<p class="xp-gain">+${checkBonusXp} bonus XP!</p>`; console.log(`Check bonus XP: ${checkBonusXp}`); }
299
  } else { // Failure
@@ -313,40 +401,31 @@
313
  const nextPageData = gameData[nextPageId];
314
 
315
  if (nextPageData) {
316
- if (nextPageData.hpLoss) {
317
- gameState.character.stats.hp -= nextPageData.hpLoss;
318
- console.log(`Lost ${nextPageData.hpLoss} HP.`);
319
- // HP check is done after potential level up healing
320
- }
321
  if (nextPageData.reward) {
322
  if (nextPageData.reward.xp) { gainedXpThisTurn += nextPageData.reward.xp; console.log(`Base reward: +${nextPageData.reward.xp} XP.`); }
323
- if (nextPageData.reward.statIncrease) { const stat = nextPageData.reward.statIncrease.stat; const amount = nextPageData.reward.statIncrease.amount; if (gameState.character.stats.hasOwnProperty(stat)) { gameState.character.stats[stat] += amount; console.log(`Stat ${stat} increased by ${amount}.`); recalculateMaxHp(); } } // Recalc HP if CON changes
324
  if(nextPageData.reward.addItem && !gameState.character.inventory.includes(nextPageData.reward.addItem)){ gameState.character.inventory.push(nextPageData.reward.addItem); console.log(`Found item: ${nextPageData.reward.addItem}`); }
325
  }
326
 
327
  if (gainedXpThisTurn > 0) {
328
  gameState.character.xp += gainedXpThisTurn;
329
  console.log(`Total XP Gained: ${gainedXpThisTurn}. Current XP: ${gameState.character.xp}`);
330
- if (!rollResultMessage.includes("bonus XP")) { // Avoid double message if check bonus already added
331
- rollResultMessage += `<p class="xp-gain">You gained ${gainedXpThisTurn} XP.</p>`;
332
- }
333
  }
334
 
335
  let leveledUp = false;
336
- while (gameState.character.xp >= gameState.character.xpToNextLevel) {
337
- if (levelUpCharacter()) { leveledUp = true; } else { break; }
338
- }
339
  if (leveledUp) { rollResultMessage += `<p class="level-up">LEVEL UP! You reached Level ${gameState.character.level}!</p>`; }
340
 
341
- recalculateMaxHp(); // Ensure maxHP is current
342
- gameState.character.stats.hp = Math.min(gameState.character.stats.hp, gameState.character.stats.maxHp); // Clamp HP
343
  gameState.character.stats.hp = Math.max(0, gameState.character.stats.hp);
344
 
345
- // Check for death *after* potential healing from level up
346
- if (gameState.character.stats.hp <= 0) {
347
- console.log("Player died!"); nextPageId = 99; // Force redirect
348
- renderPageInternal(99, gameData[99], rollResultMessage + "<p class='roll-failure'><em>Your wounds overwhelm you...</em></p>"); return;
349
- }
350
 
351
  } else { // Invalid next page ID
352
  console.error(`Data for page ${nextPageId} not found!`);
@@ -357,14 +436,23 @@
357
 
358
  function renderPageInternal(pageId, pageData, message = "") {
359
  if (!pageData) { console.error(`Render Error: No data for page ${pageId}`); return; }
 
 
 
 
360
  storyTitleElement.textContent = pageData.title || "Untitled Page";
361
  storyContentElement.innerHTML = message + (pageData.content || "<p>...</p>");
362
- updateStatsDisplay(); updateInventoryDisplay();
 
363
  choicesElement.innerHTML = '';
364
  if (pageData.options && pageData.options.length > 0) {
365
  pageData.options.forEach(option => {
366
  const button = document.createElement('button'); button.classList.add('choice-button'); button.textContent = option.text; let requirementMet = true;
 
367
  if (option.requireItem && !gameState.character.inventory.includes(option.requireItem)) { requirementMet = false; button.title = `Requires: ${option.requireItem}`; button.disabled = true; }
 
 
 
368
  if (requirementMet) { const choiceData = { nextPage: option.next, addItem: option.addItem, check: option.check, effect: option.effect }; button.onclick = () => handleChoiceClick(choiceData); } else { button.classList.add('disabled'); } choicesElement.appendChild(button); });
369
  } else { const button = document.createElement('button'); button.classList.add('choice-button'); button.textContent = pageData.gameOver ? "Restart Adventure" : "The End"; button.onclick = () => handleChoiceClick({ nextPage: pageData.gameOver ? 1 : 99 }); choicesElement.appendChild(button); if (!pageData.gameOver) choicesElement.insertAdjacentHTML('afterbegin', '<p><i>The path ends here.</i></p>'); }
370
  updateScene(pageData.illustration || 'default', pageData.sceneParams);
@@ -372,27 +460,60 @@
372
 
373
  function renderPage(pageId) { renderPageInternal(pageId, gameData[pageId]); }
374
 
375
- function updateStatsDisplay() { const char=gameState.character; statsElement.innerHTML = `<strong>Stats:</strong> <span>Lvl: ${char.level}</span> <span>XP: ${char.xp}/${char.xpToNextLevel}</span> <span>HP: ${char.stats.hp}/${char.stats.maxHp}</span> <span title="Strength">Str: ${char.stats.strength}</span> <span title="Intelligence">Int: ${char.stats.intelligence}</span> <span title="Wisdom">Wis: ${char.stats.wisdom}</span> <span title="Dexterity">Dex: ${char.stats.dexterity}</span> <span title="Constitution">Con: ${char.stats.constitution}</span> <span title="Charisma">Cha: ${char.stats.charisma}</span>`; } // Added titles
376
  function updateInventoryDisplay() { let h='<strong>Inventory:</strong> '; if(gameState.character.inventory.length === 0){ h+='<em>Empty</em>'; } else { gameState.character.inventory.forEach(i=>{ const d=itemsData[i]||{type:'unknown',description:'???'}; const c=`item-${d.type||'unknown'}`; h+=`<span class="${c}" title="${d.description}">${i}</span>`; }); } inventoryElement.innerHTML = h; }
377
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
378
  function updateScene(illustrationKey, sceneParams = {}) {
379
  if (currentAssemblyGroup) { scene.remove(currentAssemblyGroup); }
380
- currentAssemblyGroup = null; let assemblyFunction;
381
- // Simple routing for now, using default for most new keys
382
- switch (illustrationKey) {
383
- case 'city-gates': assemblyFunction = createCityGatesAssembly; break;
 
384
  case 'weaponsmith': assemblyFunction = createWeaponsmithAssembly; break;
385
  case 'temple': assemblyFunction = createTempleAssembly; break;
386
- case 'resistance-meeting': assemblyFunction = createResistanceMeetingAssembly; break;
387
- case 'shadowwood-forest': case 'dark-forest-entrance-gnarled-roots-filtered-light': case 'overgrown-forest-path-glowing-fungi-vines': case 'forest-clearing-mossy-statue-weathered-stone': case 'narrow-game-trail-forest-rope-bridge-ravine': case 'forest-stream-crossing-dappled-sunlight-stones': case 'mossy-log-bridge-over-forest-stream': case 'dense-forest-undergrowth-shadows': assemblyFunction = createForestAssembly; break; // Group forest keys
388
- case 'road-ambush': case 'two-goblins-ambush-forest-path-spears': assemblyFunction = createRoadAmbushAssembly; break; // Group ambush keys
389
- case 'forest-edge': case 'forest-edge-view-rocky-foothills-distant-mountain-fortress': assemblyFunction = createForestEdgeAssembly; break; // Group edge keys
390
- case 'prisoner-cell': assemblyFunction = createPrisonerCellAssembly; break;
391
- case 'game-over': case 'game-over-generic': assemblyFunction = createGameOverAssembly; break;
 
 
 
 
392
  case 'error': assemblyFunction = createErrorAssembly; break;
393
- // Add more specific assignments if needed
394
- default: assemblyFunction = createDefaultAssembly; break;
395
  }
 
 
396
  try { currentAssemblyGroup = assemblyFunction(sceneParams); scene.add(currentAssemblyGroup); } catch (error) { console.error(`Error creating assembly for ${illustrationKey}:`, error); currentAssemblyGroup = createErrorAssembly(); scene.add(currentAssemblyGroup); }
397
  }
398
 
 
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Choose Your Own Procedural Adventure</title>
7
  <style>
8
  body{font-family:'Courier New',monospace;background-color:#222;color:#eee;margin:0;padding:0;overflow:hidden;display:flex;flex-direction:column;height:100vh}
9
  #game-container{display:flex;flex-grow:1;overflow:hidden}
 
32
  .choice-button:disabled{background-color:#444;color:#888;cursor:not-allowed;border-color:#666;opacity:0.7}
33
  .roll-success{color:#7f7;border-left:3px solid #4a4;padding-left:8px;margin-bottom:1em;font-size:0.9em}
34
  .roll-failure{color:#f77;border-left:3px solid #a44;padding-left:8px;margin-bottom:1em;font-size:0.9em}
35
+ .xp-gain{color:#7af;font-style:italic;font-size:0.9em;display:block;margin-top:0.5em;}
36
+ .level-up{color:#ffcc66;font-weight:bold;border:1px dashed #ffcc66;padding:5px;margin-bottom:1em;text-align:center;}
37
+ /* Optional: Style for Known NPCs display */
38
+ #known-npcs-display { margin-top: 10px; }
39
+ #known-npcs-display span { background-color: #404850; border-color: #607080; } /* Bluish */
40
+ #known-npcs-display .npc-allied { background-color: #306630; border-color: #489948; } /* Green */
41
+ #known-npcs-display .npc-hostile { background-color: #663030; border-color: #994848; } /* Red */
42
+ #known-npcs-display .npc-wary { background-color: #666030; border-color: #999048; } /* Yellowish */
43
  </style>
44
  </head>
45
  <body>
 
54
  <div id="stats-inventory-container">
55
  <div id="stats-display"></div>
56
  <div id="inventory-display"></div>
57
+ <div id="known-npcs-display"></div> </div>
58
  <div id="choices-container">
59
  <h3>What will you do?</h3>
60
  <div id="choices"></div>
 
80
  const choicesElement = document.getElementById('choices');
81
  const statsElement = document.getElementById('stats-display');
82
  const inventoryElement = document.getElementById('inventory-display');
83
+ const knownNpcsElement = document.getElementById('known-npcs-display'); // Get new element
84
 
85
  let scene, camera, renderer;
86
  let currentAssemblyGroup = null;
 
89
  const woodMaterial = new THREE.MeshStandardMaterial({ color: 0x8B4513, roughness: 0.7, metalness: 0 });
90
  const darkWoodMaterial = new THREE.MeshStandardMaterial({ color: 0x5C3D20, roughness: 0.7, metalness: 0 });
91
  const leafMaterial = new THREE.MeshStandardMaterial({ color: 0x2E8B57, roughness: 0.6, metalness: 0 });
92
+ const pineLeafMaterial = new THREE.MeshStandardMaterial({ color: 0x1A5A2A, roughness: 0.7, metalness: 0 });
93
+ const gnarledWoodMaterial = new THREE.MeshStandardMaterial({ color: 0x6B4F3A, roughness: 0.85, metalness: 0 });
94
  const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x556B2F, roughness: 0.9, metalness: 0 });
95
  const metalMaterial = new THREE.MeshStandardMaterial({ color: 0xaaaaaa, metalness: 0.8, roughness: 0.3 });
96
  const templeMaterial = new THREE.MeshStandardMaterial({ color: 0xA99B78, roughness: 0.7, metalness: 0.1 });
97
  const errorMaterial = new THREE.MeshStandardMaterial({ color: 0xffa500, roughness: 0.5 });
98
  const gameOverMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000, roughness: 0.5 });
 
 
 
99
 
100
  function initThreeJS() {
101
+ // ... (Keep existing initThreeJS - no changes needed here) ...
102
  if (!sceneContainer) { console.error("Scene container not found!"); return; }
103
+ scene = new THREE.Scene(); scene.background = new THREE.Color(0x222222);
 
104
  const width = sceneContainer.clientWidth; const height = sceneContainer.clientHeight;
105
  camera = new THREE.PerspectiveCamera(75, (width / height) || 1, 0.1, 1000);
106
  camera.position.set(0, 2.5, 7); camera.lookAt(0, 0.5, 0);
 
123
  }
124
 
125
  function onWindowResize() {
126
+ // ... (Keep existing onWindowResize) ...
127
+ if (!renderer || !camera || !sceneContainer) return;
128
  const width = sceneContainer.clientWidth; const height = sceneContainer.clientHeight;
129
  if (width > 0 && height > 0) { camera.aspect = width / height; camera.updateProjectionMatrix(); renderer.setSize(width, height); }
130
  }
131
 
132
  function animate() {
133
+ // ... (Keep existing animate) ...
134
  requestAnimationFrame(animate);
135
  if (renderer && scene && camera) { renderer.render(scene, camera); }
136
  }
137
 
138
  function createMesh(geometry, material, position = { x: 0, y: 0, z: 0 }, rotation = { x: 0, y: 0, z: 0 }, scale = { x: 1, y: 1, z: 1 }) {
139
+ // ... (Keep existing createMesh) ...
140
  const mesh = new THREE.Mesh(geometry, material);
141
  mesh.position.set(position.x, position.y, position.z); mesh.rotation.set(rotation.x, rotation.y, rotation.z); mesh.scale.set(scale.x, scale.y, scale.z);
142
  mesh.castShadow = true; mesh.receiveShadow = true;
 
144
  }
145
 
146
  function createGroundPlane(material = groundMaterial, size = 20) {
147
+ // ... (Keep existing createGroundPlane) ...
148
+ const groundGeo = new THREE.PlaneGeometry(size, size);
149
  const ground = new THREE.Mesh(groundGeo, material);
150
  ground.rotation.x = -Math.PI / 2; ground.position.y = -0.05;
151
  ground.receiveShadow = true; ground.castShadow = false;
152
  return ground;
153
  }
154
 
155
+ // --- Procedural Generation Functions ---
156
+ // ... (Keep ALL existing create...Assembly functions, including parameterized createForestAssembly) ...
157
+ function createDefaultAssembly(params={}) { const group = new THREE.Group(); const sphereGeo = new THREE.SphereGeometry(0.5, 16, 16); group.add(createMesh(sphereGeo, stoneMaterial, { x: 0, y: 0.5, z: 0 })); group.add(createGroundPlane()); return group; }
158
+ function createCityGatesAssembly(params = {}) { const group = new THREE.Group(); const gh=params.height||4, gw=params.width||1.5, gd=params.depth||0.8, ah=1, aw=3; const tlGeo = new THREE.BoxGeometry(gw, gh, gd); group.add(createMesh(tlGeo, stoneMaterial, { x:-(aw/2+gw/2), y:gh/2, z:0 })); const trGeo = new THREE.BoxGeometry(gw, gh, gd); group.add(createMesh(trGeo, stoneMaterial, { x:(aw/2+gw/2), y:gh/2, z:0 })); const aGeo = new THREE.BoxGeometry(aw, ah, gd); group.add(createMesh(aGeo, stoneMaterial, { x:0, y:gh-ah/2, z:0 })); const cs=0.4; const cg = new THREE.BoxGeometry(cs, cs, gd*1.1); if(params.crenellations !== false){ for(let i=-1; i<=1; i+=2){ group.add(createMesh(cg.clone(), stoneMaterial, { x:-(aw/2+gw/2)+i*cs*0.7, y:gh+cs/2, z:0 })); group.add(createMesh(cg.clone(), stoneMaterial, { x:(aw/2+gw/2)+i*cs*0.7, y:gh+cs/2, z:0 })); } group.add(createMesh(cg.clone(), stoneMaterial, { x:0, y:gh+ah-cs/2, z:0 }));} group.add(createGroundPlane(stoneMaterial)); return group; }
159
+ function createWeaponsmithAssembly(params = {}) { const group = new THREE.Group(); const bw=params.size||3, bh=2.5, bd=3.5; const mat = params.material === 'stone' ? stoneMaterial : darkWoodMaterial; const bGeo = new THREE.BoxGeometry(bw, bh, bd); group.add(createMesh(bGeo, mat, { x:0, y:bh/2, z:0 })); if(params.chimney !== false) { const ch=3.5; const cGeo = new THREE.CylinderGeometry(0.3, 0.4, ch, 8); group.add(createMesh(cGeo, stoneMaterial, { x:bw*0.3, y:ch/2, z:-bd*0.3 }));} group.add(createGroundPlane()); return group; }
160
+ function createTempleAssembly(params = {}) { const group = new THREE.Group(); const bs=5, bsh=0.5, ch=3, cr=0.25, rh=0.5; const bGeo = new THREE.BoxGeometry(bs, bsh, bs); group.add(createMesh(bGeo, templeMaterial, { x:0, y:bsh/2, z:0 })); const cGeo = new THREE.CylinderGeometry(cr, cr, ch, 12); const cPos = [{x:-bs/3, z:-bs/3}, {x:bs/3, z:-bs/3}, {x:-bs/3, z:bs/3}, {x:bs/3, z:bs/3}]; cPos.forEach(p=>group.add(createMesh(cGeo.clone(), templeMaterial, { x:p.x, y:bsh+ch/2, z:p.z }))); const rGeo = new THREE.BoxGeometry(bs*0.9, rh, bs*0.9); group.add(createMesh(rGeo, templeMaterial, { x:0, y:bsh+ch+rh/2, z:0 })); group.add(createGroundPlane()); return group; }
161
+ function createResistanceMeetingAssembly(params = {}) { const group = new THREE.Group(); const tw=2, th=0.8, td=1, tt=0.1; const ttg = new THREE.BoxGeometry(tw, tt, td); group.add(createMesh(ttg, woodMaterial, { x:0, y:th-tt/2, z:0 })); const lh=th-tt, ls=0.1; const lg=new THREE.BoxGeometry(ls, lh, ls); const lofW=tw/2-ls*1.5; const lofD=td/2-ls*1.5; group.add(createMesh(lg, woodMaterial, { x:-lofW, y:lh/2, z:-lofD })); group.add(createMesh(lg.clone(), woodMaterial, { x:lofW, y:lh/2, z:-lofD })); group.add(createMesh(lg.clone(), woodMaterial, { x:-lofW, y:lh/2, z:lofD })); group.add(createMesh(lg.clone(), woodMaterial, { x:lofW, y:lh/2, z:lofD })); const ss=0.4; const sg=new THREE.BoxGeometry(ss, ss*0.8, ss); group.add(createMesh(sg, darkWoodMaterial, { x:-tw*0.6, y:ss*0.4, z:0 })); group.add(createMesh(sg.clone(), darkWoodMaterial, { x:tw*0.6, y:ss*0.4, z:0 })); group.add(createGroundPlane(stoneMaterial)); return group; }
162
+ function createForestAssembly(params = {}) { const group = new THREE.Group(); const treeCount = params.count ?? 10; const area = params.area ?? 10; const treeTypes = params.types ?? ['deciduous']; const avgHeight = params.avgHeight ?? 2.5; const foliageDensity = params.foliageDensity ?? 1.0; const createTree = (x, z, type) => { const treeGroup = new THREE.Group(); let trunkMat = woodMaterial; let leafMat = leafMaterial; let trunkHeight = avgHeight + (Math.random() - 0.5) * avgHeight * 0.4; let trunkRadius = trunkHeight * (0.05 + Math.random() * 0.05); let foliageRadius = trunkHeight * 0.4 * foliageDensity; if (type === 'pine') { leafMat = pineLeafMaterial; trunkHeight *= 1.2; trunkRadius *= 0.8; foliageRadius = trunkHeight * 0.25 * foliageDensity; } else if (type === 'gnarled') { trunkMat = gnarledWoodMaterial; trunkHeight *= 0.8; trunkRadius *= 1.5; foliageRadius = trunkHeight * 0.5 * foliageDensity; } const trunkGeo = new THREE.CylinderGeometry(trunkRadius * 0.7, trunkRadius, trunkHeight, 8); treeGroup.add(createMesh(trunkGeo, trunkMat, { x: 0, y: trunkHeight / 2, z: 0 })); if (type === 'pine') { const numCones = Math.max(2, Math.floor(3 * foliageDensity)); for(let i=0; i<numCones; i++){ const coneR = foliageRadius * (1.5 - i*0.3); const coneH = trunkHeight * 0.4 * (1 - i*0.1); const coneY = trunkHeight * 0.7 + i * coneH * 0.3; const coneGeo = new THREE.ConeGeometry(coneR, coneH, 8); treeGroup.add(createMesh(coneGeo, leafMat, { x: 0, y: coneY, z: 0 })); } } else { const foliageCount = Math.max(3, Math.floor((Math.random() * 4 + 4) * foliageDensity)); const sphereRadius = foliageRadius * 0.3 + Math.random() * 0.1; const sphereGeo = new THREE.SphereGeometry(sphereRadius, 6, 5); for (let i = 0; i < foliageCount; i++) { const offsetX = (Math.random() - 0.5) * foliageRadius * 1.5; const offsetY = Math.random() * foliageRadius * 0.8; const offsetZ = (Math.random() - 0.5) * foliageRadius * 1.5; treeGroup.add(createMesh(sphereGeo.clone(), leafMat, { x: offsetX, y: trunkHeight * 0.8 + offsetY, z: offsetZ })); } } treeGroup.position.set(x, 0, z); treeGroup.rotation.y = Math.random() * Math.PI * 2; return treeGroup; }; for (let i = 0; i < treeCount; i++) { const x = (Math.random() - 0.5) * area; const z = (Math.random() - 0.5) * area; const type = treeTypes[Math.floor(Math.random() * treeTypes.length)]; if (Math.sqrt(x*x + z*z) > 1.0) group.add(createTree(x, z, type)); } group.add(createGroundPlane(groundMaterial, area * 1.1)); return group; }
163
+ function createRoadAmbushAssembly(params={}) { const group = new THREE.Group(); const a=12; const fg = createForestAssembly({ count: 8, area: a, types: params.forestTypes ?? ['deciduous', 'pine'] }); group.add(fg); const rw=3, rl=a*1.2; const rGeo=new THREE.PlaneGeometry(rw, rl); const rMat=new THREE.MeshStandardMaterial({color:0x966F33, roughness:0.9}); const r=createMesh(rGeo, rMat, {x:0, y:0.01, z:0}, {x:-Math.PI/2}); r.receiveShadow=true; group.add(r); const rkGeo=new THREE.SphereGeometry(0.5, 5, 4); const rkMat=new THREE.MeshStandardMaterial({color:0x666666, roughness:0.8}); group.add(createMesh(rkGeo, rkMat, {x:rw*0.7, y:0.25, z:1}, {y:Math.random()*Math.PI})); group.add(createMesh(rkGeo.clone().scale(0.8,0.8,0.8), rkMat, {x:-rw*0.8, y:0.2, z:-2}, {y:Math.random()*Math.PI})); return group; }
164
+ function createForestEdgeAssembly(params={}) { const group = new THREE.Group(); const a=15; const fg = createForestAssembly({ count: 15, area: a, types: params.forestTypes ?? ['deciduous', 'pine'] }); const ttr=[]; fg.children.forEach(c => { if(c.type === 'Group' && c.position.x > 0) ttr.push(c); }); ttr.forEach(t => fg.remove(t)); group.add(fg); return group; }
165
+ function createPrisonerCellAssembly(params = {}) { const group = new THREE.Group(); const cs=3, wh=2.5, wt=0.2, br=0.05, bsp=0.25; const cfMat=stoneMaterial.clone(); cfMat.color.setHex(0x555555); group.add(createGroundPlane(cfMat, cs)); const wbGeo=new THREE.BoxGeometry(cs, wh, wt); group.add(createMesh(wbGeo, stoneMaterial, {x:0, y:wh/2, z:-cs/2})); const wsGeo=new THREE.BoxGeometry(wt, wh, cs); group.add(createMesh(wsGeo, stoneMaterial, {x:-cs/2, y:wh/2, z:0})); group.add(createMesh(wsGeo.clone(), stoneMaterial, {x:cs/2, y:wh/2, z:0})); const bGeo=new THREE.CylinderGeometry(br, br, wh, 8); const nb=Math.floor(cs/bsp); for(let i=0; i<nb; i++){ const xp=-cs/2+(i+0.5)*bsp; group.add(createMesh(bGeo.clone(), metalMaterial, {x:xp, y:wh/2, z:cs/2})); } return group; }
166
+ function createGameOverAssembly(params = {}) { const group = new THREE.Group(); const boxGeo = new THREE.BoxGeometry(2, 2, 2); group.add(createMesh(boxGeo, gameOverMaterial, { x: 0, y: 1, z: 0 })); group.add(createGroundPlane(stoneMaterial.clone().set({color: 0x333333}))); return group; }
167
+ function createErrorAssembly(params = {}) { const group = new THREE.Group(); const coneGeo = new THREE.ConeGeometry( 0.8, 1.5, 8 ); group.add(createMesh(coneGeo, errorMaterial, { x: 0, y: 0.75, z: 0 })); group.add(createGroundPlane()); return group; }
168
+
169
+ // --- NPC Data ---
170
+ const npcs = {
171
+ "gorn": { name: "Gorn the Weaponsmith", description: "Gruff but skilled.", initialDisposition: "neutral", locationHint: "Silverhold" },
172
+ "alara": { name: "High Priestess Alara", description: "Serene and wise.", initialDisposition: "helpful", locationHint: "Silverhold Temple" },
173
+ "lyra": { name: "Lyra, Resistance Leader", description: "Determined and wary.", initialDisposition: "neutral", locationHint: "Silverhold (Secret)" },
174
+ "shepherd": { name: "Old Man Hemlock", description: "A simple shepherd.", initialDisposition: "neutral", locationHint: "Rolling Hills" },
175
+ "cliff_hermit": { name: "Silas the Hermit", description: "Lives in the cliff caves.", initialDisposition: "wary", locationHint: "Coastal Cliffs" }
176
+ };
177
 
178
  // --- Game Data ---
179
+ const itemsData = { "Flaming Sword":{type:"weapon", description:"A fiery blade"}, /* ... other items ... */ "Crude Dagger":{type:"weapon", description:"A roughly made dagger."}, "Scout's Pouch":{type:"quest", description:"Contains odds and ends."}, "Healing Poultice":{type:"spell", description:"Soothes wounds, heals 5 HP."}, "Warm Stone":{type:"quest", description:"A smooth grey stone, strangely warm."} };
180
+ const gameData = { // Using expanded data with checks, rewards, onEnter events
181
+ "1": { title: "The Crossroads", content: `<p>Dust swirls... Which path calls to you?</p>`, options: [ { text: "Enter the Shadowwood Forest (North)", next: 5 }, { text: "Head towards the Rolling Hills (East)", next: 2 }, { text: "Investigate the Coastal Cliffs (West)", next: 3 }, { text: "Rest and gather thoughts", effect: { hpGain: 5, setNextPage: 1 } } ], illustration: "crossroads-signpost-sunny" },
182
+ "2": { title: "Rolling Hills", content: `<p>Verdant hills stretch before you...</p>`, options: [ { text: "Follow the narrow path", next: 4 }, { text: "Head back to the crossroads", next: 1 } ], illustration: "rolling-green-hills-shepherd-distance", onEnter: [{ action: "meetNpc", npcId: "shepherd", setDisposition: "seen" }] }, // Example: NPC seen
183
  "3": { title: "Coastal Cliffs Edge", content: `<p>You stand atop windswept cliffs...</p>`, options: [ { text: "Attempt the precarious descent (Dexterity Check)", check: { stat: 'dexterity', dc: 12, onFailure: 31 }, next: 30 }, { text: "Scan the cliff face for easier routes (Wisdom Check)", check: { stat: 'wisdom', dc: 11, onFailure: 32 }, next: 33 }, { text: "Return to the crossroads", next: 1 } ], illustration: "windy-sea-cliffs-crashing-waves-path-down" },
184
  "4": { title: "Hill Path Overlook", content: `<p>The path crests a hill... you see a small, overgrown shrine...</p>`, options: [ { text: "Investigate the overgrown shrine", next: 40 }, { text: "Continue towards the badlands", next: 41 }, { text: "Go back", next: 2 } ], illustration: "hilltop-view-overgrown-shrine-wildflowers" },
185
+ "5": { title: "Shadowwood Entrance", content: `<p>Sunlight struggles to pierce the dense canopy... How do you proceed?</p>`, options: [ { text: "Follow the main, albeit overgrown, path", next: 6 }, { text: "Try to navigate through the lighter undergrowth", next: 7 }, { text: "Look for animal trails or signs of passage (Wisdom Check)", check: { stat: 'wisdom', dc: 10, onFailure: 6 }, next: 8 } ], illustration: "dark-forest-entrance-gnarled-roots-filtered-light", sceneParams: { types: ['deciduous', 'gnarled'], density: 1.2, avgHeight: 3.5 } },
186
+ "6": { title: "Overgrown Forest Path", content: `<p>The path is barely visible... You hear a twig snap nearby!</p>`, options: [ { text: "Ready your weapon and investigate", next: 10 }, { text: "Attempt to hide quietly (Dexterity Check)", check: { stat: 'dexterity', dc: 11, onFailure: 10 }, next: 11 }, { text: "Call out cautiously", next: 10 } ], illustration: "overgrown-forest-path-glowing-fungi-vines", sceneParams: { types: ['deciduous', 'gnarled'], density: 1.5 } },
187
  "7": { title: "Tangled Undergrowth", content: `<p>Pushing through ferns... You stumble upon a small clearing containing a moss-covered, weathered stone statue...</p>`, options: [ { text: "Examine the statue closely (Intelligence Check)", check: { stat: 'intelligence', dc: 13, onFailure: 71 }, next: 70 }, { text: "Ignore the statue and press on", next: 72 }, { text: "Leave a small offering (if possible)", next: 73 } ], illustration: "forest-clearing-mossy-statue-weathered-stone" },
188
+ "8": { title: "Hidden Game Trail", content: `<p>Your sharp eyes spot a faint trail... It leads towards a ravine spanned by a rickety rope bridge.</p>`, options: [ { text: "Risk crossing the rope bridge (Dexterity Check)", check: { stat: 'dexterity', dc: 10, onFailure: 81 }, next: 80 }, { text: "Search for another way across the ravine", next: 82 } ], illustration: "narrow-game-trail-forest-rope-bridge-ravine", reward: { xp: 20 } },
189
  "10": { title: "Goblin Ambush!", content: `<p>Two scraggly goblins leap out, brandishing crude spears!</p>`, options: [ { text: "Fight the goblins!", next: 12 }, { text: "Attempt to dodge past them (Dexterity Check)", check: { stat: 'dexterity', dc: 13, onFailure: 101 }, next: 13 } ], illustration: "two-goblins-ambush-forest-path-spears" },
190
+ "11": { title: "Hidden Evasion", content: `<p>You melt into the shadows as the goblins blunder past.</p>`, options: [ { text: "Continue cautiously", next: 14 } ], illustration: "forest-shadows-hiding-goblins-walking-past", reward: { xp: 30 } },
191
+ "12": { title: "Ambush Victory!", content: `<p>You defeat the goblins! Found a Crude Dagger.</p>`, options: [ { text: "Press onward", next: 14 } ], illustration: "defeated-goblins-forest-path-loot", reward: { xp: 50, addItem: "Crude Dagger" } },
192
+ "13": { title: "Daring Escape", content: `<p>With surprising agility, you tumble past the goblins!</p>`, options: [ { text: "Keep running!", next: 14 } ], illustration: "blurred-motion-running-past-goblins-forest", reward: { xp: 25 } },
193
+ "14": { title: "Forest Stream Crossing", content: `<p>The path leads to a clear, shallow stream...</p>`, options: [ { text: "Wade across the stream", next: 16 }, { text: "Look for a drier crossing point (fallen log?)", next: 15 } ], illustration: "forest-stream-crossing-dappled-sunlight-stones", sceneParams: { types: ['deciduous'], density: 0.8, avgHeight: 2.8 } },
194
  "15": { title: "Log Bridge", content: `<p>Further upstream, a large, mossy log spans the stream.</p>`, options: [ { text: "Cross carefully on the log (Dexterity Check)", check: { stat: 'dexterity', dc: 9, onFailure: 151 }, next: 16 }, { text: "Go back and wade instead", next: 14 } ], illustration: "mossy-log-bridge-over-forest-stream" },
195
  "151": { title: "Splash!", content: `<p>You slip on the mossy log and tumble into the cold stream! You're soaked but unharmed.</p>`, options: [ { text: "Shake yourself off and continue", next: 16 } ], illustration: "character-splashing-into-stream-from-log" },
196
  "16": { title: "Edge of the Woods", content: `<p>You emerge from the Shadowwood... Before you lie rocky foothills...</p>`, options: [ { text: "Begin the ascent into the foothills", next: 17 }, { text: "Scan the fortress from afar (Wisdom Check)", check: { stat: 'wisdom', dc: 14, onFailure: 17 }, next: 18 } ], illustration: "forest-edge-view-rocky-foothills-distant-mountain-fortress" },
197
  "17": { title: "Rocky Foothills Path", content: `<p>The climb is arduous... The fortress looms larger now.</p>`, options: [ { text: "Continue the direct ascent", next: 19 }, { text: "Look for signs of a hidden trail (Wisdom Check)", check: { stat: 'wisdom', dc: 15, onFailure: 19 }, next: 20 } ], illustration: "climbing-rocky-foothills-path-fortress-closer" },
198
+ "18": { title: "Distant Observation", content: `<p>You notice what might be a less-guarded approach along the western ridge...</p>`, options: [ { text: "Take the main path into the foothills", next: 17 }, { text: "Attempt the western ridge approach", next: 21 } ], illustration: "zoomed-view-mountain-fortress-western-ridge", reward: { xp: 30 } },
199
  "19": { title: "Blocked Pass", content: `<p>The main path is blocked by a recent rockslide!</p>`, options: [ { text: "Try to climb over (Strength Check)", check: { stat: 'strength', dc: 14, onFailure: 191 }, next: 190 }, { text: "Search for another way around", next: 192 } ], illustration: "rockslide-blocking-mountain-path-boulders" },
200
+ "20": { title: "Goat Trail", content: `<p>You discover a narrow trail barely wide enough for a mountain goat...</p>`, options: [ { text: "Follow the precarious goat trail", next: 22 } ], illustration: "narrow-goat-trail-mountainside-fortress-view", reward: { xp: 40 } },
201
+ "30": { title: "Hidden Cove", content: `<p>Your careful descent brings you to a secluded cove. A dark cave entrance is visible...</p>`, options: [ { text: "Explore the dark cave", next: 35 } ], illustration: "hidden-cove-beach-dark-cave-entrance", reward: { xp: 25 } },
202
  "31": { title: "Tumbled Down", content: `<p>You lose your footing... landing hard... You lose 5 HP. A dark cave entrance beckons.</p>`, options: [ { text: "Gingerly explore the dark cave", next: 35 } ], illustration: "character-fallen-at-bottom-of-cliff-path-cove", hpLoss: 5 },
203
  "32": { title: "No Easier Path", content: `<p>You scan the cliffs intently but find no obviously easier routes.</p>`, options: [ { text: "Attempt the precarious descent (Dexterity Check)", check: { stat: 'dexterity', dc: 12, onFailure: 31 }, next: 30 }, { text: "Return to crossroads", next: 1} ], illustration: "scanning-sea-cliffs-no-other-paths-visible" },
204
+ "33": { title: "Smuggler's Steps?", content: `<p>Your keen eyes spot a series of barely visible handholds and steps carved into the rock...</p>`, options: [ { text: "Use the hidden steps (Easier Dex Check)", check: { stat: 'dexterity', dc: 8, onFailure: 31 }, next: 30 } ], illustration: "close-up-handholds-carved-in-cliff-face", reward: { xp: 15 } },
205
+ "35": { title: "Dark Cave", content: `<p>The cave smells of salt and decay. A figure huddles near a sputtering fire.</p>`, options: [ { text: "Approach the figure cautiously", next: 350 }, { text: "Try to sneak past", check: { "stat": "dexterity", "dc": 13, "onFailure": 351 }, "next": 352 } ], illustration: "dark-cave-sputtering-fire-huddled-figure", onEnter: [{ action: "meetNpc", npcId: "cliff_hermit", setDisposition: "seen" }] },
206
  "40": { title: "Overgrown Shrine", content: `<p>Wildflowers grow thick around a small stone shrine...</p>`, options: [{ text: "Examine the carvings (Intelligence Check)", check:{stat:'intelligence', dc:11, onFailure: 401}, next: 400 }, { text: "Leave it be", next: 4 } ], illustration: "overgrown-stone-shrine-wildflowers-close" },
207
  "41": { title: "Rocky Badlands", content: `<p>The green hills give way to cracked earth...</p>`, options: [{ text: "Scout ahead (End)", next: 99 } ], illustration: "rocky-badlands-cracked-earth-harsh-sun" },
208
+ "70": { title: "Statue Examined", content: `<p>The statue depicts a forgotten nature deity. You notice a small compartment at its base.</p>`, options: [{text:"Try to open compartment (Strength Check?)", check:{stat:'strength', dc: 10, onFailure: 71}, next: 700}], illustration:"close-up-mossy-statue-compartment", reward:{xp:10}},
209
  "71": { title: "Statue Unyielding", content: `<p>You examine the statue but learn little. It remains an imposing enigma.</p>`, options: [{text:"Press onward", next: 72}], illustration:"forest-clearing-mossy-statue-weathered-stone-shrug"},
210
  "72": { title: "Deeper Woods", content: `<p>Leaving the statue behind, you push further into the increasingly dense woods.</p>`, options: [{text:"Continue", next: 14}], illustration:"dense-forest-undergrowth-shadows" },
211
  "73": { title: "Offering Made", content: `<p>You leave a small token. For a moment, you think you feel a sense of ancient approval.</p>`, options: [{text:"Press onward", next: 72}], illustration:"offering-at-base-of-mossy-statue"},
212
+ "80": { title: "Bridge Crossed", content: `<p>You make it across the swaying bridge, your heart pounding.</p>`, options: [{text:"Continue on the trail", next: 16}], illustration:"view-from-end-of-rope-bridge-forest", reward:{xp:15}},
213
  "81": { title: "Bridge Collapse!", content: `<p>A frayed rope snaps! You plummet into the shallow ravine below, losing 8 HP!</p>`, options: [{text:"Climb out and find another way", next: 82}], illustration:"character-falling-from-broken-rope-bridge", hpLoss:8},
214
+ "82": { title: "Ravine Detour", content: `<p>You find a place where the ravine narrows and manage to climb down and back up the other side.</p>`, options: [{text:"Continue on the trail", next: 16}], illustration:"climbing-out-of-shallow-ravine-forest", reward:{xp:5}},
215
  "101": { title:"Failed Dodge", content:"<p>You try to dodge, but a goblin spear trips you! You take 3 damage.</p>", options:[{text:"Get up and Fight!", next: 12}], illustration:"character-tripped-by-goblin-spear", hpLoss: 3},
216
+ "190": { title: "Over the Rocks", content:"<p>With considerable effort, you clamber over the rockslide.</p>`, options: [{text:"Continue up the path", next: 22}], illustration:"character-climbing-over-boulders", reward: {xp:35} },
217
  "191": { title: "Climb Fails", content:"<p>The boulders are too unstable. You cannot climb them safely.</p>`, options: [{text:"Search for another way around", next: 192}], illustration:"character-slipping-on-rockslide-boulders"},
218
  "192": { title: "Detour Found", content:"<p>After some searching, you find a rough path leading around the rockslide.</p>`, options: [{text:"Continue up the path", next: 22}], illustration:"rough-detour-path-around-rockslide"},
219
  "21": { title: "Western Ridge", content:"<p>The ridge path is narrow and exposed, with strong winds...</p>`, options: [{text:"Proceed carefully (Dexterity Check)", check:{stat:'dexterity', dc: 14, onFailure: 211}, next: 22 } ], illustration:"narrow-windy-mountain-ridge-path" },
220
  "22": { title: "Fortress Approach", content:"<p>You've navigated the treacherous paths and now stand near the outer walls...</p>`, options: [{text:"Look for an unguarded entrance (End of Demo)", next: 99}], illustration:"approaching-dark-fortress-walls-guards"},
221
  "211": {title:"Lost Balance", content:"<p>A strong gust sends you tumbling down a steep slope! (-10 HP)</p>", options:[{text:"Climb back up and find another way", next: 17}], illustration:"character-falling-off-windy-ridge", hpLoss: 10},
222
+ "350": { title: "Cave Dweller", content:"<p>'Who's there?' croaks the figure, revealing a wild-eyed hermit clutching a sharpened shell. 'State yer business!'</p>", options:[{text:"'I mean no harm, just exploring.' (Charisma Check?)", next: 353},{text:"Attack the hermit!", next: 354}], illustration:"cave-hermit-wild-eyes-sharpened-shell", onEnter: [{ action: "meetNpc", npcId: "cliff_hermit", setDisposition: "wary" }] }, // Explicitly met and wary
223
+ "351": { title: "Spotted!", content:"<p>Your clumsy attempt at stealth alerts the figure! 'Intruder!' the hermit shrieks, lunging with a sharpened shell.</p>", options:[{text:"Defend yourself!", next: 354}], illustration:"cave-hermit-lunging-attack-shadows"},
224
+ "352": { title: "Sneaked Past", content:"<p>You slip past the figure unnoticed and find the cave continues deeper.</p>", options:[{text:"Explore deeper", next: 99}], illustration:"sneaking-past-cave-hermit-fire", reward:{xp:20}},
225
+ "353": { title: "Uneasy Truce", content:"<p>The hermit eyes you suspiciously but lowers the shell slightly. 'Exploring, eh? Nothin' but trouble finds these caves. Be warned.' He doesn't seem hostile now, but certainly not friendly.</p>", options:[{text:"Ask about the caves", next: 99},{text:"Leave the cave", next: 3}], illustration:"cave-hermit-suspicious-lowered-shell", onEnter: [{ action: "meetNpc", npcId: "cliff_hermit", setDisposition: "neutral" }] }, // Updated disposition
226
+ "354": { title: "Hermit Defeated", content:"<p>You overcome the surprisingly fierce hermit. His meager possessions offer little of value.</p>", options:[{text:"Explore deeper", next: 99}], illustration:"defeated-cave-hermit-meager-belongings", reward:{xp:40}, onEnter: [{ action: "meetNpc", npcId: "cliff_hermit", setDisposition: "defeated" }] },
227
+ "400": {title:"Shrine Secrets", content:"<p>The carvings depict ancient rituals. You find a loose stone revealing a Healing Poultice!</p>`, options:[{text:"Take the poultice and leave", next:4, addItem:"Healing Poultice"}], illustration:"close-up-shrine-carvings-hidden-compartment", reward:{xp:20}},
228
+ "401": {title:"Mysterious Carvings", content:"<p>The carvings are worn and indecipherable.</p>`, options:[{text:"Leave the shrine", next:4}], illustration:"worn-stone-carvings-shrine"},
229
+ "700": {title:"Statue's Gift", content:"<p>The compartment clicks open, revealing a smooth, grey stone that feels strangely warm.</p>`, options:[{text:"Take the stone and press on", next: 72, addItem:"Warm Stone"}], illustration:"hand-holding-warm-grey-stone-statue-base", reward:{xp:30}},
230
 
231
  "99": { title: "Game Over / To Be Continued...", content: "<p>Your adventure ends here (for now).</p>", options: [{ text: "Restart", next: 1 }], illustration: "game-over-generic", gameOver: true }
232
  };
 
236
  currentPageId: 1,
237
  character: {
238
  name: "Hero", race: "Human", alignment: "Neutral Good", class: "Adventurer",
239
+ level: 1, xp: 0, xpToNextLevel: 100, availableStatPoints: 0,
240
  stats: { strength: 8, intelligence: 10, wisdom: 10, dexterity: 10, constitution: 10, charisma: 8, hp: 12, maxHp: 12 },
241
+ inventory: [],
242
+ knownNpcs: {} // Added to track NPC interactions
243
  }
244
  };
245
 
246
  // --- Game Logic Functions ---
247
  function startGame() {
248
+ const defaultChar = { name: "Hero", race: "Human", alignment: "Neutral Good", class: "Adventurer", level: 1, xp: 0, xpToNextLevel: 100, availableStatPoints: 0, stats: { strength: 8, intelligence: 10, wisdom: 10, dexterity: 10, constitution: 10, charisma: 8, hp: 12, maxHp: 12 }, inventory: [], knownNpcs: {} };
249
  gameState = { currentPageId: 1, character: { ...defaultChar } };
250
+ // TODO: Load from localStorage if exists
251
  recalculateMaxHp();
252
  gameState.character.stats.hp = gameState.character.stats.maxHp;
253
  renderPage(gameState.currentPageId);
 
259
  char.level++;
260
  char.xp -= char.xpToNextLevel;
261
  char.xpToNextLevel = Math.floor(char.xpToNextLevel * 1.5 + 50);
262
+ char.availableStatPoints += 1;
263
  recalculateMaxHp();
264
+ char.stats.hp = char.stats.maxHp;
265
  console.log(`LEVEL UP! Reached Level ${char.level}.`);
266
+ updateStatsDisplay();
 
267
  return true;
268
  }
269
 
270
  function recalculateMaxHp() {
271
  const char = gameState.character;
272
  const conModifier = Math.floor((char.stats.constitution - 10) / 2);
273
+ char.stats.maxHp = 8 + (char.level * Math.max(1, 2 + conModifier));
274
+ // Clamp current HP just in case it somehow exceeded new maxHP before recalc
275
+ char.stats.hp = Math.min(char.stats.hp, char.stats.maxHp);
276
+ }
277
+
278
+ // Process events that happen just by entering a page
279
+ function processPageEntryEvents(pageData) {
280
+ if (!pageData || !pageData.onEnter) return;
281
+
282
+ const char = gameState.character;
283
+ pageData.onEnter.forEach(event => {
284
+ if (event.action === "meetNpc") {
285
+ if (!npcs[event.npcId]) {
286
+ console.warn(`NPC not found in npcs data: ${event.npcId}`);
287
+ return;
288
+ }
289
+ const currentStatus = char.knownNpcs[event.npcId];
290
+ const newStatus = event.setDisposition || "met"; // Default to 'met'
291
+ // Update status only if it's new or different (or always override?) - let's override
292
+ if (currentStatus !== newStatus) {
293
+ char.knownNpcs[event.npcId] = newStatus;
294
+ console.log(`NPC Status Update: ${npcs[event.npcId]?.name} is now ${newStatus}`);
295
+ updateKnownNpcsDisplay(); // Update the UI
296
+ } else if (!currentStatus) { // First time meeting
297
+ char.knownNpcs[event.npcId] = newStatus;
298
+ console.log(`Met NPC: ${npcs[event.npcId]?.name} (${newStatus})`);
299
+ updateKnownNpcsDisplay();
300
+ }
301
+ }
302
+ // Add other onEnter actions here (e.g., random encounters, environment effects)
303
+ });
304
+ }
305
+
306
+ // Update function to handle choice effects and NPC disposition changes
307
+ function processChoiceEffect(effect) {
308
+ if (!effect) return;
309
+ const char = gameState.character;
310
+ let hpGained = 0;
311
+
312
+ if (effect.hpGain) {
313
+ const maxHeal = char.stats.maxHp - char.stats.hp;
314
+ const actualGain = Math.min(effect.hpGain, maxHeal);
315
+ if (actualGain > 0) {
316
+ char.stats.hp += actualGain;
317
+ hpGained = actualGain;
318
+ console.log(`Recovered ${actualGain} HP.`);
319
+ }
320
+ }
321
+ // Handle NPC disposition changes from choice effect
322
+ if (effect.setNpcDisposition) {
323
+ const npcId = effect.setNpcDisposition.npcId;
324
+ const status = effect.setNpcDisposition.status;
325
+ if (npcs[npcId] && status) {
326
+ if (char.knownNpcs[npcId] !== status) {
327
+ char.knownNpcs[npcId] = status;
328
+ console.log(`NPC Status Update via Choice: ${npcs[npcId].name} is now ${status}`);
329
+ updateKnownNpcsDisplay();
330
+ }
331
+ } else {
332
+ console.warn(`Invalid setNpcDisposition effect:`, effect.setNpcDisposition);
333
+ }
334
+ }
335
+ // Add other effects (e.g., addItem, statChange)
336
+
337
+ return { hpGained }; // Return results if needed for messages
338
  }
339
 
340
+
341
  function handleChoiceClick(choiceData) {
342
  const optionNextPageId = parseInt(choiceData.nextPage);
343
  const itemToAdd = choiceData.addItem;
 
347
  const check = choiceData.check;
348
  const effect = choiceData.effect;
349
 
350
+ if (isNaN(optionNextPageId) && !check && !effect) { console.error("Invalid choice data:", choiceData); return; }
351
+
352
+ // --- Apply direct choice effects FIRST ---
353
+ let effectResult = processChoiceEffect(effect);
354
+ if (effectResult?.hpGained > 0) {
355
+ rollResultMessage += `<p class="xp-gain">Rested and recovered ${effectResult.hpGained} HP.</p>`;
356
+ }
357
+ // If effect dictates next page, use it
358
+ if (effect && effect.setNextPage !== undefined) {
359
+ nextPageId = effect.setNextPage;
360
+ // If the effect was the *only* action (like resting), proceed directly to render
361
+ if (!check && !itemToAdd && isNaN(optionNextPageId)) { // Check if there was no original 'next' page
362
+ gameState.currentPageId = nextPageId;
363
+ renderPageInternal(nextPageId, gameData[nextPageId], rollResultMessage);
364
+ return;
365
+ }
366
+ // Otherwise, allow potential check/item add to override if needed after rest
367
+ }
368
+
369
 
370
  // --- Process Stat Check ---
371
  if (check) {
 
378
  console.log(`Check: ${check.stat} (DC ${dc}) | Roll: ${roll} + Mod: ${modifier} = ${totalResult}`);
379
 
380
  if (totalResult >= dc) { // Success
381
+ nextPageId = optionNextPageId; // Ensure success path is taken
382
  rollResultMessage += `<p class="roll-success"><em>Check Success! (${totalResult} vs DC ${dc})</em></p>`;
383
+ const marginBonus = Math.max(0, Math.floor(successMargin * 1.0));
384
+ const oddsBonus = Math.max(0, Math.floor(dc * 0.5));
385
  const checkBonusXp = marginBonus + oddsBonus;
386
  if (checkBonusXp > 0) { gainedXpThisTurn += checkBonusXp; rollResultMessage += `<p class="xp-gain">+${checkBonusXp} bonus XP!</p>`; console.log(`Check bonus XP: ${checkBonusXp}`); }
387
  } else { // Failure
 
401
  const nextPageData = gameData[nextPageId];
402
 
403
  if (nextPageData) {
404
+ // Process entry events for the *new* page
405
+ processPageEntryEvents(nextPageData); // Process NPC meets etc.
406
+
407
+ if (nextPageData.hpLoss) { gameState.character.stats.hp -= nextPageData.hpLoss; console.log(`Lost ${nextPageData.hpLoss} HP.`); }
 
408
  if (nextPageData.reward) {
409
  if (nextPageData.reward.xp) { gainedXpThisTurn += nextPageData.reward.xp; console.log(`Base reward: +${nextPageData.reward.xp} XP.`); }
410
+ if (nextPageData.reward.statIncrease) { const stat = nextPageData.reward.statIncrease.stat; const amount = nextPageData.reward.statIncrease.amount; if (gameState.character.stats.hasOwnProperty(stat)) { gameState.character.stats[stat] += amount; console.log(`Stat ${stat} increased by ${amount}.`); recalculateMaxHp(); } }
411
  if(nextPageData.reward.addItem && !gameState.character.inventory.includes(nextPageData.reward.addItem)){ gameState.character.inventory.push(nextPageData.reward.addItem); console.log(`Found item: ${nextPageData.reward.addItem}`); }
412
  }
413
 
414
  if (gainedXpThisTurn > 0) {
415
  gameState.character.xp += gainedXpThisTurn;
416
  console.log(`Total XP Gained: ${gainedXpThisTurn}. Current XP: ${gameState.character.xp}`);
417
+ if (!rollResultMessage.includes("bonus XP")) { rollResultMessage += `<p class="xp-gain">You gained ${gainedXpThisTurn} XP.</p>`; }
 
 
418
  }
419
 
420
  let leveledUp = false;
421
+ while (gameState.character.xp >= gameState.character.xpToNextLevel) { if (levelUpCharacter()) { leveledUp = true; } else { break; } }
 
 
422
  if (leveledUp) { rollResultMessage += `<p class="level-up">LEVEL UP! You reached Level ${gameState.character.level}!</p>`; }
423
 
424
+ recalculateMaxHp();
425
+ gameState.character.stats.hp = Math.min(gameState.character.stats.hp, gameState.character.stats.maxHp);
426
  gameState.character.stats.hp = Math.max(0, gameState.character.stats.hp);
427
 
428
+ if (gameState.character.stats.hp <= 0 && !(nextPageData.gameOver)) { console.log("Player died!"); nextPageId = 99; renderPageInternal(99, gameData[99], rollResultMessage + "<p class='roll-failure'><em>Your wounds overwhelm you...</em></p>"); return; }
 
 
 
 
429
 
430
  } else { // Invalid next page ID
431
  console.error(`Data for page ${nextPageId} not found!`);
 
436
 
437
  function renderPageInternal(pageId, pageData, message = "") {
438
  if (!pageData) { console.error(`Render Error: No data for page ${pageId}`); return; }
439
+
440
+ // Process entry events *before* rendering content that might depend on them
441
+ processPageEntryEvents(pageData);
442
+
443
  storyTitleElement.textContent = pageData.title || "Untitled Page";
444
  storyContentElement.innerHTML = message + (pageData.content || "<p>...</p>");
445
+ updateStatsDisplay(); updateInventoryDisplay(); updateKnownNpcsDisplay(); // Update all UI parts
446
+
447
  choicesElement.innerHTML = '';
448
  if (pageData.options && pageData.options.length > 0) {
449
  pageData.options.forEach(option => {
450
  const button = document.createElement('button'); button.classList.add('choice-button'); button.textContent = option.text; let requirementMet = true;
451
+ // Add requirement checks for items OR knownNpcs status here later
452
  if (option.requireItem && !gameState.character.inventory.includes(option.requireItem)) { requirementMet = false; button.title = `Requires: ${option.requireItem}`; button.disabled = true; }
453
+ // Example NPC check:
454
+ // if (option.requireNpcStatus && gameState.character.knownNpcs[option.requireNpcStatus.npcId] !== option.requireNpcStatus.status) { requirementMet = false; button.title = `Requires: ${npcs[option.requireNpcStatus.npcId]?.name} to be ${option.requireNpcStatus.status}`; button.disabled = true; }
455
+
456
  if (requirementMet) { const choiceData = { nextPage: option.next, addItem: option.addItem, check: option.check, effect: option.effect }; button.onclick = () => handleChoiceClick(choiceData); } else { button.classList.add('disabled'); } choicesElement.appendChild(button); });
457
  } else { const button = document.createElement('button'); button.classList.add('choice-button'); button.textContent = pageData.gameOver ? "Restart Adventure" : "The End"; button.onclick = () => handleChoiceClick({ nextPage: pageData.gameOver ? 1 : 99 }); choicesElement.appendChild(button); if (!pageData.gameOver) choicesElement.insertAdjacentHTML('afterbegin', '<p><i>The path ends here.</i></p>'); }
458
  updateScene(pageData.illustration || 'default', pageData.sceneParams);
 
460
 
461
  function renderPage(pageId) { renderPageInternal(pageId, gameData[pageId]); }
462
 
463
+ function updateStatsDisplay() { const char=gameState.character; statsElement.innerHTML = `<strong>Stats:</strong> <span>Lvl: ${char.level}</span> <span>XP: ${char.xp}/${char.xpToNextLevel}</span> <span>HP: ${char.stats.hp}/${char.stats.maxHp}</span> <span title="Strength">Str: ${char.stats.strength}</span> <span title="Intelligence">Int: ${char.stats.intelligence}</span> <span title="Wisdom">Wis: ${char.stats.wisdom}</span> <span title="Dexterity">Dex: ${char.stats.dexterity}</span> <span title="Constitution">Con: ${char.stats.constitution}</span> <span title="Charisma">Cha: ${char.stats.charisma}</span>`; }
464
  function updateInventoryDisplay() { let h='<strong>Inventory:</strong> '; if(gameState.character.inventory.length === 0){ h+='<em>Empty</em>'; } else { gameState.character.inventory.forEach(i=>{ const d=itemsData[i]||{type:'unknown',description:'???'}; const c=`item-${d.type||'unknown'}`; h+=`<span class="${c}" title="${d.description}">${i}</span>`; }); } inventoryElement.innerHTML = h; }
465
 
466
+ // New function to display known NPCs
467
+ function updateKnownNpcsDisplay() {
468
+ let npcHtml = '<strong>Known NPCs:</strong> ';
469
+ const known = gameState.character.knownNpcs;
470
+ const npcIds = Object.keys(known);
471
+
472
+ if (npcIds.length === 0) {
473
+ npcHtml += '<em>None</em>';
474
+ } else {
475
+ npcIds.forEach(npcId => {
476
+ const npcData = npcs[npcId] || { name: npcId }; // Fallback name
477
+ const status = known[npcId];
478
+ // Add classes based on status for potential styling
479
+ let statusClass = 'npc-met'; // Default class
480
+ if (status === 'allied' || status === 'helped') statusClass = 'npc-allied';
481
+ else if (status === 'hostile' || status === 'defeated') statusClass = 'npc-hostile';
482
+ else if (status === 'wary') statusClass = 'npc-wary';
483
+ else if (status === 'seen') statusClass = 'npc-seen'; // Just seen, not interacted
484
+
485
+ npcHtml += `<span class="${statusClass}" title="${npcData.description} (${status})">${npcData.name}</span>`;
486
+ });
487
+ }
488
+ knownNpcsElement.innerHTML = npcHtml;
489
+ }
490
+
491
+
492
  function updateScene(illustrationKey, sceneParams = {}) {
493
  if (currentAssemblyGroup) { scene.remove(currentAssemblyGroup); }
494
+ currentAssemblyGroup = null; let assemblyFunction = createDefaultAssembly; // Default
495
+ const keyRoot = illustrationKey.split('-')[0]; // Basic check
496
+
497
+ switch (keyRoot) { // Simplified routing based on first word
498
+ case 'city': case 'gates': assemblyFunction = createCityGatesAssembly; break;
499
  case 'weaponsmith': assemblyFunction = createWeaponsmithAssembly; break;
500
  case 'temple': assemblyFunction = createTempleAssembly; break;
501
+ case 'resistance': case 'meeting': assemblyFunction = createResistanceMeetingAssembly; break;
502
+ case 'forest': case 'shadowwood': case 'overgrown': case 'clearing': case 'trail': case 'stream': case 'log': case 'edge': case 'dense': assemblyFunction = createForestAssembly; break;
503
+ case 'road': case 'ambush': case 'goblins': assemblyFunction = createRoadAmbushAssembly; break;
504
+ case 'prisoner': case 'cell': assemblyFunction = createPrisonerCellAssembly; break;
505
+ case 'hills': case 'shrine': case 'overlook': assemblyFunction = createDefaultAssembly; break; // TODO: createHillsAssembly
506
+ case 'cliffs': case 'cove': case 'cave': case 'hermit': assemblyFunction = createDefaultAssembly; break; // TODO: createCliffsAssembly
507
+ case 'ruins': assemblyFunction = createDefaultAssembly; break; // TODO: createRuinsAssembly
508
+ case 'badlands': assemblyFunction = createDefaultAssembly; break; // TODO: createBadlandsAssembly
509
+ case 'fortress': case 'ridge': case 'rockslide': assemblyFunction = createDefaultAssembly; break; // TODO: createMountainAssembly
510
+ case 'game': assemblyFunction = createGameOverAssembly; break;
511
  case 'error': assemblyFunction = createErrorAssembly; break;
512
+ // Add specific full keys if needed override root check
513
+ case 'crossroads-signpost-sunny': assemblyFunction = createDefaultAssembly; break; // TODO: createCrossroadsAssembly
514
  }
515
+ // console.log(`Routing '${illustrationKey}' (root: '${keyRoot}') to ${assemblyFunction.name}`);
516
+
517
  try { currentAssemblyGroup = assemblyFunction(sceneParams); scene.add(currentAssemblyGroup); } catch (error) { console.error(`Error creating assembly for ${illustrationKey}:`, error); currentAssemblyGroup = createErrorAssembly(); scene.add(currentAssemblyGroup); }
518
  }
519