awacke1's picture
Update index.html
0a69594 verified
raw
history blame
32.6 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Choose Your Own Procedural Adventure</title>
<style>
/* --- Base Styles --- */
body {
font-family: 'Courier New', monospace;
background-color: #222; /* Dark background */
color: #eee; /* Light text */
margin: 0;
padding: 0;
overflow: hidden; /* Prevent scrollbars */
display: flex;
flex-direction: column;
height: 100vh; /* Full viewport height */
}
/* --- Layout --- */
#game-container {
display: flex;
flex-grow: 1; /* Fill remaining vertical space */
overflow: hidden;
}
#scene-container {
flex-grow: 3; /* Give more space to 3D view */
position: relative;
border-right: 2px solid #555;
min-width: 200px;
background-color: #1a1a1a;
height: 100%;
box-sizing: border-box;
}
#ui-container {
flex-grow: 2; /* Space for UI elements */
padding: 20px;
overflow-y: auto; /* Allow scrolling */
background-color: #333;
min-width: 280px;
height: 100%;
box-sizing: border-box;
display: flex; /* Enable flex column layout */
flex-direction: column;
}
#scene-container canvas { display: block; }
/* --- UI Elements --- */
#story-title {
color: #ffcc66;
margin-top: 0;
margin-bottom: 15px;
border-bottom: 1px solid #555;
padding-bottom: 10px;
font-size: 1.4em;
}
#story-content {
margin-bottom: 20px;
line-height: 1.6;
flex-grow: 1; /* Allow story content to expand */
}
#story-content p { margin-bottom: 1em; }
#story-content p:last-child { margin-bottom: 0; }
#stats-inventory-container {
margin-bottom: 20px;
padding-bottom: 15px;
border-bottom: 1px solid #555;
font-size: 0.9em;
}
#stats-display, #inventory-display {
margin-bottom: 10px;
line-height: 1.8;
}
#stats-display span, #inventory-display span {
display: inline-block;
background-color: #444;
padding: 3px 8px;
border-radius: 15px;
margin-right: 8px;
margin-bottom: 5px;
border: 1px solid #666;
white-space: nowrap;
}
#stats-display strong, #inventory-display strong { color: #aaa; margin-right: 5px; }
#inventory-display em { color: #888; font-style: normal; }
/* Item Type Styling */
#inventory-display .item-quest { background-color: #666030; border-color: #999048;}
#inventory-display .item-weapon { background-color: #663030; border-color: #994848;}
#inventory-display .item-armor { background-color: #306630; border-color: #489948;}
#inventory-display .item-spell { background-color: #303066; border-color: #484899;}
#inventory-display .item-unknown { background-color: #555; border-color: #777;}
#choices-container {
margin-top: auto; /* Push choices to bottom if space allows */
padding-top: 15px;
border-top: 1px solid #555;
}
#choices-container h3 { margin-top: 0; margin-bottom: 10px; color: #aaa; }
#choices { display: flex; flex-direction: column; gap: 10px; }
.choice-button {
display: block; width: 100%; padding: 10px 12px; margin-bottom: 0;
background-color: #555; color: #eee; border: 1px solid #777;
border-radius: 5px; cursor: pointer; text-align: left;
font-family: 'Courier New', monospace; font-size: 1em;
transition: background-color 0.2s, border-color 0.2s;
box-sizing: border-box;
}
.choice-button:hover:not(:disabled) { background-color: #d4a017; color: #222; border-color: #b8860b; }
.choice-button:disabled { background-color: #444; color: #888; cursor: not-allowed; border-color: #666; opacity: 0.7; }
</style>
</head>
<body>
<div id="game-container">
<div id="scene-container">
</div>
<div id="ui-container">
<h2 id="story-title">Loading Adventure...</h2>
<div id="story-content">
<p>Please wait while the adventure loads.</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';
// Optional: Add OrbitControls for debugging/viewing scene
// import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// --- 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');
// --- Three.js Setup ---
let scene, camera, renderer;
let currentAssemblyGroup = null; // To hold the current scene objects
// let controls; // Optional OrbitControls
// --- Shared Materials ---
const stoneMaterial = new THREE.MeshStandardMaterial({ color: 0x888888, roughness: 0.8, metalness: 0.1 });
const woodMaterial = new THREE.MeshStandardMaterial({ color: 0x8B4513, roughness: 0.7, metalness: 0 });
const darkWoodMaterial = new THREE.MeshStandardMaterial({ color: 0x5C3D20, roughness: 0.7, metalness: 0 });
const leafMaterial = new THREE.MeshStandardMaterial({ color: 0x2E8B57, roughness: 0.6, metalness: 0 });
const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x556B2F, roughness: 0.9, metalness: 0 });
const metalMaterial = new THREE.MeshStandardMaterial({ color: 0xaaaaaa, metalness: 0.8, roughness: 0.3 });
// Add other materials as needed by assemblies...
const templeMaterial = new THREE.MeshStandardMaterial({ color: 0xA99B78, roughness: 0.7, metalness: 0.1 });
const errorMaterial = new THREE.MeshStandardMaterial({ color: 0xffa500, roughness: 0.5 });
const gameOverMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000, roughness: 0.5 });
function initThreeJS() {
console.log("Initializing Three.js with procedural scenes...");
if (!sceneContainer) { console.error("Scene container not found!"); return; }
scene = new THREE.Scene();
scene.background = new THREE.Color(0x222222);
const width = sceneContainer.clientWidth;
const height = sceneContainer.clientHeight;
if (width === 0 || height === 0) { console.warn("Scene container has zero dimensions on init."); }
camera = new THREE.PerspectiveCamera(75, (width / height) || 1, 0.1, 1000);
camera.position.set(0, 2.5, 7); // Adjusted position for better assembly view
camera.lookAt(0, 0.5, 0); // Look slightly down towards assembly center
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(width || 400, height || 300);
renderer.shadowMap.enabled = true; // Enable shadows
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
sceneContainer.appendChild(renderer.domElement);
console.log("Renderer initialized.");
// Lighting (Setup for shadows)
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1.2);
directionalLight.position.set(8, 15, 10);
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 1024;
directionalLight.shadow.mapSize.height = 1024;
directionalLight.shadow.camera.near = 0.5;
directionalLight.shadow.camera.far = 50;
const shadowCamSize = 15; // Adjust based on assembly size
directionalLight.shadow.camera.left = -shadowCamSize; directionalLight.shadow.camera.right = shadowCamSize;
directionalLight.shadow.camera.top = shadowCamSize; directionalLight.shadow.camera.bottom = -shadowCamSize;
scene.add(directionalLight);
// Remove the single cube creation - scene objects are handled by updateScene now
window.addEventListener('resize', onWindowResize, false);
setTimeout(onWindowResize, 100); // Initial resize call
animate();
console.log("Animation loop started.");
}
function onWindowResize() {
if (!renderer || !camera || !sceneContainer) return;
const width = sceneContainer.clientWidth;
const height = sceneContainer.clientHeight;
if (width > 0 && height > 0) {
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
}
}
function animate() {
requestAnimationFrame(animate);
// Optional: Add subtle animation to the entire assembly
// if (currentAssemblyGroup) {
// currentAssemblyGroup.rotation.y += 0.0005;
// }
if (renderer && scene && camera) {
renderer.render(scene, camera);
}
}
// --- Helper Functions ---
function createMesh(geometry, material, position = { x: 0, y: 0, z: 0 }, rotation = { x: 0, y: 0, z: 0 }, scale = { x: 1, y: 1, z: 1 }) {
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(position.x, position.y, position.z);
mesh.rotation.set(rotation.x, rotation.y, rotation.z);
mesh.scale.set(scale.x, scale.y, scale.z);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function createGroundPlane(material = groundMaterial, size = 20) {
const groundGeo = new THREE.PlaneGeometry(size, size);
const ground = new THREE.Mesh(groundGeo, material);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.05;
ground.receiveShadow = true;
ground.castShadow = false; // Ground itself doesn't usually cast shadows
return ground;
}
// --- Procedural Generation Functions ---
// (Using the simpler versions for now)
function createDefaultAssembly() {
const group = new THREE.Group();
const sphereGeo = new THREE.SphereGeometry(0.5, 16, 16);
group.add(createMesh(sphereGeo, stoneMaterial, { x: 0, y: 0.5, z: 0 }));
group.add(createGroundPlane());
return group;
}
function createCityGatesAssembly() {
const group = new THREE.Group();
const gateWallHeight = 4; const gateWallWidth = 1.5; const gateWallDepth = 0.8;
const archHeight = 1; const archWidth = 3;
const towerLeftGeo = new THREE.BoxGeometry(gateWallWidth, gateWallHeight, gateWallDepth);
group.add(createMesh(towerLeftGeo, stoneMaterial, { x: -(archWidth / 2 + gateWallWidth / 2), y: gateWallHeight / 2, z: 0 }));
const towerRightGeo = new THREE.BoxGeometry(gateWallWidth, gateWallHeight, gateWallDepth);
group.add(createMesh(towerRightGeo, stoneMaterial, { x: (archWidth / 2 + gateWallWidth / 2), y: gateWallHeight / 2, z: 0 }));
const archGeo = new THREE.BoxGeometry(archWidth, archHeight, gateWallDepth);
group.add(createMesh(archGeo, stoneMaterial, { x: 0, y: gateWallHeight - archHeight / 2, z: 0 }));
// Simplified crenellations
const crenellationSize = 0.4; const crenGeo = new THREE.BoxGeometry(crenellationSize, crenellationSize, gateWallDepth * 1.1);
for (let i = -1; i <= 1; i += 2) { group.add(createMesh(crenGeo.clone(), stoneMaterial, { x: -(archWidth / 2 + gateWallWidth / 2) + i * crenellationSize * 0.7, y: gateWallHeight + crenellationSize / 2, z: 0 })); group.add(createMesh(crenGeo.clone(), stoneMaterial, { x: (archWidth / 2 + gateWallWidth / 2) + i * crenellationSize * 0.7, y: gateWallHeight + crenellationSize / 2, z: 0 })); }
group.add(createMesh(crenGeo.clone(), stoneMaterial, { x: 0, y: gateWallHeight + archHeight - crenellationSize / 2, z: 0 }));
group.add(createGroundPlane(stoneMaterial));
return group;
}
function createWeaponsmithAssembly() {
// Simple Box Building + Chimney
const group = new THREE.Group();
const buildingWidth = 3; const buildingHeight = 2.5; const buildingDepth = 3.5;
const buildingGeo = new THREE.BoxGeometry(buildingWidth, buildingHeight, buildingDepth);
group.add(createMesh(buildingGeo, darkWoodMaterial, { x: 0, y: buildingHeight / 2, z: 0 }));
const chimneyHeight = 3.5; const chimneyGeo = new THREE.CylinderGeometry(0.3, 0.4, chimneyHeight, 8);
group.add(createMesh(chimneyGeo, stoneMaterial, { x: buildingWidth * 0.3, y: chimneyHeight / 2, z: -buildingDepth * 0.3 }));
group.add(createGroundPlane());
return group;
}
function createTempleAssembly() {
// Simple Base + Columns + Roof Slab
const group = new THREE.Group();
const baseSize = 5; const baseHeight = 0.5; const columnHeight = 3; const columnRadius = 0.25; const roofHeight = 0.5;
const baseGeo = new THREE.BoxGeometry(baseSize, baseHeight, baseSize); group.add(createMesh(baseGeo, templeMaterial, { x: 0, y: baseHeight / 2, z: 0 }));
const colGeo = new THREE.CylinderGeometry(columnRadius, columnRadius, columnHeight, 12);
const colPositions = [ { x: -baseSize / 3, z: -baseSize / 3 }, { x: baseSize / 3, z: -baseSize / 3 }, { x: -baseSize / 3, z: baseSize / 3 }, { x: baseSize / 3, z: baseSize / 3 }];
colPositions.forEach(pos => group.add(createMesh(colGeo.clone(), templeMaterial, { x: pos.x, y: baseHeight + columnHeight / 2, z: pos.z })));
const roofGeo = new THREE.BoxGeometry(baseSize * 0.9, roofHeight, baseSize * 0.9); group.add(createMesh(roofGeo, templeMaterial, { x: 0, y: baseHeight + columnHeight + roofHeight / 2, z: 0 }));
group.add(createGroundPlane());
return group;
}
function createResistanceMeetingAssembly() {
// Simple table + stools
const group = new THREE.Group();
const tableWidth = 2; const tableHeight = 0.8; const tableDepth = 1; const tableThickness = 0.1;
const tableTopGeo = new THREE.BoxGeometry(tableWidth, tableThickness, tableDepth); group.add(createMesh(tableTopGeo, woodMaterial, { x: 0, y: tableHeight - tableThickness / 2, z: 0 }));
const legHeight = tableHeight - tableThickness; const legSize = 0.1; const legGeo = new THREE.BoxGeometry(legSize, legHeight, legSize); const legOffsetW = tableWidth / 2 - legSize * 1.5; const legOffsetD = tableDepth / 2 - legSize * 1.5; group.add(createMesh(legGeo, woodMaterial, { x: -legOffsetW, y: legHeight / 2, z: -legOffsetD })); group.add(createMesh(legGeo.clone(), woodMaterial, { x: legOffsetW, y: legHeight / 2, z: -legOffsetD })); group.add(createMesh(legGeo.clone(), woodMaterial, { x: -legOffsetW, y: legHeight / 2, z: legOffsetD })); group.add(createMesh(legGeo.clone(), woodMaterial, { x: legOffsetW, y: legHeight / 2, z: legOffsetD }));
const stoolSize = 0.4; const stoolGeo = new THREE.BoxGeometry(stoolSize, stoolSize * 0.8, stoolSize); group.add(createMesh(stoolGeo, darkWoodMaterial, { x: -tableWidth * 0.6, y: stoolSize * 0.4, z: 0 })); group.add(createMesh(stoolGeo.clone(), darkWoodMaterial, { x: tableWidth * 0.6, y: stoolSize * 0.4, z: 0 }));
group.add(createGroundPlane(stoneMaterial));
return group;
}
function createForestAssembly(treeCount = 10, area = 10) {
// Simple Trees (Cylinder + Sphere)
const group = new THREE.Group();
const createTree = (x, z) => { const treeGroup = new THREE.Group(); const trunkHeight = Math.random() * 1.5 + 2; const trunkRadius = Math.random() * 0.1 + 0.1; const trunkGeo = new THREE.CylinderGeometry(trunkRadius * 0.7, trunkRadius, trunkHeight, 8); treeGroup.add(createMesh(trunkGeo, woodMaterial, { x: 0, y: trunkHeight / 2, z: 0 })); const foliageRadius = trunkHeight * 0.4 + 0.2; const foliageGeo = new THREE.SphereGeometry(foliageRadius, 8, 6); treeGroup.add(createMesh(foliageGeo, leafMaterial, { x: 0, y: trunkHeight * 0.9, z: 0 })); treeGroup.position.set(x, 0, z); return treeGroup; };
for (let i = 0; i < treeCount; i++) { const x = (Math.random() - 0.5) * area; const z = (Math.random() - 0.5) * area; if (Math.sqrt(x*x + z*z) > 1.0) group.add(createTree(x, z)); } // Avoid center
group.add(createGroundPlane(groundMaterial, area * 1.1));
return group;
}
function createRoadAmbushAssembly() { /* ... (calls simple createForestAssembly) ... */
const group = new THREE.Group(); const area = 12;
const forestGroup = createForestAssembly(8, area); group.add(forestGroup); // Fewer trees
const roadWidth = 3; const roadLength = area * 1.2; const roadGeo = new THREE.PlaneGeometry(roadWidth, roadLength); const roadMaterial = new THREE.MeshStandardMaterial({ color: 0x966F33, roughness: 0.9 }); const road = createMesh(roadGeo, roadMaterial, {x: 0, y: 0.01, z: 0}, {x: -Math.PI / 2}); road.receiveShadow = true; group.add(road);
const rockGeo = new THREE.SphereGeometry(0.5, 5, 4); const rockMaterial = new THREE.MeshStandardMaterial({ color: 0x666666, roughness: 0.8 }); group.add(createMesh(rockGeo, rockMaterial, {x: roadWidth * 0.7, y: 0.25, z: 1}, {y: Math.random() * Math.PI})); group.add(createMesh(rockGeo.clone().scale(0.8,0.8,0.8), rockMaterial, {x: -roadWidth * 0.8, y: 0.2, z: -2}, {y: Math.random() * Math.PI}));
return group;
}
function createForestEdgeAssembly() { /* ... (calls simple createForestAssembly) ... */
const group = new THREE.Group(); const area = 15;
const forestGroup = createForestAssembly(15, area); // Generate full forest
// Keep only trees on one side
const treesToRemove = [];
forestGroup.children.forEach(child => { if(child.type === 'Group' && child.position.x > 0) { treesToRemove.push(child); } }); // Mark trees on positive X
treesToRemove.forEach(tree => forestGroup.remove(tree)); // Remove them
group.add(forestGroup); // Add remaining trees and ground
return group;
}
function createPrisonerCellAssembly() { /* ... (Simplified version) ... */
const group = new THREE.Group(); const cellSize = 3; const wallHeight = 2.5; const wallThickness = 0.2; const barRadius = 0.05; const barSpacing = 0.25;
const cellFloorMaterial = stoneMaterial.clone(); cellFloorMaterial.color.setHex(0x555555); group.add(createGroundPlane(cellFloorMaterial, cellSize));
const wallBackGeo = new THREE.BoxGeometry(cellSize, wallHeight, wallThickness); group.add(createMesh(wallBackGeo, stoneMaterial, { x: 0, y: wallHeight / 2, z: -cellSize / 2 })); const wallSideGeo = new THREE.BoxGeometry(wallThickness, wallHeight, cellSize); group.add(createMesh(wallSideGeo, stoneMaterial, { x: -cellSize / 2, y: wallHeight / 2, z: 0 })); group.add(createMesh(wallSideGeo.clone(), stoneMaterial, { x: cellSize / 2, y: wallHeight / 2, z: 0 }));
const barGeo = new THREE.CylinderGeometry(barRadius, barRadius, wallHeight, 8); const numBars = Math.floor(cellSize / barSpacing); for (let i = 0; i < numBars; i++) { const xPos = -cellSize / 2 + (i + 0.5) * barSpacing; group.add(createMesh(barGeo.clone(), metalMaterial, { x: xPos, y: wallHeight / 2, z: cellSize / 2 })); }
return group;
}
function createGameOverAssembly() { /* ... (same as before) ... */
const group = new THREE.Group(); const boxGeo = new THREE.BoxGeometry(2, 2, 2); group.add(createMesh(boxGeo, gameOverMaterial, { x: 0, y: 1, z: 0 })); group.add(createGroundPlane(stoneMaterial.clone().set({color: 0x333333}))); return group;
}
function createErrorAssembly() { /* ... (same as before) ... */
const group = new THREE.Group(); const coneGeo = new THREE.ConeGeometry( 0.8, 1.5, 8 ); group.add(createMesh(coneGeo, errorMaterial, { x: 0, y: 0.75, z: 0 })); group.add(createGroundPlane()); return group;
}
// --- Game Data ---
const gameData = {
"1": { title: "The Beginning", content: `<p>...</p>`, options: [ { text: "Visit the local weaponsmith", next: 2 }, { text: "Seek wisdom at the temple", next: 3 }, { text: "Meet the resistance leader", next: 4 } ], illustration: "city-gates" },
"2": { title: "The Weaponsmith", content: `<p>...</p>`, options: [ { text: "Take the Flaming Sword", next: 5, addItem: "Flaming Sword" }, { text: "Choose the Whispering Bow", next: 5, addItem: "Whispering Bow" }, { text: "Select the Guardian Shield", next: 5, addItem: "Guardian Shield" } ], illustration: "weaponsmith" },
"3": { title: "The Ancient Temple", content: `<p>...</p>`, options: [ { text: "Learn Healing Light", next: 5, addItem: "Healing Light Spell" }, { text: "Master Shield of Faith", next: 5, addItem: "Shield of Faith Spell" }, { text: "Study Binding Runes", next: 5, addItem: "Binding Runes Scroll" } ], illustration: "temple" },
"4": { title: "The Resistance Leader", content: `<p>...</p>`, options: [ { text: "Take the Secret Tunnel Map", next: 5, addItem: "Secret Tunnel Map" }, { text: "Accept Poison Daggers", next: 5, addItem: "Poison Daggers" }, { text: "Choose the Master Key", next: 5, addItem: "Master Key" } ], illustration: "resistance-meeting" },
"5": { title: "The Journey Begins", content: `<p>...</p>`, options: [ { text: "Take the main road", next: 6 }, { text: "Follow the river path", next: 7 }, { text: "Brave the ruins shortcut", next: 8 } ], illustration: "shadowwood-forest" },
"6": { title: "Ambush!", content: "<p>...</p>", options: [{ text: "Fight!", next: 9 }, { text: "Try to flee!", next: 10 }], illustration: "road-ambush" },
"7": { title: "River Path", content: "<p>...</p>", options: [{ text: "Keep going", next: 15 }], illustration: "river-spirit" /* Uses default for now */ },
"8": { title: "Ancient Ruins", content: "<p>...</p>", options: [{ text: "Search carefully", next: 15 }], illustration: "ancient-ruins" /* Uses default for now */ },
"9": { title: "Victory!", content: "<p>...</p>", options: [{ text: "Proceed", next: 15 }], illustration: "forest-edge", reward: { statIncrease: { stat: "strength", amount: 1 } } }, // Example reward added back
"10": { title: "Captured!", content: "<p>...</p>", options: [{ text: "Accept fate", next: 20 }], illustration: "prisoner-cell" },
"15": { title: "Fortress Plains", content: "<p>...</p>", options: [{ text: "March onward", next: 99 }], illustration: "fortress-plains" /* Uses default */ },
"20": { title: "Prison Cell", content: "<p>...</p>", options: [{ text: "Wait", next: 99 }], illustration: "prisoner-cell" },
"99": { title: "Game Over", content: "<p>...</p>", options: [{ text: "Restart", next: 1 }], illustration: "game-over", gameOver: true }
};
const itemsData = {
"Flaming Sword": { type: "weapon", description: "A fiery blade" }, "Whispering Bow": { type: "weapon", description: "A silent bow" }, "Guardian Shield": { type: "armor", description: "A protective shield" }, "Healing Light Spell": { type: "spell", description: "Mends minor wounds" }, "Shield of Faith Spell": { type: "spell", description: "Temporary shield" }, "Binding Runes Scroll": { type: "spell", description: "Binds an enemy" }, "Secret Tunnel Map": { type: "quest", description: "Shows a hidden path" }, "Poison Daggers": { type: "weapon", description: "Daggers with poison" }, "Master Key": { type: "quest", description: "Unlocks many doors" },
};
// --- Game State ---
let gameState = {
currentPageId: 1, inventory: [],
stats: { courage: 7, wisdom: 5, strength: 6, hp: 30, maxHp: 30 }
};
// --- Game Logic Functions ---
function startGame() {
gameState = { currentPageId: 1, inventory: [], stats: { courage: 7, wisdom: 5, strength: 6, hp: 30, maxHp: 30 } };
renderPage(gameState.currentPageId);
}
function renderPage(pageId) {
const page = gameData[pageId];
if (!page) { console.error(`Page data error for ID: ${pageId}`); storyTitleElement.textContent = "Error"; storyContentElement.innerHTML = "<p>Could not load page data.</p>"; choicesElement.innerHTML = '<button class="choice-button" onclick="window.location.reload()">Restart</button>'; updateScene('error'); return; } // Changed restart to reload for simplicity here
storyTitleElement.textContent = page.title || "Untitled Page"; storyContentElement.innerHTML = page.content || "<p>...</p>";
updateStatsDisplay(); updateInventoryDisplay();
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; let requirementMet = true;
if (option.requireItem && !gameState.inventory.includes(option.requireItem)) { requirementMet = false; button.title = `Requires: ${option.requireItem}`; button.disabled = true; }
if (requirementMet) { const choiceData = { nextPage: option.next }; if (option.addItem) { choiceData.addItem = option.addItem; } button.onclick = () => handleChoiceClick(choiceData); } else { button.classList.add('disabled'); } choicesElement.appendChild(button); });
} else { const button = document.createElement('button'); button.classList.add('choice-button'); button.textContent = page.gameOver ? "Restart Adventure" : "Continue (End)"; button.onclick = () => handleChoiceClick({ nextPage: page.gameOver ? 1 : 99 }); choicesElement.appendChild(button); }
updateScene(page.illustration || 'default');
}
function handleChoiceClick(choiceData) {
const nextPageId = parseInt(choiceData.nextPage); const itemToAdd = choiceData.addItem; if (isNaN(nextPageId)) { console.error("Invalid nextPageId:", choiceData.nextPage); return; }
if (itemToAdd && !gameState.inventory.includes(itemToAdd)) { gameState.inventory.push(itemToAdd); console.log("Added item:", itemToAdd); }
gameState.currentPageId = nextPageId; const nextPageData = gameData[nextPageId];
if (nextPageData) {
if (nextPageData.hpLoss) { gameState.stats.hp = Math.max(0, gameState.stats.hp - nextPageData.hpLoss); console.log(`Lost ${nextPageData.hpLoss} HP.`); if (gameState.stats.hp <= 0) { console.log("Player died!"); renderPage(99); return; } }
if (nextPageData.reward && nextPageData.reward.statIncrease) { const stat = nextPageData.reward.statIncrease.stat; const amount = nextPageData.reward.statIncrease.amount; if (gameState.stats.hasOwnProperty(stat)) { gameState.stats[stat] += amount; console.log(`Stat ${stat} increased by ${amount}.`); } }
// Add item reward processing if needed from reward object
if (nextPageData.reward && nextPageData.reward.addItem && !gameState.inventory.includes(nextPageData.reward.addItem)) { gameState.inventory.push(nextPageData.reward.addItem); console.log(`Found item: ${nextPageData.reward.addItem}`); }
}
else { console.error(`Data for page ${nextPageId} not found!`); renderPage(99); return; }
renderPage(nextPageId); // Render the target page
}
function updateStatsDisplay() { statsElement.innerHTML = `<strong>Stats:</strong> <span>HP: ${gameState.stats.hp}/${gameState.stats.maxHp}</span> <span>Str: ${gameState.stats.strength}</span> <span>Wis: ${gameState.stats.wisdom}</span> <span>Cor: ${gameState.stats.courage}</span>`; }
function updateInventoryDisplay() { let inventoryHTML = '<strong>Inventory:</strong> '; if (gameState.inventory.length === 0) { inventoryHTML += '<em>Empty</em>'; } else { gameState.inventory.forEach(item => { const itemInfo = itemsData[item] || { type: 'unknown', description: '???' }; const itemClass = `item-${itemInfo.type || 'unknown'}`; inventoryHTML += `<span class="${itemClass}" title="${itemInfo.description}">${item}</span>`; }); } inventoryElement.innerHTML = inventoryHTML; }
// Scene Update Function (using procedural assemblies)
function updateScene(illustrationKey) {
console.log(`Updating scene to: ${illustrationKey}`);
if (currentAssemblyGroup) { scene.remove(currentAssemblyGroup); /* TODO: Proper disposal? */ }
currentAssemblyGroup = null; let assemblyFunction;
switch (illustrationKey) {
case 'city-gates': assemblyFunction = createCityGatesAssembly; break;
case 'weaponsmith': assemblyFunction = createWeaponsmithAssembly; break;
case 'temple': assemblyFunction = createTempleAssembly; break;
case 'resistance-meeting': assemblyFunction = createResistanceMeetingAssembly; break;
case 'shadowwood-forest': assemblyFunction = createForestAssembly; break;
case 'road-ambush': assemblyFunction = createRoadAmbushAssembly; break;
case 'forest-edge': assemblyFunction = createForestEdgeAssembly; break;
case 'prisoner-cell': assemblyFunction = createPrisonerCellAssembly; break;
case 'game-over': assemblyFunction = createGameOverAssembly; break;
case 'error': assemblyFunction = createErrorAssembly; break;
// Add cases for other keys, falling back to default
case 'river-spirit': case 'ancient-ruins': case 'fortress-plains': // Fall through
default: console.warn(`No specific assembly for key: "${illustrationKey}". Using default.`); assemblyFunction = createDefaultAssembly; break;
}
try { currentAssemblyGroup = assemblyFunction(); scene.add(currentAssemblyGroup); } catch (error) { console.error(`Error creating assembly for ${illustrationKey}:`, error); currentAssemblyGroup = createErrorAssembly(); scene.add(currentAssemblyGroup); }
}
// --- Initialization ---
document.addEventListener('DOMContentLoaded', () => {
console.log("DOM Ready. Initializing...");
try { initThreeJS(); startGame(); } catch (error) { console.error("Initialization failed:", error); storyTitleElement.textContent = "Error"; storyContentElement.innerHTML = `<p>Initialization Error. Check console (F12).</p><pre>${error}</pre>`; }
});
</script>
</body>
</html>