diff --git "a/index.html" "b/index.html" --- "a/index.html" +++ "b/index.html" @@ -3,11 +3,23 @@ - Choose Your Own Procedural Adventure + Choose Your Own Enhanced Procedural Adventure @@ -126,6 +174,7 @@
+
@@ -152,66 +201,88 @@ const storyContentElement = document.getElementById('story-content'); const choicesElement = document.getElementById('choices'); const statsElement = document.getElementById('stats-display'); + const effectsElement = document.getElementById('effects-display'); const inventoryElement = document.getElementById('inventory-display'); - let scene, camera, renderer; + let scene, camera, renderer, clock; let currentAssemblyGroup = null; - - // Materials - const stoneMaterial = new THREE.MeshStandardMaterial({ color: 0x888888, roughness: 0.8, metalness: 0.1 }); - const woodMaterial = new THREE.MeshStandardMaterial({ color: 0x8B4513, roughness: 0.7, metalness: 0 }); - const darkWoodMaterial = new THREE.MeshStandardMaterial({ color: 0x5C3D20, roughness: 0.7, metalness: 0 }); - const leafMaterial = new THREE.MeshStandardMaterial({ color: 0x2E8B57, roughness: 0.6, metalness: 0 }); - const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x556B2F, roughness: 0.9, metalness: 0 }); - const metalMaterial = new THREE.MeshStandardMaterial({ color: 0xaaaaaa, metalness: 0.8, roughness: 0.3 }); - const templeMaterial = new THREE.MeshStandardMaterial({ color: 0xA99B78, roughness: 0.7, metalness: 0.1 }); - const errorMaterial = new THREE.MeshStandardMaterial({ color: 0xffa500, roughness: 0.5 }); - const gameOverMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000, roughness: 0.5 }); + let currentLights = []; + let currentFog = null; + + const stoneMaterial = new THREE.MeshStandardMaterial({ color: 0x777788, roughness: 0.85, metalness: 0.1 }); + const woodMaterial = new THREE.MeshStandardMaterial({ color: 0x9F6633, roughness: 0.75, metalness: 0 }); + const darkWoodMaterial = new THREE.MeshStandardMaterial({ color: 0x6F4E2D, roughness: 0.7, metalness: 0 }); + const leafMaterial = new THREE.MeshStandardMaterial({ color: 0x3E9B4E, roughness: 0.6, metalness: 0, side: THREE.DoubleSide }); + const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x556B2F, roughness: 0.95, metalness: 0 }); + const metalMaterial = new THREE.MeshStandardMaterial({ color: 0xaaaaaa, metalness: 0.85, roughness: 0.35 }); + const templeMaterial = new THREE.MeshStandardMaterial({ color: 0xB9AB88, roughness: 0.7, metalness: 0.15 }); + const errorMaterial = new THREE.MeshStandardMaterial({ color: 0xffa500, roughness: 0.5, emissive: 0x331a00 }); + const gameOverMaterial = new THREE.MeshStandardMaterial({ color: 0xcc0000, roughness: 0.6, metalness: 0.2, emissive: 0x220000 }); const dirtMaterial = new THREE.MeshStandardMaterial({ color: 0x8B5E3C, roughness: 0.9 }); - const grassMaterial = new THREE.MeshStandardMaterial({ color: 0x3CB371, roughness: 0.8 }); - const oceanMaterial = new THREE.MeshStandardMaterial({ color: 0x1E90FF, roughness: 0.5, metalness: 0.2 }); + const grassMaterial = new THREE.MeshStandardMaterial({ color: 0x4CB781, roughness: 0.85 }); + const oceanMaterial = new THREE.MeshStandardMaterial({ color: 0x3E90CF, roughness: 0.4, metalness: 0.3, transparent: true, opacity: 0.8 }); const sandMaterial = new THREE.MeshStandardMaterial({ color: 0xF4A460, roughness: 0.9 }); - const wetStoneMaterial = new THREE.MeshStandardMaterial({ color: 0x2F4F4F, roughness: 0.7 }); - const glowMaterial = new THREE.MeshStandardMaterial({ color: 0x00FFAA, emissive: 0x00FFAA, emissiveIntensity: 0.5 }); + const wetStoneMaterial = new THREE.MeshStandardMaterial({ color: 0x3F5F5F, roughness: 0.6, metalness: 0.1 }); + const glowMaterial = new THREE.MeshStandardMaterial({ color: 0x33FFBB, emissive: 0x33FFBB, emissiveIntensity: 0.6 }); + const vineMaterial = new THREE.MeshStandardMaterial({ color: 0x448844, roughness: 0.8 }); + const goblinSkinMaterial = new THREE.MeshStandardMaterial({ color: 0x6B8E23, roughness: 0.7 }); + const mossMaterial = new THREE.MeshStandardMaterial({ color: 0x556B2F, roughness: 0.9 }); function initThreeJS() { if (!sceneContainer) { console.error("Scene container not found!"); return; } scene = new THREE.Scene(); - scene.background = new THREE.Color(0x222222); + scene.background = new THREE.Color(0x1a1a1a); + clock = new THREE.Clock(); + const width = sceneContainer.clientWidth; const height = sceneContainer.clientHeight; - camera = new THREE.PerspectiveCamera(75, (width / height) || 1, 0.1, 1000); - camera.position.set(0, 2.5, 7); + camera = new THREE.PerspectiveCamera(60, (width / height) || 1, 0.1, 1000); + camera.position.set(0, 3, 8); camera.lookAt(0, 0.5, 0); - renderer = new THREE.WebGLRenderer({ antialias: true }); + + renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); renderer.setSize(width || 400, height || 300); renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; + renderer.toneMapping = THREE.ACESFilmicToneMapping; + renderer.outputColorSpace = THREE.SRGBColorSpace; + sceneContainer.appendChild(renderer.domElement); - const ambientLight = new THREE.AmbientLight(0xffffff, 0.5); + + const ambientLight = new THREE.AmbientLight(0xffffff, 0.2); scene.add(ambientLight); + currentLights.push(ambientLight); + window.addEventListener('resize', onWindowResize, false); setTimeout(onWindowResize, 100); animate(); } function onWindowResize() { - if (!renderer || !camera || !sceneContainer) return; - const width = sceneContainer.clientWidth; - const height = sceneContainer.clientHeight; - if (width > 0 && height > 0) { - camera.aspect = width / height; - camera.updateProjectionMatrix(); - renderer.setSize(width, height); - } + if (!renderer || !camera || !sceneContainer) return; + const width = sceneContainer.clientWidth; + const height = sceneContainer.clientHeight; + if (width > 0 && height > 0) { + camera.aspect = width / height; + camera.updateProjectionMatrix(); + renderer.setSize(width, height); + } } function animate() { requestAnimationFrame(animate); - const time = performance.now() * 0.001; + const delta = clock.getDelta(); + const time = clock.getElapsedTime(); + scene.traverse(obj => { - if (obj.userData.update) obj.userData.update(time); + if (obj.userData.update) obj.userData.update(time, delta); }); + + if (currentFog && currentFog.density !== undefined) { + const baseDensity = currentFog.userData.baseDensity || currentFog.density; + currentFog.density = baseDensity + Math.sin(time * 0.3) * baseDensity * 0.05; + } + if (renderer && scene && camera) { renderer.render(scene, camera); } @@ -229,334 +300,622 @@ function createGroundPlane(material = groundMaterial, size = 20) { const groundGeo = new THREE.PlaneGeometry(size, size); const ground = new THREE.Mesh(groundGeo, material); - ground.rotation.x = -Math.PI / 2; ground.position.y = -0.05; + ground.rotation.x = -Math.PI / 2; ground.position.y = -0.01; ground.receiveShadow = true; ground.castShadow = false; return ground; } - // Procedural Generation Functions - 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; - } + function createLSystemInspiredTree(position = { x: 0, y: 0, z: 0 }, baseHeight = 3, baseRadius = 0.2, iterations = 2, branchFactor = 3) { + const treeGroup = new THREE.Group(); + treeGroup.position.copy(position); + + const trunkGeo = new THREE.CylinderGeometry(baseRadius * 0.7, baseRadius, baseHeight, 8); + const trunk = createMesh(trunkGeo, woodMaterial, { x: 0, y: baseHeight / 2, z: 0 }); + treeGroup.add(trunk); + + function addBranches(parent, currentHeight, currentRadius, currentIteration) { + if (currentIteration <= 0) { + const leafSize = baseHeight * 0.3 * (Math.random() * 0.5 + 0.7); + const leafGeo = new THREE.SphereGeometry(leafSize, 8, 6); + const leaves = createMesh(leafGeo, leafMaterial, { x: 0, y: currentHeight + leafSize * 0.5, z: 0 }); + leaves.scale.y = Math.random() * 0.5 + 0.8; + parent.add(leaves); + return; + } - 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; - } + for (let i = 0; i < branchFactor; i++) { + const branchLength = baseHeight * 0.6 * (0.8 / currentIteration) * (Math.random() * 0.4 + 0.8); + const branchRadius = currentRadius * 0.6 * (Math.random() * 0.3 + 0.7); + const branchGeo = new THREE.CylinderGeometry(branchRadius * 0.7, branchRadius, branchLength, 6); - 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; - } + const branch = new THREE.Group(); + const branchMesh = createMesh(branchGeo, woodMaterial, { x: 0, y: branchLength / 2, z: 0 }); + branch.add(branchMesh); - 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; - } + branch.position.y = currentHeight; - 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; - } + const angleX = (Math.random() - 0.3) * Math.PI / 3; + const angleZ = (Math.random() - 0.5) * Math.PI / 3; + const angleY = Math.random() * Math.PI * 2; + branch.rotation.set(angleX, angleY, angleZ); - function createForestAssembly(tc=10, a=10) { - const group = new THREE.Group(); - 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; - }; - for(let i=0; i1.0) group.add(cT(x,z)); + parent.add(branch); + addBranches(branchMesh, branchLength, branchRadius, currentIteration - 1); + } } - group.add(createGroundPlane(groundMaterial, a*1.1)); - return group; - } - function createRoadAmbushAssembly() { - const group = new THREE.Group(); - const a=12; - const fg = createForestAssembly(8, a); - 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; + addBranches(trunk, baseHeight, baseRadius, iterations); + return treeGroup; } - function createForestEdgeAssembly() { + function createForestAssembly(treeCount = 15, areaSize = 15) { const group = new THREE.Group(); - const a=15; - const fg = createForestAssembly(15, a); - 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; - } - - 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 0.3 ? groundMaterial : grassMaterial; + group.add(createGroundPlane(forestFloorMat, areaSize * 1.2)); + + for (let i = 0; i < treeCount; i++) { + const x = (Math.random() - 0.5) * areaSize; + const z = (Math.random() - 0.5) * areaSize; + if (Math.sqrt(x * x + z * z) > areaSize * 0.1) { + const baseHeight = Math.random() * 2 + 2.5; + const baseRadius = Math.random() * 0.15 + 0.15; + const iterations = Math.random() > 0.5 ? 2 : 3; + const tree = createLSystemInspiredTree({ x, y: 0, z }, baseHeight, baseRadius, iterations); + tree.rotation.y = Math.random() * Math.PI * 2; + group.add(tree); + } } + const bushGeo = new THREE.IcosahedronGeometry(0.4 + Math.random() * 0.3, 0); + for (let i = 0; i < treeCount * 0.7; i++) { + const bush = createMesh(bushGeo, leafMaterial, { x: (Math.random() - 0.5) * areaSize, y: 0.3, z: (Math.random() - 0.5) * areaSize }); + bush.scale.set(Math.random()*0.5+0.8, Math.random()*0.5+0.8, Math.random()*0.5+0.8); + group.add(bush); + } + const rockGeo = new THREE.IcosahedronGeometry(0.3 + Math.random() * 0.4, 0); + for (let i = 0; i < treeCount * 0.3; i++) { + const rock = createMesh(rockGeo, stoneMaterial, { x: (Math.random() - 0.5) * areaSize, y: 0.2, z: (Math.random() - 0.5) * areaSize }); + rock.rotation.set(Math.random()*0.5, Math.random()*Math.PI*2, Math.random()*0.5); + group.add(rock); + } return group; } - 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; - } + function createDefaultAssembly() { + const group = new THREE.Group(); + const sphereGeo = new THREE.SphereGeometry(0.8, 16, 12); + group.add(createMesh(sphereGeo, stoneMaterial, { x: 0, y: 0.8, z: 0 })); + group.add(createGroundPlane(dirtMaterial, 10)); + return group; + } - function createErrorAssembly() { + function createCityGatesAssembly() { 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; - } + const gh=4.5, gw=1.8, gd=1.0, ah=1.2, aw=3.5; + const pillarMat = stoneMaterial.clone(); + pillarMat.color.lerp(new THREE.Color(0x666677), 0.2); - function createCrossroadsAssembly() { - const group = new THREE.Group(); - group.add(createGroundPlane(dirtMaterial, 30)); - const poleGeo = new THREE.CylinderGeometry(0.1, 0.1, 3, 8); - group.add(createMesh(poleGeo, woodMaterial, { y: 1.5 })); - const signGeo = new THREE.BoxGeometry(1.5, 0.3, 0.05); - group.add(createMesh(signGeo, woodMaterial, { y: 2.5, z: 0.2 }, { y: Math.PI / 4 })); - group.add(createMesh(signGeo, woodMaterial, { y: 2.5, z: -0.2 }, { y: -Math.PI / 4 })); - const grassGeo = new THREE.ConeGeometry(0.2, 0.5, 6); - for (let i = 0; i < 20; i++) { - const x = (Math.random() - 0.5) * 15; - const z = (Math.random() - 0.5) * 15; - if (Math.abs(x) > 2 || Math.abs(z) > 2) { - group.add(createMesh(grassGeo, grassMaterial, { x, y: 0.25, z }, { y: Math.random() * Math.PI })); - } - } - const rockGeo = new THREE.SphereGeometry(0.3, 6, 6); - for (let i = 0; i < 10; i++) { - group.add(createMesh(rockGeo, stoneMaterial, { x: (Math.random() - 0.5) * 10, y: 0.15, z: (Math.random() - 0.5) * 10 }, { y: Math.random() * Math.PI })); - } - return group; - } + const tlGeo = new THREE.BoxGeometry(gw, gh, gd); + group.add(createMesh(tlGeo, pillarMat, { x:-(aw/2+gw/2), y:gh/2, z:0 })); + const trGeo = new THREE.BoxGeometry(gw, gh, gd); + group.add(createMesh(trGeo, pillarMat, { x:(aw/2+gw/2), y:gh/2, z:0 })); - function createRollingHillsAssembly() { - const group = new THREE.Group(); - const hillGeo = new THREE.PlaneGeometry(50, 50, 10, 10); - const hillMat = grassMaterial.clone(); - const hill = new THREE.Mesh(hillGeo, hillMat); - hill.rotation.x = -Math.PI / 2; - hill.receiveShadow = true; - for (let i = 0; i < hillGeo.attributes.position.count; i++) { - const x = hillGeo.attributes.position.getX(i); - const z = hillGeo.attributes.position.getZ(i); - hillGeo.attributes.position.setY(i, Math.sin(x * 0.2 + z * 0.2) * 2); + const archSegments = 10; + const archPoints = []; + for (let i = 0; i <= archSegments; i++) { + const angle = Math.PI * (i / archSegments); + archPoints.push(new THREE.Vector2(Math.cos(angle) * aw / 2, Math.sin(angle) * ah)); } - hillGeo.computeVertexNormals(); - group.add(hill); - const shepherdGeo = new THREE.CylinderGeometry(0.1, 0.1, 1, 8); - group.add(createMesh(shepherdGeo, darkWoodMaterial, { x: 10, y: 2, z: -15 })); - const grassGeo = new THREE.ConeGeometry(0.3, 0.7, 6); - for (let i = 0; i < 50; i++) { - group.add(createMesh(grassGeo, grassMaterial, { x: (Math.random() - 0.5) * 40, y: 0.35, z: (Math.random() - 0.5) * 40 }, { y: Math.random() * Math.PI })); + const archShape = new THREE.Shape(archPoints); + const extrudeSettings = { depth: gd, bevelEnabled: false }; + const aGeo = new THREE.ExtrudeGeometry(archShape, extrudeSettings); + const archMesh = createMesh(aGeo, stoneMaterial, { x:0, y:gh-ah, z:-gd/2}, {y: Math.PI}); + archMesh.position.y = gh - ah; + archMesh.position.x = -aw/2; + archMesh.rotation.y = 0; + group.add(archMesh); + + const cs=0.45; + 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.8, y:gh+cs/2, z:0 })); + group.add(createMesh(cg.clone(), stoneMaterial, { x:(aw/2+gw/2)+i*cs*0.8, y:gh+cs/2, z:0 })); } + group.add(createMesh(cg.clone(), stoneMaterial, { x:0, y:gh+ah-cs*0.2, z:0 })); + group.add(createGroundPlane(stoneMaterial, 15)); return group; } - function createCoastalCliffsAssembly() { + function createTempleAssembly() { const group = new THREE.Group(); - const cliffGeo = new THREE.BoxGeometry(10, 5, 10); - group.add(createMesh(cliffGeo, stoneMaterial, { y: 2.5 })); - const pathGeo = new THREE.PlaneGeometry(1, 10); - const path = createMesh(pathGeo, dirtMaterial, { x: -2, y: 2, z: 0 }, { x: -Math.PI / 2, z: -Math.PI / 4 }); - group.add(path); - const oceanGeo = new THREE.PlaneGeometry(100, 100); - const ocean = createMesh(oceanGeo, oceanMaterial, { y: -2 }, { x: -Math.PI / 2 }); - ocean.receiveShadow = false; - ocean.userData.update = (time) => { - ocean.position.y = -2 + Math.sin(time * 0.5) * 0.1; - }; - group.add(ocean); - return group; - } + const bs=6, bsh=0.6, ch=3.5, cr=0.3, rh=0.7; + const baseMat = templeMaterial.clone(); + baseMat.color.lerp(new THREE.Color(0xffffff), 0.1); - function createForestEntranceAssembly() { - const group = createForestAssembly(20, 12); - const rootGeo = new THREE.TorusGeometry(0.5, 0.1, 8, 16); - for (let i = 0; i < 10; i++) { - group.add(createMesh(rootGeo, woodMaterial, { x: (Math.random() - 0.5) * 8, y: 0.1, z: (Math.random() - 0.5) * 8 }, { x: Math.PI / 2 })); - } - return group; - } + const bGeo = new THREE.CylinderGeometry(bs, bs, bsh, 32); + group.add(createMesh(bGeo, baseMat, { x:0, y:bsh/2, z:0 })); - function createOvergrownPathAssembly() { - const group = new THREE.Group(); - group.add(createGroundPlane(dirtMaterial, 15)); - const forest = createForestAssembly(15, 10); - group.add(forest); - const fungiGeo = new THREE.SphereGeometry(0.1, 8, 8); - for (let i = 0; i < 30; i++) { - group.add(createMesh(fungiGeo, glowMaterial, { x: (Math.random() - 0.5) * 8, y: 0.1, z: (Math.random() - 0.5) * 8 })); - } - const vineGeo = new THREE.CylinderGeometry(0.05, 0.05, 2, 8); - for (let i = 0; i < 10; i++) { - group.add(createMesh(vineGeo, leafMaterial, { x: (Math.random() - 0.5) * 6, y: 2, z: (Math.random() - 0.5) * 6 }, { z: Math.random() * Math.PI })); + const cGeo = new THREE.CylinderGeometry(cr, cr, ch, 12); + const numCols = 8; + for(let i=0; i 0.4) { + const stalactite = createMesh(coneGeo.clone(), wetStoneMaterial, {x, y: caveHeight * 0.8 + Math.random() * 0.5, z}); + stalactite.rotation.x = Math.PI; + group.add(stalactite); + } + if (Math.random() > 0.4) { + const stalagmite = createMesh(coneGeo.clone(), wetStoneMaterial, {x, y: 0, z}); + const raycaster = new THREE.Raycaster(new THREE.Vector3(x, 5, z), new THREE.Vector3(0, -1, 0)); + const intersects = raycaster.intersectObject(floor); + if (intersects.length > 0) { + stalagmite.position.y = intersects[0].point.y + (0.5 + Math.random() * 1.5)/2; + } + group.add(stalagmite); + } } - return group; - } - function createGoblinAmbushAssembly() { - const group = createOvergrownPathAssembly(); - const bodyGeo = new THREE.CylinderGeometry(0.3, 0.3, 1, 8); - const headGeo = new THREE.SphereGeometry(0.2, 8, 8); - const goblinMat = new THREE.MeshStandardMaterial({ color: 0x556B2F }); - for (let i = -1; i <= 1; i += 2) { - const goblin = new THREE.Group(); - goblin.add(createMesh(bodyGeo, goblinMat, { y: 0.5 })); - goblin.add(createMesh(headGeo, goblinMat, { y: 1.2 })); - const spearGeo = new THREE.CylinderGeometry(0.05, 0.05, 2, 8); - goblin.add(createMesh(spearGeo, woodMaterial, { x: 0.3, y: 1, z: 0 }, { z: Math.PI / 4 })); - goblin.position.set(i * 2, 0, 2); - group.add(goblin); + const dripGeo = new THREE.SphereGeometry(0.03, 6, 6); + const dripMat = oceanMaterial.clone(); + dripMat.opacity = 0.6; + for (let i = 0; i < 5; i++) { + const startX = (Math.random() - 0.5) * caveRadius; + const startZ = (Math.random() - 0.5) * caveRadius; + const startY = caveHeight * 0.8 + Math.random() * 0.5; + const drip = createMesh(dripGeo, dripMat, { x: startX, y: startY, z: startZ }); + drip.castShadow = false; + drip.userData.startY = startY; + drip.userData.speed = Math.random() * 2 + 2; + drip.userData.update = (time, delta) => { + drip.position.y -= drip.userData.speed * delta; + if (drip.position.y < 0) { + drip.position.y = drip.userData.startY; + drip.position.x = startX + (Math.random()-0.5)*0.1; + drip.position.z = startZ + (Math.random()-0.5)*0.1; + } + }; + group.add(drip); } + + const flickerLight = new THREE.PointLight(0xffaa55, 3, 8, 1); + flickerLight.position.set(0, 1.5, 0); + flickerLight.castShadow = true; + flickerLight.shadow.mapSize.width = 512; + flickerLight.shadow.mapSize.height = 512; + flickerLight.userData.baseIntensity = 3; + flickerLight.userData.update = (time) => { + flickerLight.intensity = flickerLight.userData.baseIntensity * (0.7 + Math.random() * 0.6); + flickerLight.position.x = 0 + (Math.random()-0.5)*0.1; + flickerLight.position.z = 0 + (Math.random()-0.5)*0.1; + }; + group.add(flickerLight); return group; } - function createHiddenCoveAssembly() { + function createOvergrownPathAssembly() { const group = new THREE.Group(); - group.add(createGroundPlane(sandMaterial, 15)); - const caveGeo = new THREE.BoxGeometry(3, 2, 3); - group.add(createMesh(caveGeo, stoneMaterial, { z: -5, y: 1 })); - const rockGeo = new THREE.SphereGeometry(0.5, 6, 6); + const areaSize = 15; + group.add(createGroundPlane(dirtMaterial, areaSize)); + + for (let i = 0; i < 25; i++) { + const edgeDist = areaSize * 0.45; + const angle = Math.random() * Math.PI * 2; + const radius = edgeDist + Math.random() * (areaSize*0.2); + const x = Math.cos(angle) * radius; + const z = Math.sin(angle) * radius; + const baseHeight = Math.random() * 2 + 2; + const baseRadius = Math.random() * 0.1 + 0.1; + const tree = createLSystemInspiredTree({ x, y: 0, z }, baseHeight, baseRadius, 2); + tree.rotation.y = Math.random() * Math.PI * 2; + group.add(tree); + } + + const fungiGeo = new THREE.SphereGeometry(0.05 + Math.random()*0.05, 6, 5); for (let i = 0; i < 15; i++) { - group.add(createMesh(rockGeo, stoneMaterial, { x: (Math.random() - 0.5) * 10, y: 0.25, z: (Math.random() - 0.5) * 10 })); + const clusterX = (Math.random() - 0.5) * areaSize * 0.6; + const clusterZ = (Math.random() - 0.5) * areaSize * 0.6; + const clusterYBase = 0.1; + for (let j = 0; j < 5 + Math.random()*5; j++) { + const fungi = createMesh(fungiGeo, glowMaterial, { + x: clusterX + (Math.random() - 0.5) * 0.3, + y: clusterYBase + Math.random() * 0.1, + z: clusterZ + (Math.random() - 0.5) * 0.3 + }); + fungi.castShadow = false; + group.add(fungi); + } } - const seaweedGeo = new THREE.ConeGeometry(0.2, 1, 6); + + const vineGeo = new THREE.CylinderGeometry(0.03, 0.04, 1.5 + Math.random(), 5); for (let i = 0; i < 10; i++) { - group.add(createMesh(seaweedGeo, leafMaterial, { x: (Math.random() - 0.5) * 8, y: 0.5, z: (Math.random() - 0.5) * 8 })); + const x = (Math.random() - 0.5) * areaSize * 0.5; + const z = (Math.random() - 0.5) * areaSize * 0.5; + const y = 2.5 + Math.random(); + const vine = createMesh(vineGeo, vineMaterial, { x, y, z }, + { x: Math.random()*0.4 - 0.2, z: Math.random()*0.4 - 0.2 } + ); + group.add(vine); } return group; } - function createDarkCaveAssembly() { - const group = new THREE.Group(); - group.add(createGroundPlane(wetStoneMaterial, 10)); - const wallGeo = new THREE.CylinderGeometry(3, 3, 5, 12, 1, true); - const wall = createMesh(wallGeo, stoneMaterial, { y: 2.5 }, { x: Math.PI / 2 }); - wall.scale.set(1, 1, -1); - group.add(wall); - const dripGeo = new THREE.SphereGeometry(0.05, 8, 8); - for (let i = 0; i < 5; i++) { - const drip = createMesh(dripGeo, oceanMaterial, { x: (Math.random() - 0.5) * 2, y: 4, z: (Math.random() - 0.5) * 2 }); - drip.userData.update = (time) => { - drip.position.y -= 0.1; - if (drip.position.y < 0) drip.position.y = 4; - }; - group.add(drip); - } + function createClearingStatueAssembly() { + const group = new THREE.Group(); + const clearingSize = 12; + group.add(createGroundPlane(grassMaterial.clone().set({color: 0x6AAA6A}), clearingSize)); + + const baseGeo = new THREE.CylinderGeometry(0.6, 0.8, 0.4, 12); + const base = createMesh(baseGeo, stoneMaterial, {y: 0.2}); + group.add(base); + + const bodyGeo = new THREE.BoxGeometry(0.7, 1.5, 0.7); + const body = createMesh(bodyGeo, stoneMaterial, {y: 0.4 + 1.5/2}); + group.add(body); + + const headGeo = new THREE.SphereGeometry(0.4, 12, 8); + const head = createMesh(headGeo, stoneMaterial, {y: 0.4 + 1.5 + 0.4}); + group.add(head); + + const mossGeo = new THREE.SphereGeometry(0.1, 6, 4); + for (let i = 0; i < 25; i++) { + const targetMesh = Math.random() > 0.5 ? body : (Math.random() > 0.5 ? head : base); + const pos = new THREE.Vector3( + (Math.random() - 0.5) * (targetMesh.geometry.parameters.width || targetMesh.geometry.parameters.radiusTop || 0.5), + (Math.random() - 0.5) * targetMesh.geometry.parameters.height, + (Math.random() - 0.5) * (targetMesh.geometry.parameters.depth || targetMesh.geometry.parameters.radiusTop || 0.5) + ); + pos.multiplyScalar(0.9); + pos.add(targetMesh.position); + + const moss = createMesh(mossGeo, mossMaterial, pos); + moss.scale.setScalar(Math.random()*0.5 + 0.8); + group.add(moss); + } + + const leafGeo = new THREE.PlaneGeometry(0.15, 0.15); + for (let i = 0; i < 40; i++) { + const leaf = createMesh(leafGeo, leafMaterial, + { x: (Math.random() - 0.5) * clearingSize * 0.8, y: 0.01, z: (Math.random() - 0.5) * clearingSize * 0.8 }, + { x: -Math.PI / 2, z: Math.random() * Math.PI * 2 } + ); + leaf.receiveShadow = true; + group.add(leaf); + } + + return group; + } + + function createGoblinAmbushAssembly() { + const group = createOvergrownPathAssembly(); + + const createGoblin = (position) => { + const goblinGroup = new THREE.Group(); + goblinGroup.position.copy(position); + + const bodyHeight = 0.8; + const bodyRadius = 0.25; + const bodyGeo = new THREE.CapsuleGeometry(bodyRadius, bodyHeight - bodyRadius*2, 4, 8); + const body = createMesh(bodyGeo, goblinSkinMaterial, { y: bodyHeight / 2 + 0.1}); + goblinGroup.add(body); + + const headSize = 0.3; + const headGeo = new THREE.SphereGeometry(headSize, 10, 8); + const head = createMesh(headGeo, goblinSkinMaterial, { y: bodyHeight + headSize * 0.8 }); + goblinGroup.add(head); + + const limbGeo = new THREE.CylinderGeometry(0.05, 0.04, 0.6, 6); + const arm1 = createMesh(limbGeo, goblinSkinMaterial, {x:-bodyRadius*0.8, y: bodyHeight*0.7, z:0}, {z: Math.PI/4}); + const arm2 = createMesh(limbGeo, goblinSkinMaterial, {x:bodyRadius*0.8, y: bodyHeight*0.7, z:0}, {z: -Math.PI/4}); + goblinGroup.add(arm1); + goblinGroup.add(arm2); + + const spearLength = 1.5; + const spearGeo = new THREE.CylinderGeometry(0.03, 0.03, spearLength, 6); + const spear = createMesh(spearGeo, darkWoodMaterial, { x: 0.3, y: 0.6, z: 0.1 }, { z: Math.PI / 3, x: -0.2 }); + goblinGroup.add(spear); + + const tipGeo = new THREE.ConeGeometry(0.05, 0.15, 6); + const tip = createMesh(tipGeo, metalMaterial.clone().set({roughness: 0.7, color: 0x666666}), {y: spearLength/2}); + spear.add(tip); + + return goblinGroup; + }; + + const goblin1 = createGoblin(new THREE.Vector3(-1.5, 0, 2)); + const goblin2 = createGoblin(new THREE.Vector3(1.8, 0, 2.5)); + goblin1.rotation.y = Math.PI / 8; + goblin2.rotation.y = -Math.PI / 6; + group.add(goblin1); + group.add(goblin2); + return group; - } + } + + function createCoastalCliffsAssembly() { + const group = new THREE.Group(); + const cliffWidth = 15; + const cliffHeight = 8; + const cliffDepth = 15; + + const cliffGeo = new THREE.BoxGeometry(cliffWidth, cliffHeight, cliffDepth); + const cliffMat = stoneMaterial.clone(); + + const positions = cliffGeo.attributes.position; + const normals = cliffGeo.attributes.normal; + for(let i=0; i { + ocean.position.y = ocean.userData.baseY + Math.sin(time * 0.5) * 0.15; + const oceanPos = oceanGeo.attributes.position; + for(let i=0; i 0) { + shepherd.position.y = intersects[0].point.y + 1.4/2; + } + group.add(shepherd); + + + const sheepGeo = new THREE.SphereGeometry(0.3, 8, 6); + const sheepMat = new THREE.MeshStandardMaterial({color: 0xeeeeee, roughness: 0.9}); + for (let i = 0; i < 10; i++) { + const sx = 15 + (Math.random() - 0.5) * 8; + const sz = -20 + (Math.random() - 0.5) * 8; + const sheep = createMesh(sheepGeo, sheepMat, { x: sx, y: 0, z: sz }); + const sheepRaycaster = new THREE.Raycaster(new THREE.Vector3(sx, 10, sz), new THREE.Vector3(0, -1, 0)); + const sheepIntersects = sheepRaycaster.intersectObject(hill); + if (sheepIntersects.length > 0) { + sheep.position.y = sheepIntersects[0].point.y + 0.3; + } + group.add(sheep); + } + + const flowerGeo = new THREE.ConeGeometry(0.05, 0.2, 5); + const flowerMat = new THREE.MeshStandardMaterial({color: 0xffff00}); + for (let i = 0; i < 100; i++) { + const fx = (Math.random() - 0.5) * hillSize * 0.8; + const fz = (Math.random() - 0.5) * hillSize * 0.8; + const flower = createMesh(flowerGeo, flowerMat, { x: fx, y: 0, z: fz }); + const flowerRaycaster = new THREE.Raycaster(new THREE.Vector3(fx, 10, fz), new THREE.Vector3(0, -1, 0)); + const flowerIntersects = flowerRaycaster.intersectObject(hill); + if (flowerIntersects.length > 0) { + flower.position.y = flowerIntersects[0].point.y + 0.1; + } + group.add(flower); + } + + return group; + } + + function createCrossroadsAssembly() { + const group = new THREE.Group(); + group.add(createGroundPlane(dirtMaterial, 30)); + + const poleGeo = new THREE.CylinderGeometry(0.15, 0.12, 3.5, 8); + group.add(createMesh(poleGeo, darkWoodMaterial, { y: 1.75 })); + + const signGeo = new THREE.BoxGeometry(1.8, 0.4, 0.1); + const signMat = woodMaterial.clone(); + group.add(createMesh(signGeo, signMat, { y: 2.8, z: 0.3, x: 0.7 }, { y: Math.PI / 5 })); + group.add(createMesh(signGeo.clone(), signMat, { y: 2.5, x: -0.7 }, { y: -Math.PI / 6 })); + group.add(createMesh(signGeo.clone(), signMat, { y: 2.2, z: -0.3, x: 0.1 }, { y: Math.PI + Math.PI / 7 })); + + + const grassGeo = new THREE.ConeGeometry(0.15, 0.4, 6); + for (let i = 0; i < 80; i++) { + const x = (Math.random() - 0.5) * 28; + const z = (Math.random() - 0.5) * 28; + if (Math.abs(x) > 3 || Math.abs(z) > 3) { + const grass = createMesh(grassGeo, grassMaterial, { x, y: 0.2, z }, { y: Math.random() * Math.PI }); + grass.scale.setScalar(0.8 + Math.random()*0.4); + group.add(grass); + } + } + + const rockGeo = new THREE.IcosahedronGeometry(0.4 + Math.random()*0.3, 0); + for (let i = 0; i < 15; i++) { + const rock = createMesh(rockGeo, stoneMaterial, { x: (Math.random() - 0.5) * 25, y: 0.2, z: (Math.random() - 0.5) * 25 }, { y: Math.random() * Math.PI }); + rock.rotation.x = Math.random()*0.3; rock.rotation.z = Math.random()*0.3; + group.add(rock); + } + return group; + } + + function createForestEntranceAssembly() { + const group = createForestAssembly(30, 18); + const rootGeo = new THREE.TorusGeometry(0.8 + Math.random()*0.4, 0.15 + Math.random()*0.1, 8, 16); + for (let i = 0; i < 15; i++) { + const root = createMesh(rootGeo, darkWoodMaterial, { x: (Math.random() - 0.5) * 12, y: 0.15, z: (Math.random() - 0.5) * 12 }, { x: Math.PI / 2 + (Math.random()-0.5)*0.3, y: Math.random()*Math.PI }); + root.scale.y = 0.5 + Math.random(); + group.add(root); + } + return group; + } + + function createHiddenCoveAssembly() { + const group = new THREE.Group(); + const coveSize = 20; + group.add(createGroundPlane(sandMaterial, coveSize)); + + const caveEntranceWidth = 4; + const caveEntranceHeight = 3; + const caveWallGeo = new THREE.BoxGeometry(coveSize*1.5, 8, coveSize*0.3); + const caveWall = createMesh(caveWallGeo, stoneMaterial, { z: -coveSize/2 - coveSize*0.15, y: 4}); + group.add(caveWall); + + + const rockGeo = new THREE.IcosahedronGeometry(0.6 + Math.random()*0.5, 0); + for (let i = 0; i < 20; i++) { + const x = (Math.random() - 0.5) * coveSize * 0.9; + const z = Math.random() * coveSize * 0.4; + const rock = createMesh(rockGeo, wetStoneMaterial, { x: x, y: 0.3, z: z }); + rock.rotation.set(Math.random()*0.5, Math.random()*Math.PI*2, Math.random()*0.5); + group.add(rock); + } + + const seaweedGeo = new THREE.ConeGeometry(0.15, 1.2 + Math.random()*0.5, 6); + for (let i = 0; i < 15; i++) { + const x = (Math.random() - 0.5) * coveSize * 0.7; + const z = Math.random() * coveSize * 0.3; + const seaweed = createMesh(seaweedGeo, leafMaterial, { x: x, y: 0.6, z: z }, {x: (Math.random()-0.5)*0.2}); + group.add(seaweed); + } + + const oceanGeo = new THREE.PlaneGeometry(coveSize*1.5, coveSize*0.7, 10, 5); + const ocean = createMesh(oceanGeo, oceanMaterial, {y: 0.1, z: coveSize*0.35}, {x: -Math.PI/2}); + group.add(ocean); + + return group; + } + + 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; + } + + 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; + } + function createPrisonerCellAssembly() { return createDefaultAssembly(); } + function createResistanceMeetingAssembly() { return createDefaultAssembly(); } + function createRoadAmbushAssembly() { return createDefaultAssembly(); } + function createForestEdgeAssembly() { return createDefaultAssembly(); } + function createWeaponsmithAssembly() { return createDefaultAssembly(); } - // Game Data const itemsData = { "Flaming Sword":{type:"weapon", description:"A fiery blade"}, "Whispering Bow":{type:"weapon", description:"A silent bow"}, @@ -568,285 +927,478 @@ "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."} + "Scout's Pouch":{type:"quest", description:"Contains odds and ends."}, + "Health Potion": {type:"consumable", description:"A swirling red liquid. Restores some health when drunk.", effect: { hpGain: 15 }}, + "Antidote": {type:"consumable", description:"A chalky blue vial. Cures poison.", effect: { cure: "Poisoned" }}, }; const gameData = { "1": { title: "The Crossroads", content: `

Dust swirls... Which path calls to you?

`, 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" }, - "2": { title: "Rolling Hills", content: `

Verdant hills stretch before you... It feels peaceful...

`, options: [ { text: "Follow the narrow path", next: 4 }, { text: "Try to hail the distant shepherd (Charisma Check?)", next: 99 } ], illustration: "rolling-green-hills-shepherd-distance" }, - "3": { title: "Coastal Cliffs Edge", content: `

You stand atop windswept cliffs... A precarious-looking path descends...

`, 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 } ], illustration: "windy-sea-cliffs-crashing-waves-path-down" }, + "2": { title: "Rolling Hills", content: `

Verdant hills stretch before you... It feels peaceful...

`, options: [ { text: "Follow the narrow path", next: 4 }, { text: "Try to hail the distant shepherd (Charisma Check - DC 10)", check: { stat: 'charisma', dc: 10, onFailure: 201 }, next: 200 } ], illustration: "rolling-green-hills-shepherd-distance" }, + "3": { title: "Coastal Cliffs Edge", content: `

You stand atop windswept cliffs... A precarious-looking path descends...

`, options: [ { text: "Attempt the precarious descent (Dexterity Check - DC 12)", check: { stat: 'dexterity', dc: 12, onFailure: 31 }, next: 30 }, { text: "Scan the cliff face for easier routes (Wisdom Check - DC 11)", check: { stat: 'wisdom', dc: 11, onFailure: 32 }, next: 33 } ], illustration: "windy-sea-cliffs-crashing-waves-path-down" }, "4": { title: "Hill Path Overlook", content: `

The path crests a hill... you see a small, overgrown shrine...

`, options: [ { text: "Investigate the overgrown shrine", next: 40 }, { text: "Continue towards the badlands", next: 41 } ], illustration: "hilltop-view-overgrown-shrine-wildflowers" }, - "5": { title: "Shadowwood Entrance", content: `

Sunlight struggles to pierce the dense canopy... How do you proceed?

`, 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" }, - "6": { title: "Overgrown Forest Path", content: `

The path is barely visible... You hear a twig snap nearby!

`, 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" }, - "7": { title: "Tangled Undergrowth", content: `

Pushing through ferns... You stumble upon a small clearing containing a moss-covered, weathered stone statue...

`, 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" }, - "8": { title: "Hidden Game Trail", content: `

Your sharp eyes spot a faint trail... It leads towards a ravine spanned by a rickety rope bridge.

(+20 XP)

`, 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 } }, - "10": { title: "Goblin Ambush!", content: `

Two scraggly goblins leap out, brandishing crude spears!

`, options: [ { text: "Fight the goblins!", next: 12 }, { text: "Attempt to dodge past them (Dexterity Check)", check: { stat: 'dexterity', dc: 13, onFailure: 10 }, next: 13 } ], illustration: "two-goblins-ambush-forest-path-spears" }, - "11": { title: "Hidden Evasion", content: `

You melt into the shadows as the goblins blunder past.

(+30 XP)

`, options: [ { text: "Continue cautiously", next: 14 } ], illustration: "forest-shadows-hiding-goblins-walking-past", reward: { xp: 30 } }, - "12": { title: "Ambush Victory!", content: `

You defeat the goblins! Found a Crude Dagger.

(+50 XP)

`, options: [ { text: "Press onward", next: 14 } ], illustration: "defeated-goblins-forest-path-loot", reward: { xp: 50, addItem: "Crude Dagger" } }, - "13": { title: "Daring Escape", content: `

With surprising agility, you tumble past the goblins!

(+25 XP)

`, options: [ { text: "Keep running!", next: 14 } ], illustration: "blurred-motion-running-past-goblins-forest", reward: { xp: 25 } }, + "5": { title: "Shadowwood Entrance", content: `

Sunlight struggles to pierce the dense canopy... How do you proceed?

`, 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 - DC 10)", check: { stat: 'wisdom', dc: 10, onFailure: 6 }, next: 8 } ], illustration: "dark-forest-entrance-gnarled-roots-filtered-light" }, + "6": { title: "Overgrown Forest Path", content: `

The path is barely visible... You hear a twig snap nearby!

`, options: [ { text: "Ready your weapon and investigate", next: 10 }, { text: "Attempt to hide quietly (Dexterity Check - DC 11)", check: { stat: 'dexterity', dc: 11, onFailure: 10 }, next: 11 }, { text: "Call out cautiously", next: 10 } ], illustration: "overgrown-forest-path-glowing-fungi-vines" }, + "7": { title: "Tangled Undergrowth", content: `

Pushing through ferns... You stumble upon a small clearing containing a moss-covered, weathered stone statue...

`, options: [ { text: "Examine the statue closely (Intelligence Check - DC 13)", check: { stat: 'intelligence', dc: 13, onFailure: 71 }, next: 70 }, { text: "Ignore the statue and press on", next: 72 }, { text: "Leave a small offering (Requires: non-quest item)", requireItemType: "non-quest", consumeItem: true, next: 73 }, { text: "Rest briefly in the clearing", next: 74} ], illustration: "forest-clearing-mossy-statue-weathered-stone" }, + "8": { title: "Hidden Game Trail", content: `

Your sharp eyes spot a faint trail... It leads towards a ravine spanned by a rickety rope bridge.

Gained +20 XP.

`, options: [ { text: "Risk crossing the rope bridge (Dexterity Check - DC 10)", check: { stat: 'dexterity', dc: 10, onFailure: 81 }, next: 80 }, { text: "Search for another way across the ravine (Wisdom Check - DC 13)", check: { stat: 'wisdom', dc: 13, onFailure: 81 }, next: 82 } ], illustration: "narrow-game-trail-forest-rope-bridge-ravine", reward: { xp: 20 } }, + "10": { title: "Goblin Ambush!", content: `

Two scraggly goblins leap out, brandishing crude spears!

`, options: [ { text: "Fight the goblins!", next: 12 }, { text: "Attempt to dodge past them (Dexterity Check - DC 13)", check: { stat: 'dexterity', dc: 13, onFailure: 101 }, next: 13 }, { text: "Try to intimidate them (Charisma Check - DC 14)", check: { stat: 'charisma', dc: 14, onFailure: 101 }, next: 102 } ], illustration: "two-goblins-ambush-forest-path-spears" }, + "11": { title: "Hidden Evasion", content: `

You melt into the shadows as the goblins blunder past.

+30 XP.

`, options: [ { text: "Continue cautiously", next: 14 } ], illustration: "forest-shadows-hiding-goblins-walking-past", reward: { xp: 30 } }, + "12": { title: "Ambush Victory!", content: `

You defeat the goblins! Found a Crude Dagger and a Health Potion.

+50 XP, Crude Dagger, Health Potion.

`, options: [ { text: "Press onward", next: 14 } ], illustration: "defeated-goblins-forest-path-loot", reward: { xp: 50, addItem: ["Crude Dagger", "Health Potion"] } }, + "13": { title: "Daring Escape", content: `

With surprising agility, you tumble past the goblins!

+25 XP.

`, options: [ { text: "Keep running!", next: 14 } ], illustration: "blurred-motion-running-past-goblins-forest", reward: { xp: 25 } }, "14": { title: "Forest Stream Crossing", content: `

The path leads to a clear, shallow stream...

`, 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" }, - "15": { title: "Log Bridge", content: `

Further upstream, a large, mossy log spans the stream.

`, 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" }, - "151": { title: "Splash!", content: `

You slip on the mossy log and tumble into the cold stream! You're soaked but unharmed.

`, options: [ { text: "Shake yourself off and continue", next: 16 } ], illustration: "character-splashing-into-stream-from-log" }, - "16": { title: "Edge of the Woods", content: `

You emerge from the Shadowwood... Before you lie rocky foothills...

`, 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" }, - "17": { title: "Rocky Foothills Path", content: `

The climb is arduous... The fortress looms larger now.

`, 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" }, - "18": { title: "Distant Observation", content: `

You notice what might be a less-guarded approach along the western ridge...

(+30 XP)

`, 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 } }, - "19": { title: "Blocked Pass", content: `

The main path is blocked by a recent rockslide!

`, 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" }, - "20": { title: "Goat Trail", content: `

You discover a narrow trail barely wide enough for a mountain goat...

(+40 XP)

`, options: [ { text: "Follow the precarious goat trail", next: 22 } ], illustration: "narrow-goat-trail-mountainside-fortress-view", reward: { xp: 40 } }, - "30": { title: "Hidden Cove", content: `

Your careful descent brings you to a secluded cove. A dark cave entrance is visible...

(+25 XP)

`, options: [ { text: "Explore the dark cave", next: 35 } ], illustration: "hidden-cove-beach-dark-cave-entrance", reward: { xp: 25 } }, + "15": { title: "Log Bridge", content: `

Further upstream, a large, mossy log spans the stream.

`, options: [ { text: "Cross carefully on the log (Dexterity Check - DC 9)", check: { stat: 'dexterity', dc: 9, onFailure: 151 }, next: 16 }, { text: "Go back and wade instead", next: 14 } ], illustration: "mossy-log-bridge-over-forest-stream" }, + "151": { title: "Splash!", content: `

You slip on the mossy log and tumble into the cold stream! You're soaked but unharmed.

Gained 'Chilled' effect (-1 Dex temporarily).

`, options: [ { text: "Shake yourself off and continue", next: 16 } ], illustration: "character-splashing-into-stream-from-log", effects: [{name: "Chilled", duration: 2, mod: {dexterity: -1}}] }, + "16": { title: "Edge of the Woods", content: `

You emerge from the Shadowwood... Before you lie rocky foothills...

`, options: [ { text: "Begin the ascent into the foothills", next: 17 }, { text: "Scan the fortress from afar (Wisdom Check - DC 14)", check: { stat: 'wisdom', dc: 14, onFailure: 17 }, next: 18 } ], illustration: "forest-edge-view-rocky-foothills-distant-mountain-fortress" }, + "17": { title: "Rocky Foothills Path", content: `

The climb is arduous... The fortress looms larger now.

`, options: [ { text: "Continue the direct ascent", next: 19 }, { text: "Look for signs of a hidden trail (Wisdom Check - DC 15)", check: { stat: 'wisdom', dc: 15, onFailure: 19 }, next: 20 } ], illustration: "climbing-rocky-foothills-path-fortress-closer" }, + "18": { title: "Distant Observation", content: `

You notice what might be a less-guarded approach along the western ridge...

+30 XP.

`, 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 } }, + "19": { title: "Blocked Pass", content: `

The main path is blocked by a recent rockslide!

`, options: [ { text: "Try to climb over (Strength Check - DC 14)", check: { stat: 'strength', dc: 14, onFailure: 191 }, next: 190 }, { text: "Search for another way around", next: 192 } ], illustration: "rockslide-blocking-mountain-path-boulders" }, + "20": { title: "Goat Trail", content: `

You discover a narrow trail barely wide enough for a mountain goat...

+40 XP.

`, options: [ { text: "Follow the precarious goat trail", next: 22 } ], illustration: "narrow-goat-trail-mountainside-fortress-view", reward: { xp: 40 } }, + "30": { title: "Hidden Cove", content: `

Your careful descent brings you to a secluded cove. A dark cave entrance is visible...

+25 XP.

`, options: [ { text: "Explore the dark cave", next: 35 } ], illustration: "hidden-cove-beach-dark-cave-entrance", reward: { xp: 25 } }, "31": { title: "Tumbled Down", content: `

You lose your footing... landing hard on the sandy cove floor. You lose 5 HP. A dark cave entrance beckons.

`, options: [ { text: "Gingerly explore the dark cave", next: 35 } ], illustration: "character-fallen-at-bottom-of-cliff-path-cove", hpLoss: 5 }, - "32": { title: "No Easier Path", content: `

You scan the cliffs intently but find no obviously easier routes.

`, options: [ { text: "Attempt the precarious descent (Dexterity Check)", check: { stat: 'dexterity', dc: 12, onFailure: 31 }, next: 30 } ], illustration: "scanning-sea-cliffs-no-other-paths-visible" }, - "33": { title: "Smuggler's Steps?", content: `

Your keen eyes spot a series of barely visible handholds and steps carved into the rock...

(+15 XP)

`, 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 } }, + "32": { title: "No Easier Path", content: `

You scan the cliffs intently but find no obviously easier routes.

`, options: [ { text: "Attempt the precarious descent (Dexterity Check - DC 12)", check: { stat: 'dexterity', dc: 12, onFailure: 31 }, next: 30 } ], illustration: "scanning-sea-cliffs-no-other-paths-visible" }, + "33": { title: "Smuggler's Steps?", content: `

Your keen eyes spot a series of barely visible handholds and steps carved into the rock...

+15 XP.

`, options: [ { text: "Use the hidden steps (Easier Dex Check - DC 8)", check: { stat: 'dexterity', dc: 8, onFailure: 31 }, next: 30 } ], illustration: "close-up-handholds-carved-in-cliff-face", reward: { xp: 15 } }, "35": { title: "Dark Cave", content: `

The cave smells of salt and decay. Water drips somewhere within.

`, options: [{ text: "Press deeper into the darkness", next: 99 } ], illustration: "dark-cave-entrance-dripping-water" }, - "40": { title: "Overgrown Shrine", content: `

Wildflowers grow thick around a small stone shrine. It feels ancient and neglected.

`, options: [{ text: "Examine the carvings (Intelligence Check)", check:{stat:'intelligence', dc:11, onFailure: 401}, next: 400 } ], illustration: "overgrown-stone-shrine-wildflowers-close" }, + "40": { title: "Overgrown Shrine", content: `

Wildflowers grow thick around a small stone shrine. It feels ancient and neglected.

`, options: [{ text: "Examine the carvings (Intelligence Check - DC 11)", check:{stat:'intelligence', dc:11, onFailure: 401}, next: 400 } ], illustration: "overgrown-stone-shrine-wildflowers-close" }, "41": { title: "Rocky Badlands", content: `

The green hills give way to cracked earth and jagged rock formations under a harsh sun.

`, options: [{ text: "Scout ahead", next: 99 } ], illustration: "rocky-badlands-cracked-earth-harsh-sun" }, - "70": { title: "Statue's Secret", content:"

Running your fingers over the mossy stone... found a Scout's Pouch!

(+40 XP)

", options: [{text:"Take the pouch and press on", next: 72}], illustration:"forest-clearing-mossy-statue-hidden-compartment", reward:{addItem: "Scout's Pouch", xp: 40}}, // Added reward object - "71": { title: "Just an Old Statue", content:"

Despite a careful examination, the statue appears to be just that – an old, weathered stone figure.

", options: [{text:"Ignore the statue and press on", next: 72}], illustration:"forest-clearing-mossy-statue-weathered-stone"}, + "70": { title: "Statue's Secret", content:"

Running your fingers over the mossy stone... found a Scout's Pouch!

Found Scout's Pouch! +40 XP.

", options: [{text:"Take the pouch and press on", next: 72}], illustration:"forest-clearing-mossy-statue-hidden-compartment", reward:{addItem: "Scout's Pouch", xp: 40}}, + "71": { title: "Just an Old Statue", content:"

Despite a careful examination, the statue appears to be just that – an old, weathered stone figure.

", options: [{text:"Ignore the statue and press on", next: 72}, { text: "Rest briefly in the clearing", next: 74}], illustration:"forest-clearing-mossy-statue-weathered-stone"}, "72": { title: "Back to the Thicket", content:"

Leaving the clearing, you push back into the undergrowth, eventually relocating the main path.

", options: [{text:"Continue along the main path", next: 6}], illustration:"pushing-through-forest-undergrowth"}, - "73": { title: "A Small Offering", content:"

You place a small offering at the statue's base. You feel a subtle sense of approval.

", options: [{text:"Try to find the main path again", next: 72}], illustration:"forest-clearing-mossy-statue-offering"}, - "80": { title: "Across the Ravine", content:"

You make your way carefully across the swaying rope bridge.

(+25 XP)

", options: [{text:"Continue following the game trail", next: 14}], illustration:"character-crossing-rope-bridge-safely", reward:{xp:25}}, + "73": { title: "A Small Offering", content:"

You place a small offering ({consumedItem}) at the statue's base. You feel a subtle sense of approval.

Gained 'Statue's Blessing' effect (+1 Wis temporarily).

", options: [{text:"Try to find the main path again", next: 72}], illustration:"forest-clearing-mossy-statue-offering", effects: [{name: "Statue's Blessing", duration: 3, mod: {wisdom: 1}}]}, + "74": { title: "Moment of Rest", content:"

You spend a quiet moment in reflection. The tranquility settles your nerves.

Recovered 1 Sanity. Cleared 'Chilled' if present.

", options: [{text:"Press on", next: 72}], illustration:"forest-clearing-mossy-statue-offering", reward: {sanityGain: 1, clearEffect: "Chilled"} }, + "80": { title: "Across the Ravine", content:"

You make your way carefully across the swaying rope bridge.

+25 XP.

", options: [{text:"Continue following the game trail", next: 14}], illustration:"character-crossing-rope-bridge-safely", reward:{xp:25}}, "81": { title: "Bridge Collapse!", content:"

A rope snaps! The bridge lurches, sending you plunging into the ravine! You lose 10 HP.

", options: [{text:"Climb out and find another way", next: 82}], illustration:"rope-bridge-snapping-character-falling", hpLoss: 10}, "82": { title: "Ravine Detour", content:"

You find a place where a fallen log provides a safer way across.

", options: [{text:"Cross the log bridge and continue", next: 14}], illustration:"fallen-log-crossing-ravine"}, - "190": { title: "Over the Rocks", content:"

With considerable effort, you manage to climb over the rockslide.

(+35 XP)

", options: [{text:"Continue up the path", next: 22}], illustration:"character-climbing-over-boulders", reward: {xp:35} }, + "190": { title: "Over the Rocks", content:"

With considerable effort, you manage to climb over the rockslide.

+35 XP.

", options: [{text:"Continue up the path", next: 22}], illustration:"character-climbing-over-boulders", reward: {xp:35} }, "191": { title: "Climb Fails", content:"

The boulders are too unstable or sheer. You cannot climb them safely.

", options: [{text:"Search for another way around", next: 192}], illustration:"character-slipping-on-rockslide-boulders"}, "192": { title: "Detour Found", content:"

After some searching, you find a rough path leading around the rockslide, eventually rejoining the main trail.

", options: [{text:"Continue up the path", next: 22}], illustration:"rough-detour-path-around-rockslide"}, - "21": { title: "Western Ridge", content:"

The ridge path is narrow and exposed, with strong winds threatening to push you off.

", options: [{text:"Proceed carefully (Dexterity Check)", check:{stat:'dexterity', dc: 14, onFailure: 211}, next: 22 } ], illustration:"narrow-windy-mountain-ridge-path" }, - "22": { title: "Fortress Approach", content:"

You've navigated the treacherous paths and now stand near the outer walls of the dark fortress. Guards patrol the battlements.

", options: [{text:"Look for an unguarded entrance", next: 99}], illustration:"approaching-dark-fortress-walls-guards"}, // Simplified options for base code + "21": { title: "Western Ridge", content:"

The ridge path is narrow and exposed, with strong winds threatening to push you off.

", options: [{text:"Proceed carefully (Dexterity Check - DC 14)", check:{stat:'dexterity', dc: 14, onFailure: 211}, next: 22 } ], illustration:"narrow-windy-mountain-ridge-path" }, + "22": { title: "Fortress Approach", content:"

You've navigated the treacherous paths and now stand near the outer walls of the dark fortress. Guards patrol the battlements.

", options: [{text:"Look for an unguarded entrance", next: 99}], illustration:"approaching-dark-fortress-walls-guards"}, "211": {title:"Lost Balance", content:"

A strong gust of wind catches you off guard, sending you tumbling down a steep slope! You lose 10 HP.

", options:[{text:"Climb back up and find another way", next: 17}], illustration:"character-falling-off-windy-ridge", hpLoss: 10}, "400": { title: "Shrine Insights", content:"

The carvings depict cycles of growth. You feel a sense of calm. (+1 HP)

", options: [{text:"Continue towards the badlands", next: 41}], illustration: "overgrown-stone-shrine-wildflowers-close", reward: {hpGain: 1}}, "401": { title: "Mysterious Carvings", content:"

The carvings are too worn to decipher.

", options: [{text:"Continue towards the badlands", next: 41}], illustration: "overgrown-stone-shrine-wildflowers-close"}, "402": { title: "Moment of Peace", content:"

You spend a quiet moment in reflection. The tranquility settles your nerves.

", options: [{text:"Continue towards the badlands", next: 41}], illustration: "overgrown-stone-shrine-wildflowers-close"}, - "99": { title: "Game Over / To Be Continued...", content: "

Your adventure ends here (for now).

", options: [{ text: "Restart", next: 1 }], illustration: "game-over-generic", gameOver: true } + "200": { title: "Shepherd's Greeting", content: "

You call out. The shepherd turns, leaning on their crook, and waves cautiously. 'Lost, traveler?' they call back, their voice surprisingly strong.

", options: [{text: "Ask for directions", next: 202}, {text: "Ask about the fortress", next: 203}], illustration: "rolling-green-hills-shepherd-close"}, + "201": { title: "Shepherd Ignores You", content: "

You call out, but the wind snatches your words away, or perhaps the shepherd simply chooses to ignore you, focusing on their flock.

", options: [{text: "Follow the narrow path further East", next: 4}], illustration: "rolling-green-hills-shepherd-distance"}, + "202": { title: "Directions Given", content: "

'The path eastward leads to the badlands,' the shepherd says, pointing. 'West takes you back to the crossroads eventually. North... only trouble lies north in those woods these days.'

", options: [{text: "Thank them and head East", next: 4}, {text: "Ask about the fortress", next: 203}], illustration: "rolling-green-hills-shepherd-close"}, + "203": { title: "Whispers of the Fortress", content: "

The shepherd lowers their voice. 'The Dark Lord's Keep? Aye, it looms over all. Few go near. Fewer return. They say there's a hidden way, though... something about the western ridge, if you've the stomach for heights.'

Gained clue about Western Ridge. +10 XP.

", options: [{text: "Thank them and head East", next: 4}], illustration: "rolling-green-hills-shepherd-close", reward: {xp: 10}}, + "101": { title: "Caught!", content: `

You try to slip past or scare them, but stumble / fail to impress. You're forced to fight!

`, options: [ { text: "Fight the goblins!", next: 12 } ], illustration: "two-goblins-ambush-forest-path-spears" }, + "102": { title: "Intimidating Success", content: `

You let out a fearsome roar! The goblins, clearly not brave, hesitate, glance at each other, and scurry back into the undergrowth.

Intimidated goblins! +35 XP.

`, options: [ { text: "Continue onward, heart pounding", next: 14 } ], illustration: "forest-path-scared-goblins-fleeing", reward: { xp: 35 } }, + "99": { title: "Game Over / To Be Continued...", content: "

Your adventure ends here (for now).

", options: [{ text: "Restart Adventure", next: 1 }], illustration: "game-over-generic", gameOver: true } }; - // Game State let gameState = { currentPageId: 1, + previousPageId: 1, character: { name: "Hero", race: "Human", alignment: "Neutral Good", class: "Adventurer", level: 1, xp: 0, xpToNextLevel: 100, - stats: { strength: 8, intelligence: 10, wisdom: 10, dexterity: 10, constitution: 10, charisma: 8, hp: 12, maxHp: 12 }, - inventory: [] + stats: { strength: 10, intelligence: 10, wisdom: 10, dexterity: 10, constitution: 10, charisma: 10, hp: 20, maxHp: 20, sanity: 10, maxSanity: 10 }, + inventory: [], + effects: [] } }; - // Game Logic Functions function startGame() { - // This function RESETS the game state fully const defaultChar = { name: "Hero", race: "Human", alignment: "Neutral Good", class: "Adventurer", level: 1, xp: 0, xpToNextLevel: 100, - stats: { strength: 8, intelligence: 10, wisdom: 10, dexterity: 10, constitution: 10, charisma: 8, hp: 12, maxHp: 12 }, - inventory: [] - }; - // Use deep copy for nested objects - gameState = { currentPageId: 1, character: JSON.parse(JSON.stringify(defaultChar)) }; + stats: { strength: 10, intelligence: 10, wisdom: 10, dexterity: 10, constitution: 10, charisma: 10, hp: 20, maxHp: 20, sanity: 10, maxSanity: 10 }, + inventory: [], + effects: [] + }; + gameState = { currentPageId: 1, previousPageId: 1, character: JSON.parse(JSON.stringify(defaultChar)) }; console.log("Starting new game state:", gameState); renderPage(gameState.currentPageId); } + function applyEffect(effectData) { + if (!gameState.character.effects.some(e => e.name === effectData.name)) { + gameState.character.effects.push({...effectData}); + console.log(`Applied effect: ${effectData.name}`); + return `

Gained effect: ${effectData.name}

`; + } else { + console.log(`Effect ${effectData.name} already active.`); + return ""; + } + } + + function clearEffect(effectName) { + const initialLength = gameState.character.effects.length; + gameState.character.effects = gameState.character.effects.filter(e => e.name !== effectName); + if (gameState.character.effects.length < initialLength) { + console.log(`Cleared effect: ${effectName}`); + return `

Effect Cleared: ${effectName}

`; + } + return ""; + } + + function tickEffects() { + let effectsClearedMessage = ""; + gameState.character.effects = gameState.character.effects.filter(effect => { + if (effect.duration !== undefined) { + effect.duration -= 1; + if (effect.duration <= 0) { + console.log(`Effect expired: ${effect.name}`); + effectsClearedMessage += `

Effect Expired: ${effect.name}

`; + return false; + } + } + return true; + }); + return effectsClearedMessage; + } + + function getStatModifier(statName) { + let modifier = 0; + gameState.character.effects.forEach(effect => { + if (effect.mod && effect.mod[statName]) { + modifier += effect.mod[statName]; + } + }); + return modifier; + } + + function getEffectiveStat(statName) { + return (gameState.character.stats[statName] || 0) + getStatModifier(statName); + } + function handleChoiceClick(choiceData) { console.log("Choice clicked:", choiceData); + let message = ""; - // --- Handle Restart --- - // If the 'next' property is explicitly 1 (used by the restart button on page 99) - if (choiceData.nextPage === 1 && gameState.currentPageId === 99) { - console.log("Restarting game..."); - startGame(); // Call the function that fully resets the game - return; // Stop processing this click further - } + message += tickEffects(); + + if (choiceData.nextPage === 1 && (gameState.currentPageId === 99 || gameData[gameState.currentPageId]?.gameOver)) { + console.log("Restarting game..."); + startGame(); + return; + } + + let consumedItemName = null; + if (choiceData.consumeItem) { + let itemToRemove = choiceData.requireItem; + if (choiceData.requireItemType) { + itemToRemove = gameState.character.inventory.find(itemName => { + const itemDef = itemsData[itemName]; + if (choiceData.requireItemType === 'non-quest') { + return itemDef && itemDef.type !== 'quest'; + } + if (choiceData.requireItemType === 'consumable') { + return itemDef && itemDef.type === 'consumable'; + } + return false; + }); + } + + if (itemToRemove && gameState.character.inventory.includes(itemToRemove)) { + gameState.character.inventory = gameState.character.inventory.filter(i => i !== itemToRemove); + consumedItemName = itemToRemove; + console.log(`Consumed item: ${consumedItemName}`); + message += `

Used: ${consumedItemName}

`; + } else { + console.error("Attempted to consume an item that wasn't required or available:", choiceData); + renderPageInternal(gameState.currentPageId, gameData[gameState.currentPageId], "

Error: Tried to use an unavailable item.

"); + return; + } + } - // --- Standard Choice Processing --- const optionNextPageId = parseInt(choiceData.nextPage); - const itemToAdd = choiceData.addItem; let nextPageId = optionNextPageId; - let rollResultMessage = ""; const check = choiceData.check; - // --- Basic Validation --- - // Check if nextPage is NaN AND there's no skill check (meaning invalid choice data) if (isNaN(nextPageId) && !check) { - console.error("Invalid choice data:", choiceData); - // Optionally go to an error page or just log and return - // Going to page 99 for safety - renderPageInternal(99, gameData[99], `

Error: Invalid choice data!

`); - return; - } + console.error("Invalid choice data (no nextPage or check):", choiceData); + renderPageInternal(99, gameData[99], `

Error: Invalid choice data!

`); + return; + } - // --- Skill Check Logic --- if (check) { - const statValue = gameState.character.stats[check.stat] || 10; - const modifier = Math.floor((statValue - 10) / 2); + const baseStatValue = gameState.character.stats[check.stat] || 10; + const modifierFromEffects = getStatModifier(check.stat); + const effectiveStatValue = baseStatValue + modifierFromEffects; const roll = Math.floor(Math.random() * 20) + 1; - const totalResult = roll + modifier; + const totalResult = roll + Math.floor((effectiveStatValue - 10) / 2); const dc = check.dc; - console.log(`Check: ${check.stat} (DC ${dc}) | Roll: ${roll} + Mod: ${modifier} = ${totalResult}`); + console.log(`Check: ${check.stat} (Base: ${baseStatValue}, Effects: ${modifierFromEffects}, Eff: ${effectiveStatValue}, Mod: ${Math.floor((effectiveStatValue - 10) / 2)}) | Roll: ${roll} -> Total: ${totalResult} vs DC ${dc}`); + if (totalResult >= dc) { - nextPageId = optionNextPageId; // Success path - rollResultMessage = `

${check.stat.charAt(0).toUpperCase() + check.stat.slice(1)} Check Success! (${totalResult} vs DC ${dc})

`; + nextPageId = optionNextPageId; + message += `

${check.stat.charAt(0).toUpperCase() + check.stat.slice(1)} Check Success! (${totalResult} vs DC ${dc})

`; + + const statToIncrease = check.stat; + if (gameState.character.stats.hasOwnProperty(statToIncrease)) { + const oldValue = gameState.character.stats[statToIncrease]; + gameState.character.stats[statToIncrease]++; + const statCap = 20; + gameState.character.stats[statToIncrease] = Math.min(statCap, gameState.character.stats[statToIncrease]); + + if (gameState.character.stats[statToIncrease] > oldValue) { + console.log(`${statToIncrease} increased by 1. New value: ${gameState.character.stats[statToIncrease]}`); + message += `

Your ${statToIncrease} improved! (+1)

`; + + if (statToIncrease === 'constitution') { + recalculateMaxHp(); + const oldMod = Math.floor(((gameState.character.stats.constitution -1) - 10) / 2); + const newMod = Math.floor((gameState.character.stats.constitution - 10) / 2); + if (newMod > oldMod) { + const hpGain = (newMod - oldMod) * gameState.character.level; + gameState.character.stats.hp += hpGain; + message += `

Increased vitality! (+${hpGain} HP)

`; + } + } + if (statToIncrease === 'wisdom') { + recalculateMaxSanity(); + } + } else { + console.log(`${statToIncrease} already at cap (${statCap}).`); + } + } + } else { - nextPageId = parseInt(check.onFailure); // Failure path - rollResultMessage = `

${check.stat.charAt(0).toUpperCase() + check.stat.slice(1)} Check Failed! (${totalResult} vs DC ${dc})

`; - if (isNaN(nextPageId)) { // Handle invalid failure ID + nextPageId = parseInt(check.onFailure); + message += `

${check.stat.charAt(0).toUpperCase() + check.stat.slice(1)} Check Failed! (${totalResult} vs DC ${dc})

`; + if (isNaN(nextPageId)) { console.error("Invalid onFailure ID:", check.onFailure); nextPageId = 99; - rollResultMessage += `

Error: Invalid failure path ID!

`; + message += `

Error: Invalid failure path ID!

`; } } } - // --- Add Item from Choice Property (less common now) --- - if (itemToAdd && !gameState.character.inventory.includes(itemToAdd)) { - // Check if the item exists in itemsData before adding - if (itemsData[itemToAdd]) { - gameState.character.inventory.push(itemToAdd); - console.log("Added item via choice property:", itemToAdd); - } else { - console.warn(`Attempted to add unknown item from choice property: ${itemToAdd}`); - rollResultMessage += `

Warning: Tried to add unknown item '${itemToAdd}'.

`; - } - } - - // --- Get Target Page Data --- const targetPageData = gameData[nextPageId]; if (!targetPageData) { console.error(`Data for page ${nextPageId} not found!`); - renderPageInternal(99, gameData[99], `

Error: Page data for ${nextPageId} missing!

`); + renderPageInternal(99, gameData[99], message + `

Error: Page data for ${nextPageId} missing!

`); return; } - // --- Apply Page Consequences/Rewards --- let hpLostThisTurn = 0; - if (targetPageData.hpLoss) { - hpLostThisTurn = targetPageData.hpLoss; - gameState.character.stats.hp -= hpLostThisTurn; - console.log(`Lost ${hpLostThisTurn} HP.`); - } - if (targetPageData.reward && targetPageData.reward.hpGain) { // Check for hpGain - const hpGained = targetPageData.reward.hpGain; - gameState.character.stats.hp += hpGained; - console.log(`Gained ${hpGained} HP.`); - // Clamping to maxHP happens later + let sanityLostThisTurn = 0; + + if (targetPageData.effects) { + targetPageData.effects.forEach(effect => message += applyEffect(effect)); } - // Check for death AFTER applying HP changes for the current turn - if (gameState.character.stats.hp <= 0) { - gameState.character.stats.hp = 0; // Don't go below 0 - console.log("Player died!"); - nextPageId = 99; // Force game over page - rollResultMessage += `

You have succumbed to your injuries!${hpLostThisTurn > 0 ? ` (-${hpLostThisTurn} HP)` : ''}

`; - renderPageInternal(nextPageId, gameData[nextPageId], rollResultMessage); // Render immediately - return; // Stop further processing + if (targetPageData.hpLoss) { + hpLostThisTurn = targetPageData.hpLoss; + gameState.character.stats.hp -= hpLostThisTurn; + console.log(`Lost ${hpLostThisTurn} HP.`); + } + if (targetPageData.sanityLoss) { + sanityLostThisTurn = targetPageData.sanityLoss; + gameState.character.stats.sanity -= sanityLostThisTurn; + console.log(`Lost ${sanityLostThisTurn} Sanity.`); + message += `

Your resolve wavers... (-${sanityLostThisTurn} Sanity)

`; } - // Apply other rewards if player is still alive - if (targetPageData.reward) { - if (targetPageData.reward.xp) { + if (targetPageData.reward) { + if (targetPageData.reward.hpGain) { + const hpGained = targetPageData.reward.hpGain; + gameState.character.stats.hp += hpGained; + console.log(`Gained ${hpGained} HP.`); + } + if (targetPageData.reward.sanityGain) { + const sanityGained = targetPageData.reward.sanityGain; + gameState.character.stats.sanity += sanityGained; + console.log(`Gained ${sanityGained} Sanity.`); + message += `

You feel more composed. (+${sanityGained} Sanity)

`; + } + if (targetPageData.reward.xp) { gameState.character.xp += targetPageData.reward.xp; console.log(`Gained ${targetPageData.reward.xp} XP! Total: ${gameState.character.xp}`); - // TODO: Implement level up check here - } - if (targetPageData.reward.statIncrease) { - const stat = targetPageData.reward.statIncrease.stat; - const amount = targetPageData.reward.statIncrease.amount; - if (gameState.character.stats.hasOwnProperty(stat)) { - gameState.character.stats[stat] += amount; - console.log(`Stat ${stat} increased by ${amount}.`); - if (stat === 'constitution') recalculateMaxHp(); // Recalculate if Con changed - } - } - if (targetPageData.reward.addItem && !gameState.character.inventory.includes(targetPageData.reward.addItem)) { - const itemName = targetPageData.reward.addItem; - if (itemsData[itemName]) { // Check item exists - gameState.character.inventory.push(itemName); - console.log(`Found item via reward: ${itemName}`); - rollResultMessage += `

Item acquired: ${itemName}

`; - } else { - console.warn(`Attempted to add unknown item from reward: ${itemName}`); - rollResultMessage += `

Warning: Tried to add unknown reward item '${itemName}'.

`; - } - } + message += `

Gained ${targetPageData.reward.xp} XP.

`; + } + if (targetPageData.reward.addItem) { + const itemsToAdd = Array.isArray(targetPageData.reward.addItem) ? targetPageData.reward.addItem : [targetPageData.reward.addItem]; + itemsToAdd.forEach(itemName => { + if (itemsData[itemName]) { + if (!gameState.character.inventory.includes(itemName)) { + gameState.character.inventory.push(itemName); + console.log(`Found item via reward: ${itemName}`); + message += `

Item acquired: ${itemName}

`; + } else { + console.log(`Already had item: ${itemName}. Not adding duplicate.`); + } + } else { + console.warn(`Attempted to add unknown item from reward: ${itemName}`); + message += `

Warning: Tried to add unknown reward item '${itemName}'.

`; + } + }); + } + if (targetPageData.reward.clearEffect) { + message += clearEffect(targetPageData.reward.clearEffect); + } + } + + gameState.character.stats.hp = Math.max(0, Math.min(gameState.character.stats.hp, gameState.character.stats.maxHp)); + gameState.character.stats.sanity = Math.max(0, Math.min(gameState.character.stats.sanity, gameState.character.stats.maxSanity)); + + + if (gameState.character.stats.hp <= 0) { + console.log("Player died!"); + nextPageId = 99; + message += `

You have succumbed to your injuries!${hpLostThisTurn > 0 ? ` (-${hpLostThisTurn} HP)` : ''}

`; + renderPageInternal(nextPageId, gameData[nextPageId], message); + return; } + if (gameState.character.stats.sanity <= 0) { + console.log("Player sanity broke!"); + nextPageId = 99; + message += `

Your mind shatters under the strain!${sanityLostThisTurn > 0 ? ` (-${sanityLostThisTurn} Sanity)`: ''}

`; + renderPageInternal(nextPageId, gameData[nextPageId], message); + return; + } - // --- Update Game State & Render --- - gameState.currentPageId = nextPageId; // Set the new current page ID - recalculateMaxHp(); // Recalculate max HP based on current stats/level - gameState.character.stats.hp = Math.min(gameState.character.stats.hp, gameState.character.stats.maxHp); // Clamp HP + gameState.previousPageId = gameState.currentPageId; + gameState.currentPageId = nextPageId; console.log("Transitioning to page:", nextPageId); - renderPageInternal(nextPageId, gameData[nextPageId], rollResultMessage); // Render the next page + let pageContent = targetPageData.content || "

...

"; + if (consumedItemName) { + pageContent = pageContent.replace('{consumedItem}', consumedItemName); + } + + renderPageInternal(nextPageId, gameData[nextPageId], message, pageContent); } - function recalculateMaxHp() { - const baseHp = 10; // Assuming level 1 - const conModifier = Math.floor((gameState.character.stats.constitution - 10) / 2); - gameState.character.stats.maxHp = Math.max(1, baseHp + (conModifier * gameState.character.level)); - console.log(`Max HP recalculated: ${gameState.character.stats.maxHp}`); + function recalculateMaxHp() { + const baseHpPerLevel = 8; + const conModifier = Math.floor((getEffectiveStat('constitution') - 10) / 2); + gameState.character.stats.maxHp = 12 + (gameState.character.level * (baseHpPerLevel + conModifier)); + gameState.character.stats.maxHp = Math.max(1, gameState.character.stats.maxHp); + console.log(`Max HP recalculated: ${gameState.character.stats.maxHp}`); + gameState.character.stats.hp = Math.min(gameState.character.stats.hp, gameState.character.stats.maxHp); + } + function recalculateMaxSanity() { + const wisModifier = Math.floor((getEffectiveStat('wisdom') - 10) / 2); + gameState.character.stats.maxSanity = 10 + wisModifier; + gameState.character.stats.maxSanity = Math.max(1, gameState.character.stats.maxSanity); + console.log(`Max Sanity recalculated: ${gameState.character.stats.maxSanity}`); + gameState.character.stats.sanity = Math.min(gameState.character.stats.sanity, gameState.character.stats.maxSanity); } - function renderPageInternal(pageId, pageData, message = "") { - if (!pageData) { - console.error(`Render Error: No data for page ${pageId}! Falling back to page 99.`); - pageData = gameData[99]; // Fallback to game over page + function renderPageInternal(pageId, pageData, message = "", contentOverride = null) { + if (!pageData) { + console.error(`Render Error: No data for page ${pageId}! Falling back to page 99.`); + pageData = gameData[99]; message += `

Render Error: Data for page ${pageId} not found!

`; - pageId = 99; // Ensure we use 99 if data was missing - } + pageId = 99; + } - console.log(`Rendering page ${pageId}`); - storyTitleElement.textContent = pageData.title || "Untitled Page"; - storyContentElement.innerHTML = message + (pageData.content || "

...

"); - updateStatsDisplay(); - updateInventoryDisplay(); - choicesElement.innerHTML = ''; - - if (pageData.options && pageData.options.length > 0) { - pageData.options.forEach(option => { - const button = document.createElement('button'); - button.classList.add('choice-button'); - button.textContent = option.text; - let requirementMet = true; - let requirementText = []; // Store unmet requirements text - - // Check requirements (e.g., item needed) - if (option.requireItem && !gameState.character.inventory.includes(option.requireItem)) { - requirementMet = false; - requirementText.push(`Requires: ${option.requireItem}`); - } - // TODO: Add other requirement checks (stats, flags) here - - button.disabled = !requirementMet; - if (!requirementMet) { - button.title = requirementText.join(', '); // Show requirements on hover - } else { - // Pass page ID directly in choiceData for handleChoiceClick - const choiceData = { nextPage: option.next, addItem: option.addItem, check: option.check }; - button.onclick = () => handleChoiceClick(choiceData); - } - choicesElement.appendChild(button); - }); - } else { // No options defined - End of branch or Game Over - const button = document.createElement('button'); - button.classList.add('choice-button'); - button.textContent = pageData.gameOver ? "Restart Adventure" : "The End (Restart?)"; - // Restart button always goes to page 1, triggering the startGame logic - button.onclick = () => handleChoiceClick({ nextPage: 1 }); // Use nextPage: 1 for restart - choicesElement.appendChild(button); - if (!pageData.gameOver) { - choicesElement.insertAdjacentHTML('afterbegin', '

The path ends here.

'); - } - } - updateScene(pageData.illustration || 'default'); - } + console.log(`Rendering page ${pageId}`); + storyTitleElement.textContent = pageData.title || "Untitled Page"; + storyContentElement.innerHTML = message + (contentOverride || pageData.content || "

...

"); + + updateStatsDisplay(); + updateEffectsDisplay(); + updateInventoryDisplay(); + choicesElement.innerHTML = ''; + + if (pageData.options && pageData.options.length > 0) { + pageData.options.forEach(option => { + const button = document.createElement('button'); + button.classList.add('choice-button'); + button.textContent = option.text; + let requirementMet = true; + let requirementText = []; + + if (option.requireItem) { + if (!gameState.character.inventory.includes(option.requireItem)) { + requirementMet = false; + requirementText.push(`Requires: ${option.requireItem}`); + } + } + if (option.requireItemType && requirementMet) { + const hasItemOfType = gameState.character.inventory.some(itemName => { + const itemDef = itemsData[itemName]; + if (option.requireItemType === 'non-quest') { + return itemDef && itemDef.type !== 'quest'; + } + if (option.requireItemType === 'consumable') { + return itemDef && itemDef.type === 'consumable'; + } + return false; + }); + if (!hasItemOfType) { + requirementMet = false; + requirementText.push(`Requires: ${option.requireItemType} item`); + } + } + + button.disabled = !requirementMet; + if (!requirementMet) { + button.title = requirementText.join(', '); + } else { + const choiceData = { + nextPage: option.next, + check: option.check, + addItem: option.addItem, + requireItem: option.requireItem, + requireItemType: option.requireItemType, + consumeItem: option.consumeItem, + }; + button.onclick = () => handleChoiceClick(choiceData); + } + choicesElement.appendChild(button); + }); + } else { + const button = document.createElement('button'); + button.classList.add('choice-button'); + button.textContent = (pageData.gameOver || pageId === 99) ? "Restart Adventure" : "The End (Restart?)"; + button.onclick = () => handleChoiceClick({ nextPage: 1 }); + choicesElement.appendChild(button); + if (!pageData.gameOver && pageId !== 99) { + choicesElement.insertAdjacentHTML('afterbegin', '

The path ends here...

'); + } + } + updateScene(pageData.illustration || 'default'); + } function renderPage(pageId) { renderPageInternal(pageId, gameData[pageId]); } function updateStatsDisplay() { - const char=gameState.character; - statsElement.innerHTML = `Stats: Lvl: ${char.level} XP: ${char.xp}/${char.xpToNextLevel} HP: ${char.stats.hp}/${char.stats.maxHp} Str: ${char.stats.strength} Int: ${char.stats.intelligence} Wis: ${char.stats.wisdom} Dex: ${char.stats.dexterity} Con: ${char.stats.constitution} Cha: ${char.stats.charisma}`; + const char = gameState.character; + const hpColor = char.stats.hp / char.stats.maxHp < 0.3 ? 'style="color:#f99;"' : (char.stats.hp / char.stats.maxHp < 0.6 ? 'style="color:#fd5;"' : ''); + const sanityColor = char.stats.sanity / char.stats.maxSanity < 0.3 ? 'style="color:#c9f;"' : (char.stats.sanity / char.stats.maxSanity < 0.6 ? 'style="color:#daf;"' : ''); + + let statsHtml = `Stats: Lvl: ${char.level} XP: ${char.xp}/${char.xpToNextLevel} HP: ${char.stats.hp}/${char.stats.maxHp} San: ${char.stats.sanity}/${char.stats.maxSanity} `; + ['strength', 'intelligence', 'wisdom', 'dexterity', 'constitution', 'charisma'].forEach(stat => { + const base = char.stats[stat]; + const mod = getStatModifier(stat); + const effective = base + mod; + let display = `${effective}`; + if (mod !== 0) { + display += ` (${base}${mod > 0 ? '+' : ''}${mod})`; + } + statsHtml += `${stat.substring(0,3).toUpperCase()}: ${display} `; + }); + statsElement.innerHTML = statsHtml; } + function updateEffectsDisplay() { + let h = 'Effects: '; + if (gameState.character.effects.length === 0) { + h += 'None'; + } else { + gameState.character.effects.forEach(effect => { + const durationText = effect.duration !== undefined ? ` (${effect.duration} turns)` : ''; + let effectClass = 'effect-neutral'; + if (effect.mod) { + const isBuff = Object.values(effect.mod).some(val => val > 0); + const isDebuff = Object.values(effect.mod).some(val => val < 0); + if (isBuff && !isDebuff) effectClass = 'effect-buff'; + else if (isDebuff && !isBuff) effectClass = 'effect-debuff'; + } + const modDesc = effect.mod ? Object.entries(effect.mod).map(([key, val]) => `${key} ${val > 0 ? '+' : ''}${val}`).join(', ') : 'No stat change'; + h += `${effect.name}${durationText}`; + }); + } + effectsElement.innerHTML = h; + } + function updateInventoryDisplay() { let h='Inventory: '; if(gameState.character.inventory.length === 0){ @@ -855,137 +1407,336 @@ gameState.character.inventory.forEach(i=>{ const d=itemsData[i]||{type:'unknown',description:'???'}; const c=`item-${d.type||'unknown'}`; - h+=`${i}`; + h+=`${i}`; }); } inventoryElement.innerHTML = h; } function updateScene(illustrationKey) { - if (!scene) return; // Guard clause + if (!scene) return; + if (currentAssemblyGroup) { - scene.remove(currentAssemblyGroup); - // Basic disposal - currentAssemblyGroup.traverse(child => { - if (child.isMesh) { - child.geometry.dispose(); - // Avoid disposing shared materials - } - }); - currentAssemblyGroup = null; - } - scene.fog = null; - scene.background = new THREE.Color(0x222222); - camera.position.set(0, 2.5, 7); - camera.lookAt(0, 0.5, 0); + currentAssemblyGroup.traverse(child => { + if (child.isMesh) { + child.geometry.dispose(); + } + }); + scene.remove(currentAssemblyGroup); + currentAssemblyGroup = null; + } + currentLights.forEach(light => { + if (light !== scene.children.find(c => c.isAmbientLight)) { + scene.remove(light); + if (light.dispose) light.dispose(); + } + }); + currentLights = [scene.children.find(c => c.isAmbientLight)]; + + scene.fog = null; + currentFog = null; + + camera.position.set(0, 3, 8); + camera.lookAt(0, 1, 0); let assemblyFunction; - switch (illustrationKey) { - case 'city-gates': assemblyFunction = createCityGatesAssembly; break; - case 'weaponsmith': assemblyFunction = createWeaponsmithAssembly; break; - case 'temple': assemblyFunction = createTempleAssembly; break; - case 'resistance-meeting': assemblyFunction = createResistanceMeetingAssembly; break; - case 'shadowwood-forest': assemblyFunction = createForestAssembly; break; - case 'road-ambush': assemblyFunction = createRoadAmbushAssembly; break; - case 'forest-edge': assemblyFunction = createForestEdgeAssembly; break; - case 'prisoner-cell': assemblyFunction = createPrisonerCellAssembly; break; - case 'game-over': case 'game-over-generic': assemblyFunction = createGameOverAssembly; break; - case 'error': assemblyFunction = createErrorAssembly; break; - case 'crossroads-signpost-sunny': scene.fog = new THREE.Fog(0x87CEEB, 10, 30); scene.background = new THREE.Color(0x87CEEB); camera.position.set(0, 3, 10); camera.lookAt(0, 1, 0); assemblyFunction = createCrossroadsAssembly; break; - case 'rolling-green-hills-shepherd-distance': scene.fog = new THREE.Fog(0xA8E4A0, 15, 50); camera.position.set(0, 5, 15); camera.lookAt(0, 2, -5); assemblyFunction = createRollingHillsAssembly; break; - case 'windy-sea-cliffs-crashing-waves-path-down': scene.fog = new THREE.Fog(0x6699CC, 10, 40); scene.background = new THREE.Color(0x6699CC); camera.position.set(5, 5, 10); camera.lookAt(-2, 0, -5); assemblyFunction = createCoastalCliffsAssembly; break; - case 'dark-forest-entrance-gnarled-roots-filtered-light': scene.fog = new THREE.Fog(0x2E2E2E, 5, 20); camera.position.set(0, 2, 8); camera.lookAt(0, 1, 0); assemblyFunction = createForestEntranceAssembly; break; - case 'overgrown-forest-path-glowing-fungi-vines': scene.fog = new THREE.Fog(0x1A2F2A, 3, 15); camera.position.set(0, 1.5, 6); camera.lookAt(0, 0.5, 0); assemblyFunction = createOvergrownPathAssembly; break; - case 'forest-clearing-mossy-statue-weathered-stone': case 'forest-clearing-mossy-statue-hidden-compartment': case 'forest-clearing-mossy-statue-offering': scene.fog = new THREE.Fog(0x2E4F3A, 5, 25); camera.position.set(0, 2, 5); camera.lookAt(0, 1, 0); assemblyFunction = createClearingStatueAssembly; break; - case 'two-goblins-ambush-forest-path-spears': case 'forest-shadows-hiding-goblins-walking-past': case 'defeated-goblins-forest-path-loot': case 'blurred-motion-running-past-goblins-forest': scene.fog = new THREE.Fog(0x2E2E2E, 5, 20); camera.position.set(0, 2, 7); camera.lookAt(0, 1, 0); assemblyFunction = createGoblinAmbushAssembly; break; - case 'hidden-cove-beach-dark-cave-entrance': case 'character-fallen-at-bottom-of-cliff-path-cove': scene.fog = new THREE.Fog(0x336699, 5, 30); scene.background = new THREE.Color(0x336699); camera.position.set(0, 2, 8); camera.lookAt(0, 1, -2); assemblyFunction = createHiddenCoveAssembly; break; - case 'dark-cave-entrance-dripping-water': scene.fog = new THREE.Fog(0x1A1A1A, 2, 10); scene.background = new THREE.Color(0x1A1A1A); camera.position.set(0, 1.5, 4); camera.lookAt(0, 1, 0); assemblyFunction = createDarkCaveAssembly; break; - case 'hilltop-view-overgrown-shrine-wildflowers': scene.fog = new THREE.Fog(0xA8E4A0, 15, 50); camera.position.set(0, 5, 15); camera.lookAt(0, 2, -5); assemblyFunction = createRollingHillsAssembly; break; // Added missing case from data - case 'character-splashing-into-stream-from-log': scene.fog = new THREE.Fog(0x668866, 8, 25); camera.position.set(0, 2, 6); camera.lookAt(0, 0.5, 0); assemblyFunction = createForestAssembly; break; // Added missing case - case 'forest-stream-crossing-dappled-sunlight-stones': scene.fog = new THREE.Fog(0x668866, 8, 25); camera.position.set(0, 2, 6); camera.lookAt(0, 0.5, 0); assemblyFunction = createForestAssembly; break;// Added missing case - case 'mossy-log-bridge-over-forest-stream': scene.fog = new THREE.Fog(0x668866, 8, 25); camera.position.set(1, 2, 5); camera.lookAt(-1, 0.5, 0); assemblyFunction = createForestAssembly; break;// Added missing case - case 'forest-edge-view-rocky-foothills-distant-mountain-fortress': scene.fog = new THREE.Fog(0xAAAAAA, 10, 40); camera.position.set(0, 3, 10); camera.lookAt(0, 1, -5); assemblyFunction = createForestEdgeAssembly; break;// Added missing case - case 'climbing-rocky-foothills-path-fortress-closer': scene.fog = new THREE.Fog(0x778899, 8, 35); camera.position.set(0, 4, 9); camera.lookAt(0, 2, 0); assemblyFunction = createDefaultAssembly; break;// Added missing case - case 'zoomed-view-mountain-fortress-western-ridge': scene.fog = new THREE.Fog(0x778899, 8, 35); camera.position.set(5, 6, 12); camera.lookAt(-2, 3, -5); assemblyFunction = createDefaultAssembly; break;// Added missing case - case 'rockslide-blocking-mountain-path-boulders': scene.fog = new THREE.Fog(0x778899, 8, 35); camera.position.set(0, 4, 9); camera.lookAt(0, 2, 0); assemblyFunction = createDefaultAssembly; break;// Added missing case - case 'narrow-goat-trail-mountainside-fortress-view': scene.fog = new THREE.Fog(0x778899, 5, 30); camera.position.set(1, 3, 6); camera.lookAt(0, 2, -2); assemblyFunction = createDefaultAssembly; break;// Added missing case - case 'character-climbing-over-boulders': scene.fog = new THREE.Fog(0x778899, 8, 35); camera.position.set(0, 4, 9); camera.lookAt(0, 2, 0); assemblyFunction = createDefaultAssembly; break;// Added missing case - case 'character-slipping-on-rockslide-boulders': scene.fog = new THREE.Fog(0x778899, 8, 35); camera.position.set(0, 4, 9); camera.lookAt(0, 2, 0); assemblyFunction = createDefaultAssembly; break;// Added missing case - case 'rough-detour-path-around-rockslide': scene.fog = new THREE.Fog(0x778899, 8, 35); camera.position.set(0, 4, 9); camera.lookAt(0, 2, 0); assemblyFunction = createDefaultAssembly; break;// Added missing case - case 'narrow-windy-mountain-ridge-path': scene.fog = new THREE.Fog(0x8899AA, 6, 25); camera.position.set(2, 5, 7); camera.lookAt(0, 3, -3); assemblyFunction = createDefaultAssembly; break;// Added missing case - case 'approaching-dark-fortress-walls-guards': scene.fog = new THREE.Fog(0x444455, 5, 20); camera.position.set(0, 3, 8); camera.lookAt(0, 2, 0); assemblyFunction = createDefaultAssembly; break;// Added missing case - case 'character-falling-off-windy-ridge': scene.fog = new THREE.Fog(0x8899AA, 6, 25); camera.position.set(2, 5, 7); camera.lookAt(0, 3, -3); assemblyFunction = createDefaultAssembly; break;// Added missing case - case 'scanning-sea-cliffs-no-other-paths-visible': scene.fog = new THREE.Fog(0x6699CC, 10, 40); scene.background = new THREE.Color(0x6699CC); camera.position.set(5, 5, 10); camera.lookAt(-2, 0, -5); assemblyFunction = createCoastalCliffsAssembly; break;// Added missing case - case 'close-up-handholds-carved-in-cliff-face': scene.fog = new THREE.Fog(0x6699CC, 10, 40); scene.background = new THREE.Color(0x6699CC); camera.position.set(5, 5, 10); camera.lookAt(-2, 0, -5); assemblyFunction = createCoastalCliffsAssembly; break;// Added missing case - case 'overgrown-stone-shrine-wildflowers-close': scene.fog = new THREE.Fog(0xA8E4A0, 15, 50); camera.position.set(1, 2, 4); camera.lookAt(0, 0.5, 0); assemblyFunction = createRollingHillsAssembly; break;// Added missing case - case 'rocky-badlands-cracked-earth-harsh-sun': scene.fog = new THREE.Fog(0xD2B48C, 15, 40); scene.background = new THREE.Color(0xCD853F); camera.position.set(0, 3, 12); camera.lookAt(0, 1, 0); assemblyFunction = createDefaultAssembly; break;// Added missing case - case 'pushing-through-forest-undergrowth': scene.fog = new THREE.Fog(0x2E2E2E, 5, 20); camera.position.set(0, 1.5, 5); camera.lookAt(0, 1, 0); assemblyFunction = createForestAssembly; break;// Added missing case - case 'narrow-game-trail-forest-rope-bridge-ravine': scene.fog = new THREE.Fog(0x2E2E2E, 5, 20); camera.position.set(2, 3, 6); camera.lookAt(0, -1, -2); assemblyFunction = createForestAssembly; break;// Added missing case - case 'character-crossing-rope-bridge-safely': scene.fog = new THREE.Fog(0x2E2E2E, 5, 20); camera.position.set(2, 3, 6); camera.lookAt(0, -1, -2); assemblyFunction = createForestAssembly; break;// Added missing case - case 'rope-bridge-snapping-character-falling': scene.fog = new THREE.Fog(0x2E2E2E, 5, 20); camera.position.set(2, 3, 6); camera.lookAt(0, -1, -2); assemblyFunction = createForestAssembly; break;// Added missing case - case 'fallen-log-crossing-ravine': scene.fog = new THREE.Fog(0x2E2E2E, 5, 20); camera.position.set(2, 3, 6); camera.lookAt(0, -1, -2); assemblyFunction = createForestAssembly; break;// Added missing case + let fogSettings = { type: 'none' }; + let background = new THREE.Color(0x1a1a1a); + switch (illustrationKey) { + case 'crossroads-signpost-sunny': + assemblyFunction = createCrossroadsAssembly; + fogSettings = { type: 'linear', color: 0xB0E0E6, near: 10, far: 35 }; + background = new THREE.Color(0xADD8E6); + camera.position.set(0, 3, 10); + camera.lookAt(0, 1, 0); + break; + case 'rolling-green-hills-shepherd-distance': + case 'rolling-green-hills-shepherd-close': + assemblyFunction = createRollingHillsAssembly; + fogSettings = { type: 'exp2', color: 0xD0F0C0, density: 0.02 }; + background = new THREE.Color(0xACE1AF); + camera.position.set(0, 5, 18); + camera.lookAt(0, 1, -5); + break; + case 'windy-sea-cliffs-crashing-waves-path-down': + case 'scanning-sea-cliffs-no-other-paths-visible': + case 'close-up-handholds-carved-in-cliff-face': + assemblyFunction = createCoastalCliffsAssembly; + fogSettings = { type: 'linear', color: 0x778899, near: 5, far: 50 }; + background = new THREE.Color(0x87CEFA); + camera.position.set(6, 6, 12); + camera.lookAt(-2, 1, -5); + break; + case 'dark-forest-entrance-gnarled-roots-filtered-light': + assemblyFunction = createForestEntranceAssembly; + fogSettings = { type: 'exp2', color: 0x1A2A1A, density: 0.08 }; + background = new THREE.Color(0x112211); + camera.position.set(0, 2, 7); + camera.lookAt(0, 1, 0); + break; + case 'overgrown-forest-path-glowing-fungi-vines': + case 'two-goblins-ambush-forest-path-spears': + case 'forest-shadows-hiding-goblins-walking-past': + case 'defeated-goblins-forest-path-loot': + case 'blurred-motion-running-past-goblins-forest': + case 'forest-path-scared-goblins-fleeing': + assemblyFunction = createOvergrownPathAssembly; + if (illustrationKey.includes('goblin')) { + assemblyFunction = createGoblinAmbushAssembly; + } + fogSettings = { type: 'exp2', color: 0x182820, density: 0.1 }; + background = new THREE.Color(0x0a1810); + camera.position.set(0, 1.8, 6); + camera.lookAt(0, 0.8, 0); + break; + case 'forest-clearing-mossy-statue-weathered-stone': + case 'forest-clearing-mossy-statue-hidden-compartment': + case 'forest-clearing-mossy-statue-offering': + assemblyFunction = createClearingStatueAssembly; + fogSettings = { type: 'linear', color: 0x3A5F3A, near: 5, far: 30 }; + background = new THREE.Color(0x2A4F2A); + camera.position.set(0, 2.5, 7); + camera.lookAt(0, 1, 0); + break; + case 'hidden-cove-beach-dark-cave-entrance': + case 'character-fallen-at-bottom-of-cliff-path-cove': + assemblyFunction = createHiddenCoveAssembly; + fogSettings = { type: 'linear', color: 0x6688AA, near: 8, far: 40 }; + background = new THREE.Color(0x7799BB); + camera.position.set(0, 3, 10); + camera.lookAt(0, 1, -2); + break; + case 'dark-cave-entrance-dripping-water': + assemblyFunction = createDarkCaveAssembly; + fogSettings = { type: 'exp2', color: 0x050508, density: 0.15 }; + background = new THREE.Color(0x000000); + camera.position.set(0, 1.5, 5); + camera.lookAt(0, 1, 0); + break; + case 'game-over': case 'game-over-generic': + assemblyFunction = createGameOverAssembly; + fogSettings = { type: 'exp2', color: 0x330000, density: 0.05 }; + background = new THREE.Color(0x220000); + break; + case 'error': + assemblyFunction = createErrorAssembly; + fogSettings = { type: 'linear', color: 0x886600, near: 2, far: 15 }; + background = new THREE.Color(0x553300); + break; + case 'hilltop-view-overgrown-shrine-wildflowers': assemblyFunction = createRollingHillsAssembly; fogSettings = { type: 'exp2', color: 0xD0F0C0, density: 0.02 }; background = new THREE.Color(0xACE1AF); camera.position.set(0, 5, 15); camera.lookAt(0, 1, -5); break; + case 'character-splashing-into-stream-from-log': + case 'forest-stream-crossing-dappled-sunlight-stones': + case 'mossy-log-bridge-over-forest-stream': assemblyFunction = createForestAssembly; fogSettings = { type: 'exp2', color: 0x668866, density: 0.06 }; background = new THREE.Color(0x557755); camera.position.set(0, 2, 6); camera.lookAt(0, 0.5, 0); break; + case 'forest-edge-view-rocky-foothills-distant-mountain-fortress': assemblyFunction = createForestEdgeAssembly; fogSettings = { type: 'linear', color: 0xAAAAAA, near: 10, far: 40 }; background = new THREE.Color(0xB0B0B0); camera.position.set(0, 3, 10); camera.lookAt(0, 1, -5); break; + case 'climbing-rocky-foothills-path-fortress-closer': + case 'zoomed-view-mountain-fortress-western-ridge': + case 'rockslide-blocking-mountain-path-boulders': + case 'narrow-goat-trail-mountainside-fortress-view': + case 'character-climbing-over-boulders': + case 'character-slipping-on-rockslide-boulders': + case 'rough-detour-path-around-rockslide': + case 'narrow-windy-mountain-ridge-path': + case 'approaching-dark-fortress-walls-guards': + case 'character-falling-off-windy-ridge': + case 'rocky-badlands-cracked-earth-harsh-sun': + case 'pushing-through-forest-undergrowth': + case 'narrow-game-trail-forest-rope-bridge-ravine': + case 'character-crossing-rope-bridge-safely': + case 'rope-bridge-snapping-character-falling': + case 'fallen-log-crossing-ravine': + assemblyFunction = createDefaultAssembly; + console.warn(`Using default assembly for illustration key: ${illustrationKey}`); + fogSettings = { type: 'linear', color: 0xAAAAAA, near: 5, far: 25 }; + background = new THREE.Color(0x999999); + break; default: - console.warn(`Unknown illustration key: "${illustrationKey}". Using default.`); - assemblyFunction = createDefaultAssembly; break; + console.warn(`Unknown illustration key: "${illustrationKey}". Using default assembly.`); + assemblyFunction = createDefaultAssembly; + fogSettings = { type: 'linear', color: 0xAAAAAA, near: 5, far: 25 }; + background = new THREE.Color(0x999999); + break; } + + if (fogSettings.type === 'linear') { + scene.fog = new THREE.Fog(fogSettings.color, fogSettings.near, fogSettings.far); + } else if (fogSettings.type === 'exp2') { + scene.fog = new THREE.FogExp2(fogSettings.color, fogSettings.density); + scene.fog.userData = { baseDensity: fogSettings.density }; + } + currentFog = scene.fog; + scene.background = background; + + try { currentAssemblyGroup = assemblyFunction(); - if (currentAssemblyGroup && currentAssemblyGroup.isGroup) { // Check it's a group - scene.add(currentAssemblyGroup); - adjustLighting(illustrationKey); - } else { - throw new Error("Assembly function failed to return a valid THREE.Group"); - } + if (currentAssemblyGroup && currentAssemblyGroup.isGroup) { + scene.add(currentAssemblyGroup); + adjustLighting(illustrationKey); + } else { + throw new Error("Assembly function failed to return a valid THREE.Group"); + } } catch (error) { console.error(`Error creating assembly for ${illustrationKey}:`, error); - if (currentAssemblyGroup) { scene.remove(currentAssemblyGroup); } // Try cleanup + if (currentAssemblyGroup) { scene.remove(currentAssemblyGroup); } currentAssemblyGroup = createErrorAssembly(); scene.add(currentAssemblyGroup); - adjustLighting('error'); + adjustLighting('error'); } } - function adjustLighting(illustrationKey) { // Unchanged + function adjustLighting(illustrationKey) { if (!scene) return; - scene.children.forEach(child => { if (child.isLight && child !== scene.children.find(c => c.isAmbientLight)) { scene.remove(child); } }); - const ambient = scene.children.find(c => c.isAmbientLight); - if (!ambient) { console.warn("Ambient light missing!"); return; } // Added guard - let directionalLight; + const ambient = currentLights[0]; + if (!ambient || !ambient.isAmbientLight) { + console.error("Ambient light not found or invalid!"); + if (!ambient) { + const newAmbient = new THREE.AmbientLight(0xffffff, 0.2); + scene.add(newAmbient); + currentLights[0] = newAmbient; + console.warn("Recreated missing ambient light."); + } + return; + } + + let dirLight = null; + let hemiLight = null; + + ambient.intensity = 0.2; + let dirIntensity = 0.8; + let dirColor = 0xffffff; + let dirPosition = new THREE.Vector3(10, 15, 8); + let hemiSkyColor = 0xB1E1FF; + let hemiGroundColor = 0xB97A20; + let hemiIntensity = 0.3; + + switch (illustrationKey) { - case 'crossroads-signpost-sunny': ambient.intensity = 0.8; directionalLight = new THREE.DirectionalLight(0xFFF8E1, 1.5); directionalLight.position.set(10, 15, 10); break; - case 'dark-forest-entrance-gnarled-roots-filtered-light': case 'overgrown-forest-path-glowing-fungi-vines': ambient.intensity = 0.3; directionalLight = new THREE.DirectionalLight(0xA8E4A0, 0.6); directionalLight.position.set(5, 10, 5); break; - case 'dark-cave-entrance-dripping-water': ambient.intensity = 0.1; directionalLight = new THREE.DirectionalLight(0x666666, 0.2); directionalLight.position.set(2, 5, 2); break; - default: ambient.intensity = 0.5; directionalLight = new THREE.DirectionalLight(0xffffff, 1.2); directionalLight.position.set(8, 15, 10); + case 'crossroads-signpost-sunny': + ambient.intensity = 0.4; + dirIntensity = 1.2; + dirColor = 0xFFF8DC; + dirPosition = new THREE.Vector3(15, 20, 10); + hemiSkyColor = 0xFFE4B5; + hemiGroundColor = 0xCD853F; + hemiIntensity = 0.5; + break; + + case 'dark-forest-entrance-gnarled-roots-filtered-light': + case 'overgrown-forest-path-glowing-fungi-vines': + case 'forest-clearing-mossy-statue-weathered-stone': + ambient.intensity = 0.15; + dirIntensity = 0.5; + dirColor = 0x98FB98; + dirPosition = new THREE.Vector3(5, 10, 5); + dirLight = new THREE.DirectionalLight(dirColor, dirIntensity); + dirLight.shadow.bias = -0.001; + dirLight.position.copy(dirPosition); + hemiSkyColor = 0xADD8E6; + hemiGroundColor = 0x4F4F2F; + hemiIntensity = 0.4; + break; + case 'two-goblins-ambush-forest-path-spears': + ambient.intensity = 0.1; + dirIntensity = 0.4; + dirColor = 0x9ACD32; + dirPosition = new THREE.Vector3(3, 8, 6); + hemiSkyColor = 0xA0B0A0; + hemiGroundColor = 0x404020; + hemiIntensity = 0.3; + break; + + case 'dark-cave-entrance-dripping-water': + ambient.intensity = 0.05; + dirIntensity = 0; + hemiSkyColor = 0x445577; + hemiGroundColor = 0x333344; + hemiIntensity = 0.2; + break; + + case 'game-over': case 'game-over-generic': + ambient.intensity = 0.1; + dirIntensity = 0.5; + dirColor = 0xFF6347; + dirPosition = new THREE.Vector3(0, 10, -5); + hemiSkyColor = 0x8B0000; + hemiGroundColor = 0x400000; + hemiIntensity = 0.4; + break; + case 'error': + ambient.intensity = 0.2; + dirIntensity = 0.7; + dirColor = 0xFFA500; + hemiSkyColor = 0xFFD700; + hemiGroundColor = 0x8B4513; + hemiIntensity = 0.5; + break; + + default: + ambient.intensity = 0.3; + dirIntensity = 1.0; + dirColor = 0xffffff; + dirPosition = new THREE.Vector3(8, 15, 10); + hemiSkyColor = 0xB1E1FF; + hemiGroundColor = 0xB97A20; + hemiIntensity = 0.4; } - if (!directionalLight) { // Ensure light is created - console.warn("Directional light not set for key:", illustrationKey, ". Using default."); - ambient.intensity = 0.5; directionalLight = new THREE.DirectionalLight(0xffffff, 1.2); directionalLight.position.set(8, 15, 10); + + if (dirIntensity > 0 && !dirLight) { + dirLight = new THREE.DirectionalLight(dirColor, dirIntensity); + dirLight.position.copy(dirPosition); } - directionalLight.castShadow = true; - directionalLight.shadow.mapSize.set(1024, 1024); - directionalLight.shadow.camera.near = 0.5; directionalLight.shadow.camera.far = 50; - directionalLight.shadow.camera.left = -15; directionalLight.shadow.camera.right = 15; - directionalLight.shadow.camera.top = 15; directionalLight.shadow.camera.bottom = -15; - scene.add(directionalLight); + if(dirLight){ + dirLight.castShadow = true; + dirLight.shadow.mapSize.width = 1024; + dirLight.shadow.mapSize.height = 1024; + dirLight.shadow.camera.near = 0.5; + dirLight.shadow.camera.far = 50; + const shadowBounds = 20; + dirLight.shadow.camera.left = -shadowBounds; + dirLight.shadow.camera.right = shadowBounds; + dirLight.shadow.camera.top = shadowBounds; + dirLight.shadow.camera.bottom = -shadowBounds; + dirLight.shadow.bias = -0.0005; + + scene.add(dirLight); + currentLights.push(dirLight); + + } + + if (hemiIntensity > 0) { + hemiLight = new THREE.HemisphereLight(hemiSkyColor, hemiGroundColor, hemiIntensity); + scene.add(hemiLight); + currentLights.push(hemiLight); + } + + currentAssemblyGroup?.traverse(child => { + if (child.isPointLight) { + currentLights.push(child); + child.castShadow = true; + child.shadow.mapSize.width = 512; + child.shadow.mapSize.height = 512; + child.shadow.bias = -0.005; + } + }); + } - // Initialization document.addEventListener('DOMContentLoaded', () => { - console.log("DOM Ready."); + console.log("DOM Ready - Initializing Enhanced Adventure."); try { - initThreeJS(); // Initialize Three.js first - if (!scene || !camera || !renderer) { // Check if init failed - throw new Error("Three.js initialization failed."); + initThreeJS(); + if (!scene || !camera || !renderer) { + throw new Error("Three.js core component initialization failed."); } - startGame(); // Start game logic + startGame(); console.log("Game started."); } catch (error) { console.error("Initialization failed:", error); storyTitleElement.textContent = "Error During Initialization"; storyContentElement.innerHTML = `

Could not start the adventure. Please check the developer console (F12) for more details.

${error.stack || error}
`; - choicesElement.innerHTML = ''; // Clear choices on error - if(sceneContainer) sceneContainer.innerHTML = ''; // Clear scene on error + choicesElement.innerHTML = ''; + if(sceneContainer) sceneContainer.innerHTML = '

3D Scene Failed to Load

'; } });