Spaces:
Running
Running
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Persistent Procedural World (Fixed Again)</title> | |
<style> | |
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; } | |
#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; } | |
#inventory-display .item-tag:hover { background-color: #6a6a6a; } | |
#inventory-display .item-tag.placing { background-color: #a07030; border-color: #c89040; color: #fff; } | |
#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); } | |
.message-success { color: #8f8; border-left-color: #4a4; } | |
.message-failure { color: #f88; border-left-color: #a44; } | |
.message-info { color: #aaa; border-left-color: #666; } | |
.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: none; z-index: 10;} | |
</style> | |
</head> | |
<body> | |
<div id="game-container"> | |
<div id="scene-container"> | |
<div id="action-info">Mode: Explore</div> | |
</div> | |
<div id="ui-container"> | |
<h2 id="story-title">World Initializing...</h2> | |
<div id="story-content"><p>Establishing reality...</p></div> | |
<div id="stats-inventory-container"> | |
<div id="stats-display"></div> | |
<div id="inventory-display"></div> | |
</div> | |
<div id="choices-container"> | |
<h3>What will you do?</h3> | |
<div id="choices"></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'; | |
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'); | |
let scene, camera, renderer, clock, controls, raycaster, mouse; | |
let worldGroup = null; | |
let locationGroups = {}; | |
let currentMessage = ""; | |
let currentPlacingItem = null; | |
let currentLights = []; | |
const MAT = { | |
stone: new THREE.MeshStandardMaterial({ color: 0x777788, roughness: 0.85, metalness: 0.1 }), | |
wood: new THREE.MeshStandardMaterial({ color: 0x9F6633, roughness: 0.75, metalness: 0 }), | |
leaf: new THREE.MeshStandardMaterial({ color: 0x3E9B4E, roughness: 0.6, metalness: 0, side: THREE.DoubleSide }), | |
ground: new THREE.MeshStandardMaterial({ color: 0x556B2F, roughness: 0.95, metalness: 0 }), | |
metal: new THREE.MeshStandardMaterial({ color: 0xaaaaaa, metalness: 0.85, roughness: 0.35 }), | |
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, metalness: 0.2, transparent: true, opacity: 0.85 }), | |
error: new THREE.MeshStandardMaterial({ color: 0xff3300, roughness: 0.5, emissive: 0x551100 }), | |
gameOver: new THREE.MeshStandardMaterial({ color: 0xaa0000, roughness: 0.6, metalness: 0.2, emissive: 0x220000 }), | |
simple: new THREE.MeshStandardMaterial({ color: 0xaaaaaa, roughness: 0.8 }), | |
pickupHighlight: new THREE.MeshBasicMaterial({ color: 0xffff00, wireframe: true, depthTest: false }), | |
placementPreview: new THREE.MeshBasicMaterial({ color: 0x00ff00, transparent: true, opacity: 0.5, wireframe: true }), | |
}; | |
// ---> Item Data Definition (Ensure this exists globally) <--- | |
const itemsData = { | |
"Rusty Sword": {type:"weapon", description:"Old but sharp."}, | |
"Torch": {type:"consumable", description:"Provides light.", use: "light"}, | |
"Key": {type:"quest", description:"A simple iron key."}, | |
"Mysterious Cube": {type:"unknown", description:"A plain stone cube."} // Added item from default zone | |
}; | |
// ---> Location/Zone Definitions <--- | |
const locationData = { | |
'start': { creator: createDefaultZone }, | |
'forest': { creator: createForestZone }, | |
'cave': { creator: createCaveZone } | |
}; | |
// ---> Navigation/Story Graph <--- | |
const pageGraph = { | |
'start': { | |
title: "The Crossroads", | |
options: [ { text: "Enter Forest", transitionTo: 'forest' }, { text: "Enter Cave", transitionTo: 'cave'} ] | |
}, | |
'forest': { | |
title: "Dark Forest", | |
options: [ { text: "Return to Crossroads", transitionTo: 'start' } ] | |
}, | |
'cave': { | |
title: "Dim Cave", | |
options: [ { text: "Leave Cave", transitionTo: 'start' } ] | |
} | |
}; | |
// ---> Game State Variable <--- | |
let gameState = {}; // Initialized in startGame | |
// --- Core Functions --- | |
function initThreeJS() { | |
scene = new THREE.Scene(); | |
scene.background = new THREE.Color(0x1a1a1a); | |
clock = new THREE.Clock(); | |
raycaster = new THREE.Raycaster(); | |
mouse = new THREE.Vector2(); | |
worldGroup = new THREE.Group(); | |
scene.add(worldGroup); | |
const width = sceneContainer.clientWidth || 1; | |
const height = sceneContainer.clientHeight || 1; | |
camera = new THREE.PerspectiveCamera(60, width / height, 0.1, 1000); | |
camera.position.set(0, 5, 10); | |
renderer = new THREE.WebGLRenderer({ antialias: true }); | |
renderer.setSize(width, height); | |
renderer.shadowMap.enabled = true; | |
renderer.shadowMap.type = THREE.PCFSoftShadowMap; | |
renderer.toneMapping = THREE.ACESFilmicToneMapping; | |
renderer.outputColorSpace = THREE.SRGBColorSpace; | |
sceneContainer.appendChild(renderer.domElement); | |
controls = new OrbitControls(camera, renderer.domElement); | |
controls.enableDamping = true; | |
controls.dampingFactor = 0.1; | |
controls.target.set(0, 1, 0); | |
controls.maxPolarAngle = Math.PI / 2 - 0.05; | |
window.addEventListener('resize', onWindowResize, false); | |
renderer.domElement.addEventListener('mousemove', onMouseMove, false); | |
renderer.domElement.addEventListener('click', onMouseClick, false); | |
setTimeout(onWindowResize, 50); | |
animate(); | |
} | |
function onWindowResize() { | |
if (!renderer || !camera || !sceneContainer) return; | |
const width = sceneContainer.clientWidth || 1; | |
const height = sceneContainer.clientHeight || 1; | |
camera.aspect = width / height; | |
camera.updateProjectionMatrix(); | |
renderer.setSize(width, height); | |
} | |
function onMouseMove( event ) { | |
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 ) { | |
if (currentPlacingItem) { | |
placeItem(); | |
} else { | |
pickupItem(); | |
} | |
} | |
function animate() { | |
requestAnimationFrame(animate); | |
const delta = clock.getDelta(); | |
const time = clock.getElapsedTime(); | |
controls.update(); | |
worldGroup.traverse(obj => { if (obj.userData.update) obj.userData.update(time, delta); }); | |
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') { | |
currentLights.forEach(light => { | |
if (light) scene.remove(light); | |
}); | |
currentLights = []; | |
let ambientIntensity = 0.4; | |
let dirIntensity = 0.9; | |
let dirColor = 0xffffff; | |
let dirPosition = new THREE.Vector3(10, 15, 8); | |
if (type === 'forest') { | |
ambientIntensity = 0.3; dirIntensity = 0.7; dirColor = 0xccffcc; dirPosition = new THREE.Vector3(5, 10, 5); | |
} else if (type === 'cave') { | |
ambientIntensity = 0.1; dirIntensity = 0; | |
const ptLight = new THREE.PointLight(0xffaa55, 1.5, 12, 1); | |
ptLight.position.set(0, 1.5, 1); | |
ptLight.castShadow = true; | |
ptLight.shadow.mapSize.set(512, 512); | |
scene.add(ptLight); currentLights.push(ptLight); | |
} else if (type === 'gameover') { | |
ambientIntensity = 0.1; dirIntensity = 0.4; dirColor = 0xff6666; | |
} | |
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 shadowBounds = 20; | |
directionalLight.shadow.camera.left = -shadowBounds; | |
directionalLight.shadow.camera.right = shadowBounds; | |
directionalLight.shadow.camera.top = shadowBounds; | |
directionalLight.shadow.camera.bottom = -shadowBounds; | |
directionalLight.shadow.bias = -0.0005; | |
scene.add(directionalLight); | |
currentLights.push(directionalLight); | |
} | |
} | |
function createDefaultZone() { | |
const group = new THREE.Group(); | |
group.add(createGround(MAT.dirt, 20)); | |
const boxGeo = new THREE.BoxGeometry(1, 1, 1); | |
const interactBox = createMesh(boxGeo, MAT.stone, {y: 0.5, x: 2, z: 2}); | |
interactBox.userData = { isPickupable: true, itemName: "Mysterious Cube", description: "A plain stone cube."}; | |
group.add(interactBox); | |
group.visible = false; | |
return { group, lighting: 'default', entryText: "You are in a default, featureless area.", cameraPos: {x:0, y:5, z:10}, targetPos: {x:0, y:1, z:0} }; | |
} | |
function createForestZone() { | |
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<20; i++) { | |
const x = (Math.random() - 0.5) * 28; | |
const z = (Math.random() - 0.5) * 28; | |
if(Math.sqrt(x*x+z*z) < 3) 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); | |
group.visible = false; | |
return { group, lighting: 'forest', entryText: "You enter the dark forest. Sunlight struggles to get through.", cameraPos: {x:-5, y:6, z:12}, targetPos: {x:0, y:1, z:0} }; | |
} | |
function createCaveZone() { | |
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 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 leans against the wall."}; | |
group.add(torch); | |
group.visible = false; | |
return { group, lighting: 'cave', entryText: "It's dark and damp in here.", cameraPos: {x:0, y:4, z:8}, targetPos: {x:0, y:1, z:0} }; | |
} | |
function startGame() { | |
const defaultChar = { | |
name: "Player", | |
stats: { hp: 20, maxHp: 20, xp: 0 }, | |
inventory: ["Rusty Sword"] | |
}; | |
gameState = { | |
currentLocationId: null, | |
character: JSON.parse(JSON.stringify(defaultChar)) | |
}; | |
console.log("Starting new game:", gameState); | |
transitionToLocation('start'); | |
} | |
function transitionToLocation(newLocationId) { | |
console.log(`Transitioning from ${gameState.currentLocationId} to ${newLocationId}`); | |
currentMessage = ""; | |
currentPlacingItem = null; | |
if (gameState.currentLocationId && locationGroups[gameState.currentLocationId]) { | |
locationGroups[gameState.currentLocationId].visible = false; | |
} | |
let newGroup; | |
let locationInfo; | |
if (locationGroups[newLocationId]) { | |
newGroup = locationGroups[newLocationId]; | |
newGroup.visible = true; | |
locationInfo = locationData[newLocationId].cachedInfo; | |
} else { | |
if (locationData[newLocationId] && locationData[newLocationId].creator) { | |
locationInfo = locationData[newLocationId].creator(); | |
newGroup = locationInfo.group; | |
locationGroups[newLocationId] = newGroup; | |
locationData[newLocationId].cachedInfo = locationInfo; | |
worldGroup.add(newGroup); | |
newGroup.visible = true; | |
} else { | |
console.error(`Location data or creator missing for ID: ${newLocationId}, attempting fallback to 'start'`); | |
if (!locationGroups['start']) { | |
locationData['start'].cachedInfo = locationData['start'].creator(); | |
locationGroups['start'] = locationData['start'].cachedInfo.group; | |
worldGroup.add(locationGroups['start']); | |
} | |
locationInfo = locationData['start'].cachedInfo; | |
newGroup = locationGroups['start']; | |
newGroup.visible = true; | |
newLocationId = 'start'; | |
currentMessage += `<p class="message message-failure">Error: Couldn't load target location, returned to start.</p>`; | |
} | |
} | |
gameState.currentLocationId = newLocationId; | |
setupLighting(locationInfo.lighting || 'default'); | |
if (locationInfo.cameraPos) camera.position.set(locationInfo.cameraPos.x, locationInfo.cameraPos.y, locationInfo.cameraPos.z); | |
if (locationInfo.targetPos) controls.target.set(locationInfo.targetPos.x, locationInfo.targetPos.y, locationInfo.targetPos.z); | |
controls.update(); | |
renderCurrentPageUI(); | |
} | |
function renderCurrentPageUI() { | |
const page = pageGraph[gameState.currentLocationId]; | |
const locationInfo = locationData[gameState.currentLocationId]?.cachedInfo; | |
if (!page) { | |
console.error(`No page graph data for location ${gameState.currentLocationId}`); | |
storyTitleElement.textContent = "Lost"; | |
storyContentElement.innerHTML = currentMessage + "<p>You seem to be in an unknown place.</p>"; | |
choicesElement.innerHTML = `<button class="choice-button" onclick="handleTransition({transitionTo: 'start'})">Return to Start</button>`; | |
updateStatsDisplay(); | |
updateInventoryDisplay(); | |
updateActionInfo(); | |
return; | |
} | |
storyTitleElement.textContent = page.title; | |
storyContentElement.innerHTML = currentMessage + (locationInfo?.entryText ? `<p>${locationInfo.entryText}</p>` : ''); | |
choicesElement.innerHTML = ''; | |
if (page.options && page.options.length > 0) { | |
page.options.forEach(option => { | |
const button = document.createElement('button'); | |
button.classList.add('choice-button'); | |
button.textContent = option.text; | |
button.onclick = () => handleTransition(option); | |
choicesElement.appendChild(button); | |
}); | |
} else { | |
choicesElement.innerHTML = '<p><i>No transitions available from here yet.</i></p>'; | |
} | |
updateStatsDisplay(); | |
updateInventoryDisplay(); | |
updateActionInfo(); | |
} | |
function handleTransition(option) { | |
if (option.transitionTo) { | |
transitionToLocation(option.transitionTo); | |
} else { | |
console.warn("Choice option has no transitionTo property:", option); | |
} | |
} | |
window.handleTransition = handleTransition; | |
function updateStatsDisplay() { | |
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() { | |
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' : ''; | |
invHtml += `<span class="item-tag ${itemClass}${placingClass}" title="Click to Place: ${itemDef.description}" data-itemname="${item}">${item}</span>`; | |
}); | |
} | |
inventoryElement.innerHTML = invHtml; | |
inventoryElement.querySelectorAll('.item-tag').forEach(tag => { | |
tag.onclick = (event) => { | |
event.stopPropagation(); | |
togglePlacementMode(tag.dataset.itemname); | |
}; | |
}); | |
} | |
function updateActionInfo() { | |
if(currentPlacingItem) { | |
actionInfoElement.textContent = `Placing: ${currentPlacingItem} (Click ground)`; | |
actionInfoElement.style.display = 'block'; | |
} else { | |
actionInfoElement.textContent = `Mode: Explore (Click items/Use UI)`; | |
actionInfoElement.style.display = 'block'; | |
} | |
} | |
function pickupItem() { | |
if (currentPlacingItem) return; | |
raycaster.setFromCamera(mouse, camera); | |
const currentGroup = locationGroups[gameState.currentLocationId]; | |
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) { | |
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>(You already had one)</em></p>`; | |
} | |
clickedObject.visible = false; | |
clickedObject.userData.isPickupable = false; | |
renderCurrentPageUI(); | |
} | |
} | |
} | |
function togglePlacementMode(itemName) { | |
if (!itemName) return; | |
if (currentPlacingItem === itemName) { | |
currentPlacingItem = null; | |
console.log("Placement cancelled."); | |
} else { | |
currentPlacingItem = itemName; | |
console.log(`Ready to place: ${itemName}`); | |
} | |
updateInventoryDisplay(); | |
updateActionInfo(); | |
} | |
function placeItem() { | |
if (!currentPlacingItem) return; | |
raycaster.setFromCamera(mouse, camera); | |
const currentGroup = locationGroups[gameState.currentLocationId]; | |
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)}`); | |
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}); | |
placedMesh.userData = { isPlacedItem: true, itemName: itemName, isPickupable: true, description: `Placed ${itemName}` }; | |
currentGroup.add(placedMesh); | |
gameState.character.inventory = gameState.character.inventory.filter(i => i !== itemName); | |
currentMessage = `<p class="message message-item"><em>Placed ${itemName}.</em></p>`; | |
currentPlacingItem = null; | |
renderCurrentPageUI(); | |
} else { | |
console.log("Placement click missed ground."); | |
currentMessage = `<p class="message message-failure"><em>Cannot place item there.</em></p>`; | |
currentPlacingItem = null; | |
renderCurrentPageUI(); | |
} | |
} | |
document.addEventListener('DOMContentLoaded', () => { | |
console.log("DOM Ready - Initializing Persistent World Adventure."); | |
try { | |
initThreeJS(); | |
if (!scene || !camera || !renderer) throw new Error("Three.js failed to initialize."); | |
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>`; | |
if(sceneContainer) sceneContainer.innerHTML = '<p style="color:red; padding: 20px;">3D Scene Failed</p>'; | |
document.getElementById('stats-inventory-container').style.display = 'none'; | |
document.getElementById('choices-container').style.display = 'none'; | |
} | |
}); | |
</script> | |
</body> | |
</html> |