Spaces:
Running
Running
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>World Grid + Interaction</title> | |
| <style> | |
| /* Styles from previous version (unchanged) */ | |
| body { font-family: 'Courier New', monospace; background-color: #111; color: #eee; margin: 0; padding: 0; overflow: hidden; display: flex; flex-direction: column; height: 100vh; } | |
| #game-container { display: flex; flex-grow: 1; overflow: hidden; } | |
| #scene-container { flex-grow: 3; position: relative; border-right: 2px solid #444; min-width: 250px; background-color: #000; height: 100%; box-sizing: border-box; overflow: hidden; cursor: crosshair; } /* Changed cursor */ | |
| #ui-container { flex-grow: 2; padding: 25px; overflow-y: auto; background-color: #2b2b2b; min-width: 320px; height: 100%; box-sizing: border-box; display: flex; flex-direction: column; } | |
| #scene-container canvas { display: block; } | |
| #story-title { color: #f0c060; margin: 0 0 15px 0; padding-bottom: 10px; border-bottom: 1px solid #555; font-size: 1.6em; text-shadow: 1px 1px 1px #000; } | |
| #story-content { margin-bottom: 25px; line-height: 1.7; flex-grow: 1; font-size: 1.1em; } | |
| #stats-inventory-container { margin-bottom: 25px; padding: 15px; border: 1px solid #444; border-radius: 4px; background-color: #333; font-size: 0.95em; } | |
| #stats-display, #inventory-display { margin-bottom: 10px; line-height: 1.8; } | |
| #stats-display span, #inventory-display .item-tag { display: inline-block; background-color: #484848; padding: 3px 9px; border-radius: 15px; margin: 0 8px 5px 0; border: 1px solid #6a6a6a; white-space: nowrap; box-shadow: inset 0 1px 2px rgba(0,0,0,0.3); } | |
| #inventory-display .item-tag { cursor: pointer; transition: background-color 0.2s, border-color 0.2s; } /* Make clickable */ | |
| #inventory-display .item-tag:hover { background-color: #6a6a6a; } | |
| #inventory-display .item-tag.placing { background-color: #a07030; border-color: #c89040; color: #fff; box-shadow: 0 0 5px #ffc040;} /* Highlight placing item */ | |
| #stats-display strong, #inventory-display strong { color: #ccc; margin-right: 6px; } | |
| #inventory-display em { color: #888; font-style: normal; } | |
| .item-quest { background-color: #666030; border-color: #999048;} | |
| .item-weapon { background-color: #663030; border-color: #994848;} | |
| .item-armor { background-color: #306630; border-color: #489948;} | |
| .item-consumable { background-color: #664430; border-color: #996648;} | |
| .item-unknown { background-color: #555; border-color: #777;} | |
| #choices-container { margin-top: auto; padding-top: 20px; border-top: 1px solid #555; } | |
| #choices-container h3 { margin-top: 0; margin-bottom: 12px; color: #ccc; font-size: 1.1em; } | |
| #choices { display: flex; flex-direction: column; gap: 12px; } | |
| .choice-button { display: block; width: 100%; padding: 12px 15px; margin-bottom: 0; background-color: #555; color: #eee; border: 1px solid #777; border-radius: 4px; cursor: pointer; text-align: left; font-family: 'Courier New', monospace; font-size: 1.05em; transition: background-color 0.2s, border-color 0.2s, box-shadow 0.1s; box-sizing: border-box; } | |
| .choice-button:hover:not(:disabled) { background-color: #e0b050; color: #111; border-color: #c89040; box-shadow: 0 0 5px rgba(255, 200, 100, 0.5); } | |
| .choice-button:disabled { background-color: #404040; color: #777; cursor: not-allowed; border-color: #555; opacity: 0.7; } | |
| .message { padding: 8px 12px; margin-bottom: 1em; border-left-width: 3px; border-left-style: solid; font-size: 0.95em; background-color: rgba(255, 255, 255, 0.05); border-color: #666; color: #aaa;} | |
| .message-failure { color: #f88; border-left-color: #a44; } | |
| .message-item { color: #8bf; border-left-color: #46a; } | |
| #action-info { position: absolute; bottom: 10px; left: 10px; background-color: rgba(0,0,0,0.7); color: #ffcc66; padding: 5px 10px; border-radius: 3px; font-size: 0.9em; display: block; z-index: 10;} | |
| </style> | |
| </head> | |
| <body> | |
| <div id="game-container"> | |
| <div id="scene-container"> | |
| <div id="action-info">Initializing...</div> | |
| </div> | |
| <div id="ui-container"> | |
| <h2 id="story-title">Initializing...</h2> | |
| <div id="story-content"><p>Loading assets...</p></div> | |
| <div id="stats-inventory-container"> | |
| <div id="stats-display">HP: ?/? | XP: ?</div> | |
| <div id="inventory-display">Inventory: Empty</div> | |
| </div> | |
| <div id="choices-container"> | |
| <h3>What will you do?</h3> | |
| <div id="choices">Loading...</div> | |
| </div> | |
| </div> | |
| </div> | |
| <script type="importmap"> | |
| { "imports": { | |
| "three": "https://unpkg.com/[email protected]/build/three.module.js", | |
| "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/" | |
| }} | |
| </script> | |
| <script type="module"> | |
| import * as THREE from 'three'; | |
| import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; // Re-enabled controls | |
| console.log("Script module execution started."); | |
| const sceneContainer = document.getElementById('scene-container'); | |
| const storyTitleElement = document.getElementById('story-title'); | |
| const storyContentElement = document.getElementById('story-content'); | |
| const choicesElement = document.getElementById('choices'); | |
| const statsElement = document.getElementById('stats-display'); | |
| const inventoryElement = document.getElementById('inventory-display'); | |
| const actionInfoElement = document.getElementById('action-info'); | |
| console.log("DOM elements obtained."); | |
| let scene, camera, renderer, clock, controls, raycaster, mouse; // Added controls back | |
| let worldGroup = null; | |
| let zoneGroups = {}; | |
| let currentMessage = ""; | |
| let currentLights = []; | |
| let currentPlacingItem = null; // Added back for placement mode | |
| const MAT = { | |
| stone: new THREE.MeshStandardMaterial({ color: 0x777788, roughness: 0.85 }), | |
| wood: new THREE.MeshStandardMaterial({ color: 0x9F6633, roughness: 0.75 }), | |
| leaf: new THREE.MeshStandardMaterial({ color: 0x3E9B4E, roughness: 0.6, side: THREE.DoubleSide }), | |
| ground: new THREE.MeshStandardMaterial({ color: 0x556B2F, roughness: 0.95 }), | |
| dirt: new THREE.MeshStandardMaterial({ color: 0x8B5E3C, roughness: 0.9 }), | |
| grass: new THREE.MeshStandardMaterial({ color: 0x4CB781, roughness: 0.85 }), | |
| water: new THREE.MeshStandardMaterial({ color: 0x4682B4, roughness: 0.3, transparent: true, opacity: 0.85 }), | |
| simple: new THREE.MeshStandardMaterial({ color: 0xaaaaaa, roughness: 0.8 }), | |
| }; | |
| let gameState = {}; | |
| const itemsData = { | |
| "Rusty Sword": {type:"weapon", description:"Old but sharp.", baseDamage: 3}, | |
| "Rock": {type:"unknown", description:"A simple rock."}, | |
| "Torch": {type:"consumable", description:"Provides light."}, | |
| "Cave Crystal": {type:"unknown", description:"A faintly glowing crystal shard."} // Example item | |
| }; | |
| const zoneCreators = {}; | |
| const MAP_ROWS = 3; | |
| const MAP_COLS = 4; | |
| function initThreeJS() { | |
| console.log("initThreeJS started."); | |
| try { | |
| scene = new THREE.Scene(); | |
| scene.background = new THREE.Color(0x1a1a1a); | |
| clock = new THREE.Clock(); | |
| raycaster = new THREE.Raycaster(); // Initialize raycaster | |
| mouse = new THREE.Vector2(); // Initialize mouse vector | |
| worldGroup = new THREE.Group(); | |
| scene.add(worldGroup); | |
| console.log("Scene and worldGroup created."); | |
| const width = sceneContainer.clientWidth || 300; | |
| const height = sceneContainer.clientHeight || 200; | |
| console.log(`Renderer dimensions: ${width}x${height}`); | |
| camera = new THREE.PerspectiveCamera(60, width / height, 0.1, 1000); | |
| camera.position.set(0, 6, 12); | |
| camera.lookAt(0, 1, 0); | |
| console.log("Camera created."); | |
| renderer = new THREE.WebGLRenderer({ antialias: true }); | |
| renderer.setSize(width, height); | |
| renderer.shadowMap.enabled = true; | |
| renderer.shadowMap.type = THREE.PCFSoftShadowMap; | |
| sceneContainer.appendChild(renderer.domElement); | |
| console.log("Renderer created and appended."); | |
| controls = new OrbitControls(camera, renderer.domElement); // Initialize controls | |
| controls.enableDamping = true; | |
| controls.dampingFactor = 0.1; | |
| controls.target.set(0, 1, 0); | |
| controls.maxPolarAngle = Math.PI / 2 - 0.05; | |
| console.log("OrbitControls initialized."); | |
| window.addEventListener('resize', onWindowResize, false); | |
| renderer.domElement.addEventListener('mousemove', onMouseMove, false); // Added back | |
| renderer.domElement.addEventListener('click', onMouseClick, false); // Added back | |
| setTimeout(onWindowResize, 100); | |
| animate(); | |
| console.log("initThreeJS finished successfully."); | |
| } catch (error) { | |
| console.error("Error during initThreeJS:", error); | |
| throw error; | |
| } | |
| } | |
| function onWindowResize() { | |
| console.log("onWindowResize called."); | |
| if (!renderer || !camera || !sceneContainer) return; | |
| const width = sceneContainer.clientWidth || 300; | |
| const height = sceneContainer.clientHeight || 200; | |
| if (width > 0 && height > 0) { | |
| camera.aspect = width / height; | |
| camera.updateProjectionMatrix(); | |
| renderer.setSize(width, height); | |
| console.log(`Resized renderer to ${width}x${height}`); | |
| } else { | |
| console.warn("Skipping resize, zero dimensions detected."); | |
| } | |
| } | |
| function onMouseMove( event ) { // Added back | |
| const rect = renderer.domElement.getBoundingClientRect(); | |
| mouse.x = ( (event.clientX - rect.left) / rect.width ) * 2 - 1; | |
| mouse.y = - ( (event.clientY - rect.top) / rect.height ) * 2 + 1; | |
| } | |
| function onMouseClick( event ) { // Added back | |
| console.log(`Mouse click detected. Placing item: ${currentPlacingItem}`); | |
| if (currentPlacingItem) { | |
| placeItem(); | |
| } else { | |
| pickupItem(); | |
| } | |
| } | |
| let frameCount = 0; | |
| function animate() { | |
| frameCount++; | |
| // if(frameCount % 300 === 0) console.log("Animate loop running..."); // Reduce logging frequency | |
| requestAnimationFrame(animate); | |
| controls.update(); // Update controls | |
| if (renderer && scene && camera) renderer.render(scene, camera); | |
| } | |
| function createMesh(geometry, material, pos = {x:0,y:0,z:0}, rot = {x:0,y:0,z:0}, scale = {x:1,y:1,z:1}) { | |
| const mesh = new THREE.Mesh(geometry, material); | |
| mesh.position.set(pos.x, pos.y, pos.z); | |
| mesh.rotation.set(rot.x, rot.y, rot.z); | |
| mesh.scale.set(scale.x, scale.y, scale.z); | |
| mesh.castShadow = true; mesh.receiveShadow = true; | |
| return mesh; | |
| } | |
| function createGround(material = MAT.ground, size = 20) { | |
| const geo = new THREE.PlaneGeometry(size, size); | |
| const ground = new THREE.Mesh(geo, material); | |
| ground.rotation.x = -Math.PI / 2; ground.position.y = 0; | |
| ground.receiveShadow = true; ground.castShadow = false; | |
| ground.userData.isGround = true; | |
| return ground; | |
| } | |
| function setupLighting(type = 'default') { | |
| console.log(`Setting up lighting for type: ${type}`); | |
| currentLights.forEach(light => { | |
| if (light && light.parent) light.parent.remove(light); | |
| if (light && scene.children.includes(light)) scene.remove(light); | |
| }); | |
| currentLights = []; | |
| let ambientIntensity = 0.5; | |
| let dirIntensity = 1.0; | |
| let dirColor = 0xffffff; | |
| let dirPosition = new THREE.Vector3(10, 15, 7); | |
| if (type === 'forest') { ambientIntensity = 0.4; dirIntensity = 0.8; dirColor = 0xccffcc; dirPosition = new THREE.Vector3(5, 10, 5); } | |
| if (type === 'cave') { ambientIntensity = 0.2; dirIntensity = 0; } | |
| if (type === 'ruins') { ambientIntensity = 0.4; dirIntensity = 0.7; dirColor = 0xaaaaff; dirPosition = new THREE.Vector3(-8, 12, -5); } | |
| const ambientLight = new THREE.AmbientLight(0xffffff, ambientIntensity); | |
| scene.add(ambientLight); | |
| currentLights.push(ambientLight); | |
| if (dirIntensity > 0) { | |
| const directionalLight = new THREE.DirectionalLight(dirColor, dirIntensity); | |
| directionalLight.position.copy(dirPosition); | |
| directionalLight.castShadow = true; | |
| directionalLight.shadow.mapSize.set(1024, 1024); | |
| directionalLight.shadow.camera.near = 0.5; directionalLight.shadow.camera.far = 50; | |
| const sb = 20; | |
| directionalLight.shadow.camera.left = -sb; directionalLight.shadow.camera.right = sb; | |
| directionalLight.shadow.camera.top = sb; directionalLight.shadow.camera.bottom = -sb; | |
| directionalLight.shadow.bias = -0.0005; | |
| scene.add(directionalLight); | |
| currentLights.push(directionalLight); | |
| } | |
| if (type === 'cave') { // Add cave light specifically here, track it | |
| const ptLight = new THREE.PointLight(0xffaa55, 1.5, 12, 1); | |
| ptLight.position.set(0, 3, 0); // Position relative to zone origin | |
| ptLight.castShadow = true; | |
| ptLight.shadow.mapSize.set(512, 512); | |
| currentLights.push(ptLight); // Add to list, will be added to group in transition | |
| } | |
| console.log(`Lighting setup complete. Lights tracked: ${currentLights.length}`); | |
| } | |
| // --- Zone Creation Functions --- | |
| function createFieldZone(zoneId) { | |
| console.log(`Creating zone: ${zoneId} (Field)`); | |
| const group = new THREE.Group(); | |
| group.add(createGround(MAT.grass, 30)); | |
| const rockGeo = new THREE.IcosahedronGeometry(0.8, 0); | |
| for(let i=0; i<5; i++) { | |
| const rock = createMesh(rockGeo, MAT.stone, {x: (Math.random()-0.5)*25, y:0.4, z: (Math.random()-0.5)*25}); | |
| rock.userData = { isPickupable: true, itemName: "Rock", description: "A field rock." }; // Make rocks pickupable | |
| group.add(rock); | |
| } | |
| group.visible = false; | |
| return { group, lighting: 'default', title: "Open Field", entryText: `You are in ${zoneId}. It's grassy. Some rocks litter the ground.`, options: [], zoneId: zoneId }; | |
| } | |
| function createForestZone(zoneId) { | |
| console.log(`Creating zone: ${zoneId} (Forest)`); | |
| const group = new THREE.Group(); | |
| group.add(createGround(MAT.ground, 30)); | |
| const trunkGeo = new THREE.CylinderGeometry(0.2, 0.3, 4, 8); | |
| const leafGeo = new THREE.SphereGeometry(1.5, 8, 6); | |
| for(let i=0; i<25; i++) { | |
| const x = (Math.random() - 0.5) * 28; | |
| const z = (Math.random() - 0.5) * 28; | |
| if(Math.sqrt(x*x+z*z) < 1) continue; | |
| const tree = new THREE.Group(); | |
| const trunk = createMesh(trunkGeo, MAT.wood, {y: 2}); | |
| const leaves = createMesh(leafGeo, MAT.leaf, {y: 4.5}); | |
| tree.add(trunk); tree.add(leaves); | |
| tree.position.set(x, 0, z); | |
| tree.rotation.y = Math.random() * Math.PI * 2; | |
| group.add(tree); | |
| } | |
| const swordGeo = new THREE.BoxGeometry(0.1, 1, 0.05); | |
| const sword = createMesh(swordGeo, MAT.metal, {x: 3, y: 0.5, z: 4}, {z: Math.PI / 4}); | |
| sword.userData = { isPickupable: true, itemName: "Rusty Sword", description: "An old sword sticking out of the ground."}; | |
| group.add(sword); // Add pickupable sword | |
| group.visible = false; | |
| return { group, lighting: 'forest', title: "Dark Forest", entryText: "Sunlight is sparse beneath the thick canopy.", options: [], zoneId: zoneId }; | |
| } | |
| function createCaveZone(zoneId) { | |
| console.log(`Creating zone: ${zoneId} (Cave)`); | |
| const group = new THREE.Group(); | |
| group.add(createGround(MAT.stone.clone().set({color: 0x555560}), 18)); | |
| const wallGeo = new THREE.SphereGeometry(12, 32, 16, 0, Math.PI*2, 0, Math.PI*0.7); | |
| const walls = createMesh(wallGeo, MAT.stone, {y: 4}); | |
| walls.material.side = THREE.BackSide; | |
| group.add(walls); | |
| const coneGeo = new THREE.ConeGeometry(0.2, 1.0, 8); | |
| for(let i=0; i<15; i++){ | |
| const st = createMesh(coneGeo, MAT.stone, {x: (Math.random()-0.5)*16, y: 6 + Math.random()*2, z: (Math.random()-0.5)*16}, {x:Math.PI}); | |
| group.add(st); | |
| } | |
| const crystalGeo = new THREE.IcosahedronGeometry(0.3, 0); | |
| const crystal = createMesh(crystalGeo, MAT.simple.clone().set({color:0xaaaaff, emissive: 0x333399}), {x: 0, y: 0.3, z: -4}); | |
| crystal.userData = { isPickupable: true, itemName: "Cave Crystal", description: "A glowing crystal."}; | |
| group.add(crystal); // Add pickupable crystal | |
| group.visible = false; | |
| return { group, lighting: 'cave', title: "Dim Cave", entryText: "It's dark and damp in here. Water drips.", options: [], zoneId: zoneId }; | |
| } | |
| function createRuinsZone(zoneId) { | |
| console.log(`Creating zone: ${zoneId} (Ruins)`); | |
| const group = new THREE.Group(); | |
| group.add(createGround(MAT.dirt, 25)); | |
| const wallGeo = new THREE.BoxGeometry(0.5, 2, 3); | |
| for(let i=0; i<8; i++) { | |
| const wall = createMesh(wallGeo, MAT.stone, | |
| {x: (Math.random()-0.5)*20, y:1, z: (Math.random()-0.5)*20}, | |
| {y: Math.random() * Math.PI} | |
| ); | |
| wall.scale.y = 0.5 + Math.random() * 0.8; | |
| wall.rotation.x = (Math.random()-0.5)*0.1; | |
| wall.rotation.z = (Math.random()-0.5)*0.1; | |
| group.add(wall); | |
| } | |
| const torchGeo = new THREE.CylinderGeometry(0.05, 0.05, 0.6, 6); | |
| const torch = createMesh(torchGeo, MAT.wood, {x: -2, y: 0.3, z: 3}, {z: -Math.PI / 6}); | |
| torch.userData = { isPickupable: true, itemName: "Torch", description: "An unlit torch lies in the rubble."}; | |
| group.add(torch); // Add pickupable torch | |
| group.visible = false; | |
| return { group, lighting: 'ruins', title: "Crumbling Ruins", entryText: "The wind whistles through broken walls.", options: [], zoneId: zoneId }; | |
| } | |
| function getZoneId(row, col) { return `zone_${row}_${col}`; } | |
| function populateZoneCreators() { | |
| console.log("Populating zone creators..."); | |
| // zoneCreators = {}; // Removed reassignment | |
| for (let r = 0; r < MAP_ROWS; r++) { | |
| for (let c = 0; c < MAP_COLS; c++) { | |
| const zoneId = getZoneId(r, c); | |
| let creatorFunc; | |
| if (r === 0) creatorFunc = createForestZone; | |
| else if (r === 1 && c % 2 === 0) creatorFunc = createFieldZone; | |
| else if (r === 1 && c % 2 !== 0) creatorFunc = createRuinsZone; | |
| else creatorFunc = createCaveZone; | |
| zoneCreators[zoneId] = () => creatorFunc(zoneId); | |
| } | |
| } | |
| console.log(`Zone creators populated with ${Object.keys(zoneCreators).length} entries.`); | |
| } | |
| function getZoneNeighbors(zoneId) { | |
| const parts = zoneId.split('_'); | |
| if (parts.length !== 3) return {}; | |
| const r = parseInt(parts[1]); | |
| const c = parseInt(parts[2]); | |
| const neighbors = {}; | |
| if (r > 0 && zoneCreators[getZoneId(r - 1, c)]) neighbors.north = getZoneId(r - 1, c); | |
| if (r < MAP_ROWS - 1 && zoneCreators[getZoneId(r + 1, c)]) neighbors.south = getZoneId(r + 1, c); | |
| if (c > 0 && zoneCreators[getZoneId(r, c - 1)]) neighbors.west = getZoneId(r, c - 1); | |
| if (c < MAP_COLS - 1 && zoneCreators[getZoneId(r, c + 1)]) neighbors.east = getZoneId(r, c + 1); | |
| return neighbors; | |
| } | |
| function startGame() { | |
| console.log("startGame called."); | |
| const defaultChar = { | |
| name: "Player", | |
| stats: { hp: 20, maxHp: 20, xp: 0 }, | |
| inventory: [] // Start with empty inventory initially | |
| }; | |
| gameState = { | |
| currentZoneId: null, | |
| character: JSON.parse(JSON.stringify(defaultChar)) | |
| }; | |
| populateZoneCreators(); | |
| zoneGroups = {}; | |
| while(worldGroup.children.length > 0){ | |
| worldGroup.remove(worldGroup.children[0]); | |
| } | |
| console.log("Starting new game state:", gameState); | |
| transitionToZone(getZoneId(1, 1)); // Start in center | |
| console.log("startGame finished."); | |
| } | |
| function transitionToZone(newZoneId) { | |
| console.log(`Attempting transition to ${newZoneId}`); | |
| currentMessage = ""; | |
| currentPlacingItem = null; // Cancel placement on zone change | |
| if (gameState.currentZoneId && zoneGroups[gameState.currentZoneId]) { | |
| console.log(`Hiding old zone: ${gameState.currentZoneId}`); | |
| zoneGroups[gameState.currentZoneId].group.visible = false; | |
| } else { | |
| console.log("No current zone to hide."); | |
| } | |
| let zoneInfo; | |
| if (zoneGroups[newZoneId]) { | |
| zoneInfo = zoneGroups[newZoneId]; | |
| zoneInfo.group.visible = true; | |
| console.log(`Re-entering cached zone ${newZoneId}`); | |
| } else { | |
| const creator = zoneCreators[newZoneId]; | |
| if (creator) { | |
| try { | |
| zoneInfo = creator(); | |
| zoneGroups[newZoneId] = zoneInfo; | |
| worldGroup.add(zoneInfo.group); | |
| zoneInfo.group.visible = true; | |
| console.log(`Created and entered new zone ${newZoneId}`); | |
| } catch (creationError) { | |
| console.error(`Error creating zone ${newZoneId}:`, creationError); | |
| currentMessage = `<p class="message message-failure">Error creating zone ${newZoneId}.</p>`; | |
| renderCurrentPageUI(); | |
| return; | |
| } | |
| } else { | |
| console.error(`No creator found for zone ID: ${newZoneId}, critical error.`); | |
| currentMessage = `<p class="message message-failure">Error: Zone creator missing for ${newZoneId}. Cannot proceed.</p>`; | |
| storyTitleElement.textContent = "Fatal Error"; | |
| storyContentElement.innerHTML = currentMessage; | |
| choicesElement.innerHTML = ''; | |
| return; | |
| } | |
| } | |
| gameState.currentZoneId = newZoneId; | |
| setupLighting(zoneInfo.lighting || 'default'); | |
| // Add relevant tracked lights (like cave point light) to the new zone group | |
| const currentZoneGroup = zoneInfo.group; | |
| currentLights.forEach(light => { | |
| if (light && light.isPointLight && zoneInfo.lighting === 'cave') { // Example: only add point lights to caves | |
| if (light.parent) light.parent.remove(light); // Remove from old parent if any | |
| currentZoneGroup.add(light); | |
| console.log("Added point light to cave group:", newZoneId); | |
| } | |
| // Ensure other lights (ambient, directional) are in the main scene, not the group | |
| else if (light && !light.isPointLight && !light.parent) { | |
| scene.add(light); | |
| } | |
| }); | |
| camera.position.set(0, 6, 12); | |
| controls.target.set(0, 1, 0); | |
| controls.update(); | |
| console.log(`Transition to ${newZoneId} complete. Rendering UI.`); | |
| renderCurrentPageUI(); | |
| } | |
| function renderCurrentPageUI() { | |
| console.log(`renderCurrentPageUI called for zone: ${gameState.currentZoneId}`); | |
| const zoneInfo = zoneGroups[gameState.currentZoneId]; | |
| const zoneId = gameState.currentZoneId; | |
| if (!storyTitleElement || !storyContentElement || !choicesElement || !statsElement || !inventoryElement || !actionInfoElement) { | |
| console.error("Crucial UI element missing!"); return; | |
| } | |
| if (!zoneInfo || !zoneInfo.group) { | |
| console.error(`No zone info or group loaded for ${zoneId}`); | |
| storyTitleElement.textContent = "Error"; | |
| storyContentElement.innerHTML = currentMessage + "<p>Cannot render current zone data.</p>"; | |
| choicesElement.innerHTML = `<button class="choice-button" onclick="transitionToZoneWrapper('${getZoneId(1, 1)}')">Return to Start</button>`; | |
| updateStatsDisplay(); updateInventoryDisplay(); updateActionInfo(); return; | |
| } | |
| console.log(`Rendering UI for zone ${zoneId} with title "${zoneInfo.title}"`); | |
| storyTitleElement.textContent = zoneInfo.title || "Unknown Zone"; | |
| storyContentElement.innerHTML = currentMessage + (zoneInfo.entryText ? `<p>${zoneInfo.entryText}</p>` : ''); | |
| choicesElement.innerHTML = ''; | |
| const neighbors = getZoneNeighbors(zoneId); | |
| const directions = {'north': 'North', 'south': 'South', 'east': 'East', 'west': 'West'}; | |
| let addedChoices = 0; | |
| console.log("Adding neighbor buttons:", neighbors); | |
| for(const dir in neighbors) { | |
| const neighborId = neighbors[dir]; | |
| const button = document.createElement('button'); | |
| button.classList.add('choice-button'); | |
| button.textContent = `Go ${directions[dir]}`; | |
| button.addEventListener('click', () => transitionToZone(neighborId)); // Use event listener | |
| choicesElement.appendChild(button); | |
| addedChoices++; | |
| } | |
| if (zoneInfo.options && zoneInfo.options.length > 0) { | |
| console.log("Adding zone specific options"); | |
| zoneInfo.options.forEach(option => { | |
| const button = document.createElement('button'); | |
| button.classList.add('choice-button'); | |
| button.textContent = option.text; | |
| button.addEventListener('click', () => console.log("Zone action TBC:", option.action)); | |
| choicesElement.appendChild(button); | |
| addedChoices++; | |
| }); | |
| } | |
| if (addedChoices === 0 && choicesElement.innerHTML === '') { // Check if empty after adding | |
| choicesElement.innerHTML = '<p><i>No exits or actions defined here yet.</i></p>'; | |
| } | |
| console.log("Updating stats, inventory, action info..."); | |
| updateStatsDisplay(); | |
| updateInventoryDisplay(); | |
| updateActionInfo(); | |
| console.log("renderCurrentPageUI finished."); | |
| } | |
| function transitionToZoneWrapper(zoneId) { // Keep wrapper for potential inline use later | |
| transitionToZone(zoneId); | |
| } | |
| window.transitionToZoneWrapper = transitionToZoneWrapper; | |
| function updateStatsDisplay() { | |
| if (!gameState.character || !statsElement) return; | |
| const { hp, maxHp, xp } = gameState.character.stats; | |
| const hpColor = hp / maxHp < 0.3 ? '#f88' : (hp / maxHp < 0.6 ? '#fd5' : '#8f8'); | |
| statsElement.innerHTML = `<strong>Stats:</strong> <span style="color:${hpColor}">HP: ${hp}/${maxHp}</span> <span>XP: ${xp}</span>`; | |
| } | |
| function updateInventoryDisplay() { // Added back placement functionality | |
| if (!gameState.character || !inventoryElement) return; | |
| let invHtml = '<strong>Inventory:</strong> '; | |
| if (gameState.character.inventory.length === 0) { | |
| invHtml += '<em>Empty</em>'; | |
| } else { | |
| gameState.character.inventory.forEach(item => { | |
| const itemDef = itemsData[item] || { type: 'unknown', description: '???' }; | |
| const itemClass = `item-${itemDef.type || 'unknown'}`; | |
| const placingClass = (item === currentPlacingItem) ? ' placing' : ''; // Highlight item being placed | |
| invHtml += `<span class="item-tag ${itemClass}${placingClass}" title="Click to Place: ${itemDef.description}" data-itemname="${item}">${item}</span>`; | |
| }); | |
| } | |
| inventoryElement.innerHTML = invHtml; | |
| // Re-attach click listeners for placement mode | |
| inventoryElement.querySelectorAll('.item-tag').forEach(tag => { | |
| tag.addEventListener('click', (event) => { | |
| event.stopPropagation(); // Prevent click from triggering pickup if UI overlaps canvas | |
| togglePlacementMode(tag.dataset.itemname); | |
| }); | |
| }); | |
| } | |
| function updateActionInfo() { // Updated Action Info | |
| if (!actionInfoElement || !gameState ) return; | |
| if (currentPlacingItem) { | |
| actionInfoElement.textContent = `Placing: ${currentPlacingItem} (Click ground)`; | |
| } else { | |
| actionInfoElement.textContent = `Zone: ${gameState.currentZoneId || 'None'} | Mode: Explore (Click items)`; | |
| } | |
| actionInfoElement.style.display = 'block'; | |
| } | |
| // --- Pickup/Placement Functions (Restored) --- | |
| function pickupItem() { | |
| if (currentPlacingItem) return; // Don't pick up while placing | |
| raycaster.setFromCamera(mouse, camera); | |
| const currentGroup = zoneGroups[gameState.currentZoneId]?.group; | |
| if (!currentGroup) return; | |
| const pickupables = []; | |
| currentGroup.traverseVisible(child => { | |
| if (child.userData.isPickupable) { | |
| pickupables.push(child); | |
| } | |
| }); | |
| const intersects = raycaster.intersectObjects(pickupables, false); | |
| if (intersects.length > 0) { | |
| // Basic outline/highlight effect could go here if desired | |
| const clickedObject = intersects[0].object; | |
| const itemName = clickedObject.userData.itemName; | |
| if (itemName && itemsData[itemName]) { | |
| console.log(`Picked up: ${itemName}`); | |
| currentMessage = `<p class="message message-item"><em>Picked up: ${itemName}</em></p>`; | |
| if (!gameState.character.inventory.includes(itemName)) { | |
| gameState.character.inventory.push(itemName); | |
| } else { | |
| currentMessage += `<p class="message message-info"><em>(Cannot carry more ${itemName})</em></p>`; | |
| } | |
| clickedObject.visible = false; // Hide the object | |
| clickedObject.userData.isPickupable = false; // Mark as picked up | |
| // Optionally remove from scene: clickedObject.parent.remove(clickedObject); | |
| renderCurrentPageUI(); // Update inventory and messages | |
| } | |
| } | |
| } | |
| function togglePlacementMode(itemName) { // Added back | |
| if (!itemName || !gameState.character.inventory.includes(itemName)) return; | |
| if (currentPlacingItem === itemName) { | |
| currentPlacingItem = null; | |
| console.log("Placement cancelled."); | |
| } else { | |
| currentPlacingItem = itemName; | |
| console.log(`Ready to place: ${itemName}`); | |
| } | |
| updateInventoryDisplay(); // Update highlighting | |
| updateActionInfo(); | |
| } | |
| function placeItem() { // Added back | |
| if (!currentPlacingItem) return; | |
| raycaster.setFromCamera(mouse, camera); | |
| const currentGroup = zoneGroups[gameState.currentZoneId]?.group; | |
| if (!currentGroup) return; | |
| const grounds = []; | |
| currentGroup.traverseVisible(child => { if(child.userData.isGround) grounds.push(child); }); | |
| const intersects = raycaster.intersectObjects(grounds); | |
| if (intersects.length > 0) { | |
| const point = intersects[0].point; | |
| const itemName = currentPlacingItem; | |
| const itemDef = itemsData[itemName]; | |
| console.log(`Placing ${itemName} at ${point.x.toFixed(1)}, ${point.z.toFixed(1)}`); | |
| // Create a visual representation of the item | |
| const itemGeo = new THREE.BoxGeometry(0.5, 0.5, 0.5); | |
| const itemMat = MAT.simple.clone(); | |
| if(itemDef?.type === 'weapon') itemMat.color.setHex(0xaa4444); | |
| else if(itemDef?.type === 'consumable') itemMat.color.setHex(0xaa7744); | |
| else itemMat.color.setHex(0x8888aa); | |
| const placedMesh = createMesh(itemGeo, itemMat, {x: point.x, y: 0.25, z: point.z}); // Place slightly above ground | |
| placedMesh.userData = { | |
| isPlacedItem: true, | |
| itemName: itemName, | |
| isPickupable: true, // Allow picking it back up | |
| description: `Placed ${itemName}` | |
| }; | |
| currentGroup.add(placedMesh); | |
| gameState.character.inventory = gameState.character.inventory.filter(i => i !== itemName); // Remove from inventory | |
| currentMessage = `<p class="message message-item"><em>Placed ${itemName}.</em></p>`; | |
| currentPlacingItem = null; // Exit placement mode | |
| renderCurrentPageUI(); // Update UI | |
| } else { | |
| console.log("Placement click missed ground."); | |
| currentMessage = `<p class="message message-failure"><em>Cannot place item there.</em></p>`; | |
| currentPlacingItem = null; | |
| renderCurrentPageUI(); | |
| } | |
| } | |
| // --- Combat/Checks (Placeholders) --- | |
| function startCombat(enemyTypeId) { console.log("Combat disabled."); } | |
| function handleCombatAction(action) { console.log("Combat disabled."); } | |
| window.startCombat = startCombat; | |
| window.handleCombatAction = handleCombatAction; | |
| // --- Initialization --- | |
| document.addEventListener('DOMContentLoaded', () => { | |
| console.log("DOM Ready - Initializing World Grid + Interaction."); | |
| try { | |
| initThreeJS(); | |
| if (!scene || !camera || !renderer) throw new Error("Three.js failed to initialize."); | |
| // Font not needed currently, start game directly | |
| startGame(); | |
| console.log("Game world initialized and started."); | |
| } catch (error) { | |
| console.error("Initialization failed:", error); | |
| storyTitleElement.textContent = "Initialization Error"; | |
| storyContentElement.innerHTML = `<p style="color:red;">Failed to start game:</p><pre style="color:red; white-space: pre-wrap;">${error.stack || error}</pre><p style="color:yellow;">Check console (F12) for details.</p>`; | |
| if(sceneContainer) sceneContainer.innerHTML = '<p style="color:red; padding: 20px;">3D Scene Failed</p>'; | |
| const statsInvContainer = document.getElementById('stats-inventory-container'); | |
| const choicesCont = document.getElementById('choices-container'); | |
| if (statsInvContainer) statsInvContainer.style.display = 'none'; | |
| if (choicesCont) choicesCont.style.display = 'none'; | |
| } | |
| }); | |
| </script> | |
| </body> | |
| </html> |