awacke1's picture
Create index.html
5a10444 verified
raw
history blame
51.5 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Procedural World - D&D Style</title>
<style>
/* --- Base Styles --- */
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: default; }
#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; }
/* --- UI Elements --- */
#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 { 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 { 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); cursor: default; } /* No placement click */
#stats-display strong, #inventory-display strong { color: #ccc; margin-right: 6px; }
#inventory-display em { color: #888; font-style: normal; }
.item-weapon { background-color: #663030; border-color: #994848;}
.item-consumable { background-color: #664430; border-color: #996648;}
.item-unknown { background-color: #555; border-color: #777;}
/* --- Choices & Messages --- */
#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-success { color: #8f8; border-left-color: #4a4; }
.message-info { color: #aaa; border-left-color: #666; }
.message-item { color: #8bf; border-left-color: #46a; }
.message-combat { color: #f98; border-left-color: #c64; font-weight: bold;}
.combat-button { background-color: #a33; border-color: #c66; color: #fff; font-weight: bold; text-align: center;}
.combat-button:hover:not(:disabled) { background-color: #d44; border-color: #f88;}
/* --- Action Info --- */
#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 world...</p></div>
<div id="stats-inventory-container">
<div id="stats-display">Loading Stats...</div>
<div id="inventory-display">Inventory: ...</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';
import { FontLoader } from 'three/addons/loaders/FontLoader.js';
import { TextGeometry } from 'three/addons/geometries/TextGeometry.js';
console.log("Script module execution started.");
// --- DOM Elements ---
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');
// --- Core Three.js Variables ---
let scene, camera, renderer, clock, controls, raycaster, mouse;
let worldGroup = null; // Parent for all zone content
let zoneGroups = {}; // Stores loaded zone data: { zoneId: { group, lighting, title, ... } }
let currentLights = [];
let threeFont = null; // For 3D text
// --- Game State ---
let gameState = {}; // Initialized in startGame
let currentMessage = ""; // Accumulates messages for UI update
let activeTimeouts = []; // Track animation timeouts
// --- Materials ---
const MAT = {
stone: new THREE.MeshStandardMaterial({ color: 0x777788, roughness: 0.85 }),
dark_stone: new THREE.MeshStandardMaterial({ color: 0x444455, roughness: 0.9 }),
wood: new THREE.MeshStandardMaterial({ color: 0x9F6633, roughness: 0.75 }),
dark_wood: new THREE.MeshStandardMaterial({ color: 0x6F4E2D, roughness: 0.8 }),
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 }),
metal: new THREE.MeshStandardMaterial({ color: 0xaaaaaa, metalness: 0.8, roughness: 0.4 }),
simple: new THREE.MeshStandardMaterial({ color: 0xaaaaaa, roughness: 0.8 }),
text: new THREE.MeshBasicMaterial({ color: 0xffddaa }),
// Zone specific themes
ruins_stone: new THREE.MeshStandardMaterial({ color: 0x888a8f, roughness: 0.9 }),
town_wood: new THREE.MeshStandardMaterial({ color: 0xae8a63, roughness: 0.7 }),
town_roof: new THREE.MeshStandardMaterial({ color: 0x8b4513, roughness: 0.8 }),
};
// --- Game Data ---
const itemsData = {
"Rusty Sword": {type:"weapon", description:"Old but sharp.", baseDamage: 3},
"Health Potion": {type:"consumable", description:"Restores 10 HP.", effect: { hpGain: 10 }},
"Goblin Ear": {type:"quest", description:"A gruesome trophy."},
"Cave Crystal": {type:"unknown", description:"A faintly glowing crystal shard."},
"Ancient Coin": {type:"unknown", description:"A worn coin from a forgotten era."}
};
const enemyData = {
'goblin': { name: "Goblin", hp: 8, defense: 11, attackDamage: 2, xp: 15, drops: ["Goblin Ear", "Health Potion"] },
'skeleton': { name: "Skeleton", hp: 10, defense: 12, attackDamage: 3, xp: 20, drops: ["Ancient Coin"] },
'spider': { name: "Giant Spider", hp: 12, defense: 13, attackDamage: 3, xp: 25, drops: ["Cave Crystal"] }
};
const zoneCreators = {};
const MAP_ROWS = 3;
const MAP_COLS = 4;
// --- Core Functions ---
function initThreeJS() {
console.log("initThreeJS started.");
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 || 300;
const height = sceneContainer.clientHeight || 200;
camera = new THREE.PerspectiveCamera(60, width / height, 0.1, 1000);
camera.position.set(0, 8, 15); // Start slightly further back/higher
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(width, height);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
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;
controls.minDistance = 3;
controls.maxDistance = 50;
window.addEventListener('resize', onWindowResize, false);
renderer.domElement.addEventListener('click', onMouseClick, false);
setTimeout(onWindowResize, 100);
animate();
console.log("initThreeJS finished successfully.");
}
function loadFontAndStart() {
console.log("Loading font...");
const loader = new FontLoader();
loader.load('https://unpkg.com/[email protected]/examples/fonts/helvetiker_regular.typeface.json', function (font) {
threeFont = font;
console.log("Font loaded.");
startGame();
}, undefined, function (error) {
console.error('Font loading failed:', error);
storyTitleElement.textContent = "Font Load Error";
storyContentElement.innerHTML = `<p class="message message-failure">Could not load required font. Combat text disabled.</p>`;
startGame(); // Start anyway, but combat text won't work
});
}
function onWindowResize() {
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);
}
}
function onMouseClick( event ) {
// Currently only used for picking up items
pickupItem();
}
function animate() {
requestAnimationFrame(animate);
const delta = clock.getDelta();
const time = clock.getElapsedTime();
controls.update();
// Animate objects within the *currently visible* zone group
if (gameState.currentZoneId && zoneGroups[gameState.currentZoneId]) {
zoneGroups[gameState.currentZoneId].group.traverse(obj => {
if (obj.userData.update) obj.userData.update(time, delta);
});
}
if (renderer && scene && camera) renderer.render(scene, camera);
}
// --- Geometry/Mesh Helpers ---
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;
}
// --- Procedural Structure Helpers ---
function createTowerSegment(radius = 1, height = 2, material = MAT.stone) {
const geo = new THREE.CylinderGeometry(radius, radius, height, 8);
return createMesh(geo, material, {y: height/2});
}
function createWallSection(width = 4, height = 2.5, depth = 0.5, material = MAT.stone) {
const geo = new THREE.BoxGeometry(width, height, depth);
return createMesh(geo, material, {y: height/2});
}
function createSimpleHouse(width=3, height=2, depth=4, woodMat=MAT.town_wood, roofMat=MAT.town_roof) {
const group = new THREE.Group();
const wallGeo = new THREE.BoxGeometry(width, height, depth);
const walls = createMesh(wallGeo, woodMat, {y: height/2});
group.add(walls);
const roofGeo = new THREE.ConeGeometry(Math.max(width, depth) * 0.7, height * 0.6, 4); // Pyramid roof
const roof = createMesh(roofGeo, roofMat, {y: height + height*0.3});
roof.rotation.y = Math.PI / 4; // Align edges
group.add(roof);
return group;
}
// --- Lighting ---
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.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); }
if (type === 'cave') { ambientIntensity = 0.15; dirIntensity = 0; } // Rely on point light
if (type === 'ruins') { ambientIntensity = 0.35; dirIntensity = 0.6; dirColor = 0xaaaaff; dirPosition = new THREE.Vector3(-8, 12, -5); }
if (type === 'town') { ambientIntensity = 0.5; dirIntensity = 1.0; dirColor = 0xffeedd; dirPosition = new THREE.Vector3(12, 18, 10); }
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 = 25; // Wider shadow area for larger zones
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') {
const ptLight = new THREE.PointLight(0xffaa55, 1.5, 15, 1.5); // Increased range/decay
ptLight.position.set(0, 3, 0);
ptLight.castShadow = true;
ptLight.shadow.mapSize.set(512, 512);
currentLights.push(ptLight); // Will be added to group later
}
console.log(`Lighting setup complete. Lights tracked: ${currentLights.length}`);
}
// --- Zone Creation Functions (Enhanced) ---
function createFieldZone(zoneId) {
console.log(`Creating zone: ${zoneId} (Field)`);
const group = new THREE.Group();
group.add(createGround(MAT.grass, 40)); // Larger zone
const rockGeo = new THREE.IcosahedronGeometry(0.5 + Math.random()*0.8, 0);
for(let i=0; i<8; i++) {
const rock = createMesh(rockGeo, MAT.stone, {x: (Math.random()-0.5)*35, y:0.4, z: (Math.random()-0.5)*35});
rock.rotation.set(Math.random(), Math.random(), Math.random());
group.add(rock);
}
// Add a simple floating/bobbing animation to rocks
group.children.filter(c=>c.geometry.type === 'IcosahedronGeometry').forEach(rock => {
rock.userData.startY = rock.position.y;
rock.userData.update = (time) => {
rock.position.y = rock.userData.startY + Math.sin(time * 1.5 + rock.id * 0.5) * 0.1; // Bobbing
};
});
group.visible = false;
return { group, lighting: 'default', title: "Rolling Fields", entryText: `The wind whispers through the tall grass of zone ${zoneId}. Scattered boulders dot the landscape.`, options: [], zoneId: zoneId };
}
function createForestZone(zoneId) {
console.log(`Creating zone: ${zoneId} (Forest)`);
const group = new THREE.Group();
group.add(createGround(MAT.ground, 40));
const trunkGeo = new THREE.CylinderGeometry(0.2, 0.3, 4 + Math.random()*2, 8);
const leafGeo = new THREE.SphereGeometry(1.5 + Math.random(), 8, 6);
for(let i=0; i<35; i++) { // Denser forest
const x = (Math.random() - 0.5) * 38;
const z = (Math.random() - 0.5) * 38;
if(Math.sqrt(x*x+z*z) < 1) continue;
const tree = new THREE.Group();
const trunkHeight = 4 + Math.random()*2;
const trunk = createMesh(trunkGeo.clone().scale(1, trunkHeight/4, 1), MAT.wood, {y: trunkHeight/2}); // Scale trunk height
const leaves = createMesh(leafGeo.clone().scale(1+Math.random()*0.3, 1+Math.random()*0.3, 1+Math.random()*0.3), MAT.leaf, {y: trunkHeight + 0.5});
tree.add(trunk); tree.add(leaves);
tree.position.set(x, 0, z);
tree.rotation.y = Math.random() * Math.PI * 2;
// Add subtle sway animation
tree.userData.swaySpeed = 0.1 + Math.random() * 0.1;
tree.userData.swayAmount = 0.005 + Math.random() * 0.005;
tree.userData.update = (time) => {
tree.rotation.z = Math.sin(time * tree.userData.swaySpeed + tree.position.x) * tree.userData.swayAmount;
tree.rotation.x = Math.cos(time * tree.userData.swaySpeed * 0.7 + tree.position.z) * tree.userData.swayAmount;
};
group.add(tree);
}
group.visible = false;
return { group, lighting: 'forest', title: "Deep Forest", entryText: `Ancient trees form a dense canopy overhead in ${zoneId}. Strange sounds echo.`, options: [{text: "Search for Goblin Tracks", action: "triggerCombat", enemy: "goblin"}], zoneId: zoneId };
}
function createCaveZone(zoneId) {
console.log(`Creating zone: ${zoneId} (Cave)`);
const group = new THREE.Group();
group.add(createGround(MAT.stone.clone().set({color: 0x4a4a55}), 25)); // Darker floor
const wallGeo = new THREE.SphereGeometry(15, 32, 16, 0, Math.PI*2, 0, Math.PI*0.8); // Larger cave
const walls = createMesh(wallGeo, MAT.dark_stone, {y: 5});
walls.material.side = THREE.BackSide;
group.add(walls);
const coneGeo = new THREE.ConeGeometry(0.1 + Math.random()*0.2, 0.8 + Math.random()*1.5, 8); // Stalactites/mites
for(let i=0; i<25; i++){
const x = (Math.random()-0.5)*22;
const z = (Math.random()-0.5)*22;
const yUp = 7 + Math.random()*3;
const yDown = 0.5 + Math.random();
if (Math.random() > 0.5) group.add(createMesh(coneGeo.clone(), MAT.dark_stone, {x:x, y:yUp, z:z}, {x:Math.PI})); // Stalactite
if (Math.random() > 0.5) group.add(createMesh(coneGeo.clone(), MAT.dark_stone, {x:x, y:yDown, z:z})); // Stalagmite
}
// Add glowing crystals
const crystalGeo = new THREE.IcosahedronGeometry(0.3 + Math.random()*0.2, 0);
for(let i=0; i<5; i++) {
const crystal = createMesh(crystalGeo, MAT.simple.clone().set({color:0xaaaaff, emissive: 0x4444ff, emissiveIntensity: 0.8}),
{x: (Math.random()-0.5)*15, y:0.3 + Math.random()*2, z: (Math.random()-0.5)*15}
);
crystal.userData = { isPickupable: true, itemName: "Cave Crystal", description: "A faintly glowing crystal shard."};
// Add pulsing animation
crystal.userData.baseScale = 1.0;
crystal.userData.update = (time) => {
const scale = crystal.userData.baseScale + Math.sin(time * 2 + crystal.id) * 0.1;
crystal.scale.set(scale, scale, scale);
};
group.add(crystal);
}
group.visible = false;
return { group, lighting: 'cave', title: "Echoing Cave", entryText: `Water drips in the darkness of ${zoneId}. Strange crystals pulse with faint light.`, options: [{text: "Disturb Spider Nest", action: "triggerCombat", enemy: "spider"}], zoneId: zoneId };
}
function createRuinsZone(zoneId) {
console.log(`Creating zone: ${zoneId} (Ruins)`);
const group = new THREE.Group();
group.add(createGround(MAT.dirt, 35));
// Stacked walls/pillars
for(let i=0; i<12; i++) {
const stackHeight = Math.floor(1 + Math.random() * 3); // 1 to 3 segments high
const basePos = {x: (Math.random()-0.5)*30, y:0, z: (Math.random()-0.5)*30};
const rotY = Math.random() * Math.PI;
for (let j=0; j<stackHeight; j++) {
const width = 1 + Math.random();
const height = 0.8 + Math.random() * 0.4;
const depth = 1 + Math.random();
const segmentGeo = new THREE.BoxGeometry(width, height, depth);
const segment = createMesh(segmentGeo, MAT.ruins_stone,
{x: basePos.x, y: basePos.y + height/2, z: basePos.z},
{x:(Math.random()-0.5)*0.1, y: rotY + (Math.random()-0.5)*0.1, z:(Math.random()-0.5)*0.1} // Slight random tilt
);
group.add(segment);
basePos.y += height; // Move up for next segment
}
}
group.visible = false;
return { group, lighting: 'ruins', title: "Ancient Ruins", entryText: `The wind howls through the skeletal remains of ${zoneId}. Broken stones lie everywhere.`, options: [{text: "Disturb Grave", action: "triggerCombat", enemy: "skeleton"}], zoneId: zoneId };
}
function createTownZone(zoneId) { // New Zone Type
console.log(`Creating zone: ${zoneId} (Town)`);
const group = new THREE.Group();
group.add(createGround(MAT.dirt.clone().set({color: 0xaa8866}), 30)); // Packed earth/cobble look
for(let i=0; i<10; i++) {
const house = createSimpleHouse(
2 + Math.random()*2, // width
1.8 + Math.random()*0.5, // height
3 + Math.random()*2, // depth
MAT.town_wood, MAT.town_roof
);
house.position.set((Math.random()-0.5)*25, 0, (Math.random()-0.5)*25);
house.rotation.y = Math.floor(Math.random()*4) * Math.PI / 2 + (Math.random()-0.5)*0.1; // Align roughly to grid + tilt
group.add(house);
}
// Add a central well (example of combining primitives)
const wellBaseGeo = new THREE.CylinderGeometry(0.8, 0.8, 0.5, 12);
const wellBase = createMesh(wellBaseGeo, MAT.stone, {y: 0.25});
group.add(wellBase);
const wellWallGeo = new THREE.CylinderGeometry(0.7, 0.6, 1.0, 12);
const wellWall = createMesh(wellWallGeo, MAT.stone, {y: 0.5 + 0.5});
group.add(wellWall);
group.visible = false;
return { group, lighting: 'town', title: "Small Settlement", entryText: `You arrive at the small settlement in ${zoneId}. Smoke curls from a few chimneys.`, options: [{text:"Talk to Villager (TBC)", action:"talk"}], zoneId: zoneId };
}
function getZoneId(row, col) { return `zone_${row}_${col}`; }
function populateZoneCreators() {
console.log("Populating zone creators...");
// zoneCreators = {}; // Removed const error
for (let r = 0; r < MAP_ROWS; r++) {
for (let c = 0; c < MAP_COLS; c++) {
const zoneId = getZoneId(r, c);
let creatorFunc;
// More varied pattern
if (r === 0 && c === 0) creatorFunc = createCaveZone;
else if (r === 0) creatorFunc = createForestZone;
else if (r === 1 && c === 1) creatorFunc = createTownZone; // Add town
else if (r === 1 && c === 3) creatorFunc = createRuinsZone;
else if (r === 2 && c === 0) creatorFunc = createRuinsZone;
else if (r === 2 && c === 3) creatorFunc = createCaveZone;
else creatorFunc = createFieldZone; // Default to field
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, strength: 10, dexterity: 10, constitution: 10, intelligence: 10, wisdom: 10, charisma: 10 }, // Added D&D stats
inventory: []
};
gameState = {
currentZoneId: null,
character: JSON.parse(JSON.stringify(defaultChar)),
combat: null // Reset combat state
};
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 = "";
gameState.combat = null; // End combat 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 tracked point lights to the current zone group
const currentZoneGroup = zoneInfo.group;
currentLights.forEach(light => {
if (light && light.isPointLight && zoneInfo.lighting === 'cave') { // Only add point lights to caves
if(light.parent) light.parent.remove(light);
currentZoneGroup.add(light);
console.log("Added point light to cave group:", newZoneId);
} else if (light && !light.isPointLight && !light.parent) { // Ensure ambient/directional are in main scene
scene.add(light);
}
});
camera.position.set(0, 8, 15); // Reset camera view slightly higher
controls.target.set(0, 1, 0);
controls.update();
console.log(`Transition to ${newZoneId} complete. Rendering UI.`);
renderCurrentPageUI();
}
function renderCurrentPageUI() {
console.log(`renderCurrentPageUI 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/group for ${zoneId}`);
storyTitleElement.textContent = "Error"; storyContentElement.innerHTML = currentMessage + "<p>Cannot render zone data.</p>";
choicesElement.innerHTML = `<button class="choice-button" onclick="transitionToZoneWrapper('${getZoneId(1, 1)}')">Return to Start</button>`;
updateStatsDisplay(); updateInventoryDisplay(); updateActionInfo(); return;
}
storyTitleElement.textContent = zoneInfo.title || "Unknown Zone";
storyContentElement.innerHTML = currentMessage + (zoneInfo.entryText ? `<p>${zoneInfo.entryText}</p>` : '');
choicesElement.innerHTML = '';
// --- Navigation Buttons (Always Show, Disable if no neighbor) ---
const neighbors = getZoneNeighbors(zoneId);
const directions = {'north': 'North', 'south': 'South', 'east': 'East', 'west': 'West'};
console.log("Adding neighbor buttons:", neighbors);
for(const dir in directions) {
const neighborId = neighbors[dir];
const button = document.createElement('button');
button.classList.add('choice-button');
button.textContent = `Go ${directions[dir]}`;
if (neighborId) {
button.addEventListener('click', () => transitionToZone(neighborId));
} else {
button.disabled = true; // Disable if no neighbor in this direction
}
choicesElement.appendChild(button);
}
// --- Zone Specific Action Buttons ---
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');
if (option.action === 'triggerCombat') { // Style combat buttons differently
button.classList.add('combat-button');
}
button.textContent = option.text;
button.addEventListener('click', () => handleZoneAction(option));
choicesElement.appendChild(button);
});
}
// --- Combat UI ---
if (gameState.combat?.active) {
choicesElement.innerHTML += `
<div id="combat-ui">
<p class="message message-combat">Combat vs ${gameState.combat.enemyName}! (Enemy HP: ${gameState.combat.enemyHp})</p>
<button class="choice-button combat-button" onclick="handleCombatAction('attack')">Roll to Attack!</button>
</div>`;
}
if (choicesElement.innerHTML === '') { // Check if empty after adding everything
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.");
}
// Wrapper for potential inline use later (though addEventListener is preferred)
function transitionToZoneWrapper(zoneId) { transitionToZone(zoneId); }
window.transitionToZoneWrapper = transitionToZoneWrapper;
function handleZoneAction(option) {
console.log("Handling zone action:", option);
if (option.action === 'triggerCombat' && option.enemy) {
startCombat(option.enemy);
} else {
currentMessage = `<p class="message message-info">Action '${option.action || option.text}' not fully implemented yet.</p>`;
renderCurrentPageUI(); // Re-render to show message
}
}
window.handleZoneAction = handleZoneAction; // Make accessible
function updateStatsDisplay() {
if (!gameState.character || !statsElement) return;
const { hp, maxHp, xp, strength, dexterity, constitution, intelligence, wisdom, charisma } = gameState.character.stats;
const hpColor = hp / maxHp < 0.3 ? '#f88' : (hp / maxHp < 0.6 ? '#fd5' : '#8f8');
// Calculate basic modifiers (D&D style)
const strMod = Math.floor((strength - 10) / 2);
const dexMod = Math.floor((dexterity - 10) / 2);
const conMod = Math.floor((constitution - 10) / 2);
const intMod = Math.floor((intelligence - 10) / 2);
const wisMod = Math.floor((wisdom - 10) / 2);
const chaMod = Math.floor((charisma - 10) / 2);
statsElement.innerHTML = `<strong>Stats:</strong>
<span style="color:${hpColor}">HP: ${hp}/${maxHp}</span> <span>XP: ${xp}</span><br>
<span>Str: ${strength} (${strMod>=0?'+':''}${strMod})</span>
<span>Dex: ${dexterity} (${dexMod>=0?'+':''}${dexMod})</span>
<span>Con: ${constitution} (${conMod>=0?'+':''}${conMod})</span>
<span>Int: ${intelligence} (${intMod>=0?'+':''}${intMod})</span>
<span>Wis: ${wisdom} (${wisMod>=0?'+':''}${wisMod})</span>
<span>Cha: ${charisma} (${chaMod>=0?'+':''}${chaMod})</span>`;
}
function updateInventoryDisplay() {
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'}`;
invHtml += `<span class="item-tag ${itemClass}" title="${itemDef.description}">${item}</span>`;
});
}
inventoryElement.innerHTML = invHtml;
// No placement listeners needed now
}
function updateActionInfo() {
if (!actionInfoElement || !gameState ) return;
const mode = gameState.combat?.active ? "Combat" : "Explore";
actionInfoElement.textContent = `Zone: ${gameState.currentZoneId || 'None'} | Mode: ${mode}`;
}
// --- Combat & Item Functions ---
function startCombat(enemyTypeId) {
const enemyBase = enemyData[enemyTypeId];
if (!enemyBase) {
console.error("Unknown enemy type:", enemyTypeId);
currentMessage = `<p class="message message-failure">Error: Unknown enemy encountered!</p>`;
renderCurrentPageUI();
return;
}
gameState.combat = {
active: true,
enemyId: enemyTypeId,
enemyName: enemyBase.name,
enemyHp: enemyBase.hp,
enemyMaxHp: enemyBase.hp, // Store max HP
enemyDefense: enemyBase.defense,
enemyDamage: enemyBase.attackDamage,
enemyXp: enemyBase.xp,
enemyDrops: enemyBase.drops || []
};
currentMessage = `<p class="message message-combat">A wild ${enemyBase.name} appears!</p>`;
renderCurrentPageUI();
}
function handleCombatAction(action) {
if (!gameState.combat?.active) return;
currentMessage = ""; // Clear previous combat messages
if (action === 'attack') {
// --- Player Turn ---
const roll = Math.floor(Math.random() * 20) + 1;
const attackBonus = Math.floor((gameState.character.stats.strength - 10) / 2); // Simple STR mod
const totalAttack = roll + attackBonus;
const hit = totalAttack >= gameState.combat.enemyDefense;
displayDiceRoll(roll, hit); // Show the dice roll visually
if (hit) {
const weapon = gameState.character.inventory.find(i => itemsData[i]?.type === 'weapon');
const baseDamage = itemsData[weapon]?.baseDamage || 1; // Use weapon or 1
const damageRoll = Math.max(1, Math.floor(Math.random() * baseDamage) + 1 + attackBonus); // Add STR mod to damage
gameState.combat.enemyHp -= damageRoll;
currentMessage += `<p class="message message-success">You hit the ${gameState.combat.enemyName} for ${damageRoll} damage! (Rolled ${totalAttack} vs AC ${gameState.combat.enemyDefense})</p>`;
} else {
currentMessage += `<p class="message message-failure">You missed the ${gameState.combat.enemyName}. (Rolled ${totalAttack} vs AC ${gameState.combat.enemyDefense})</p>`;
}
// --- Check Enemy Defeat ---
if (gameState.combat.enemyHp <= 0) {
currentMessage += `<p class="message message-success"><b>You defeated the ${gameState.combat.enemyName}!</b></p>`;
gameState.character.stats.xp += gameState.combat.enemyXp;
currentMessage += `<p class="message message-info"><em>Gained ${gameState.combat.enemyXp} XP.</em></p>`;
if (gameState.combat.enemyDrops.length > 0) {
const droppedItemName = gameState.combat.enemyDrops[Math.floor(Math.random() * gameState.combat.enemyDrops.length)];
dropItemInZone(droppedItemName, new THREE.Vector3(Math.random()*2-1, 0, Math.random()*2-1));
currentMessage += `<p class="message message-item"><em>The ${gameState.combat.enemyName} dropped a ${droppedItemName}!</em></p>`;
}
gameState.combat = null; // End combat
renderCurrentPageUI(); // Update UI completely
return; // Exit function after enemy defeat
}
// --- Enemy Turn (if player didn't defeat it) ---
const enemyAttackRoll = Math.floor(Math.random() * 20) + 1 + 3; // Enemy bonus = +3
const playerDefense = 10 + Math.floor((gameState.character.stats.dexterity - 10) / 2); // Simple AC
if (enemyAttackRoll >= playerDefense) {
const enemyDamageDealt = Math.max(1, Math.floor(Math.random() * gameState.combat.enemyDamage) + 1);
gameState.character.stats.hp -= enemyDamageDealt;
currentMessage += `<p class="message message-failure">The ${gameState.combat.enemyName} hits you for ${enemyDamageDealt} damage! (Rolled ${enemyAttackRoll} vs AC ${playerDefense})</p>`;
if (gameState.character.stats.hp <= 0) {
currentMessage += `<p class="message message-failure"><b>You have been defeated!</b></p>`;
gameState.combat = null; // End combat
// TODO: Implement proper game over / respawn
gameState.character.stats.hp = 1; // Temp: reset to 1 hp
transitionToZone(getZoneId(1,1)); // Go back to start
return; // Exit after player defeat
}
} else {
currentMessage += `<p class="message message-info">The ${gameState.combat.enemyName} misses you. (Rolled ${enemyAttackRoll} vs AC ${playerDefense})</p>`;
}
renderCurrentPageUI(); // Update UI after both turns
}
}
window.handleCombatAction = handleCombatAction; // Make accessible
function displayDiceRoll(result, success) {
if (!threeFont) return; // Can't display if font isn't loaded
// Clear previous dice rolls immediately
activeTimeouts.forEach(timeoutId => clearTimeout(timeoutId));
activeTimeouts = [];
worldGroup.children.filter(c => c.userData.isDiceRoll).forEach(c => worldGroup.remove(c));
const textGeo = new TextGeometry(result.toString(), { font: threeFont, size: 0.8, height: 0.1, curveSegments: 4 });
textGeo.computeBoundingBox();
const textWidth = textGeo.boundingBox.max.x - textGeo.boundingBox.min.x;
const textMat = MAT.text.clone();
textMat.color.setHex(success ? 0x88ff88 : 0xff8888);
const textMesh = new THREE.Mesh(textGeo, textMat);
textMesh.userData.isDiceRoll = true; // Mark for cleanup
const distance = 4; // How far in front of camera
const textPos = camera.position.clone().add(camera.getWorldDirection(new THREE.Vector3()).multiplyScalar(distance));
textMesh.position.copy(textPos);
textMesh.position.y += 1.5; // Higher up
textMesh.position.x -= textWidth / 2;
textMesh.quaternion.copy(camera.quaternion);
worldGroup.add(textMesh); // Add to world group, not scene directly
// Animate and remove
const duration = 2.0; // seconds
const startTime = clock.getElapsedTime();
textMesh.userData.startTime = startTime;
textMesh.userData.update = (time) => {
const elapsed = time - textMesh.userData.startTime;
if (elapsed >= duration) {
if (textMesh.parent) textMesh.parent.remove(textMesh);
delete textMesh.userData.update;
} else {
textMesh.position.y += 0.01; // Float up slowly
textMesh.material.opacity = 1.0 - (elapsed / duration); // Fade out (requires transparent=true on material)
// textMesh.scale.setScalar(1 + elapsed * 0.5); // Optionally grow
}
};
}
function dropItemInZone(itemName, positionOffset = new THREE.Vector3(0, 0, 0)) {
const currentGroup = zoneGroups[gameState.currentZoneId]?.group;
if (!currentGroup || !itemsData[itemName]) return;
const itemDef = itemsData[itemName];
const itemGeo = new THREE.BoxGeometry(0.4, 0.4, 0.4);
const itemMat = MAT.simple.clone();
if(itemDef.type === 'weapon') itemMat.color.setHex(0xcc6666);
else if(itemDef.type === 'consumable') itemMat.color.setHex(0xcc9966);
else if(itemDef.type === 'quest') itemMat.color.setHex(0xcccc66);
else itemMat.color.setHex(0xaaaaee);
const dropPos = new THREE.Vector3(positionOffset.x, 0.2, positionOffset.z);
const droppedMesh = createMesh(itemGeo, itemMat, dropPos);
droppedMesh.userData = { isPickupable: true, itemName: itemName, description: `Dropped ${itemName}` };
currentGroup.add(droppedMesh);
console.log(`Dropped ${itemName} in zone ${gameState.currentZoneId}`);
}
function pickupItem() {
if (gameState.combat?.active) return; // No pickup during combat
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) {
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;
clickedObject.userData.isPickupable = false;
// Consider removing object fully: clickedObject.parent.remove(clickedObject);
renderCurrentPageUI();
}
}
}
// --- 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.");
loadFontAndStart(); // Load font, then start game
console.log("Initialization sequence 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>