awacke1 commited on
Commit
4b81814
·
verified ·
1 Parent(s): 756e345

Update game.js

Browse files
Files changed (1) hide show
  1. game.js +328 -756
game.js CHANGED
@@ -1,818 +1,390 @@
1
  import * as THREE from 'three';
2
- import * as CANNON from 'cannon-es';
3
- // import CannonDebugger from 'cannon-es-debugger'; // Keep commented for now
4
 
5
  // --- DOM Elements ---
6
  const sceneContainer = document.getElementById('scene-container');
 
 
 
7
  const statsElement = document.getElementById('stats-display');
8
  const inventoryElement = document.getElementById('inventory-display');
9
- const logElement = document.getElementById('log-display');
10
-
11
- // --- Config ---
12
- const ROOM_SIZE = 10;
13
- const WALL_HEIGHT = 3; // Slightly shorter walls
14
- const WALL_THICKNESS = 0.5;
15
- const CAMERA_Y_OFFSET = 25; // Higher camera
16
- const PLAYER_SPEED = 6;
17
- const PLAYER_RADIUS = 0.5;
18
- const PLAYER_HEIGHT = 1.8; // Visual height
19
- const PLAYER_JUMP_IMPULSE = 7; // Impulse force for jump
20
- const PROJECTILE_SPEED = 15;
21
- const PROJECTILE_RADIUS = 0.2;
22
- const PICKUP_RADIUS = 1.5;
23
- const PICKUP_RADIUS_SQ = PICKUP_RADIUS * PICKUP_RADIUS; // Use squared distance
24
 
25
  // --- Three.js Setup ---
26
- let scene, camera, renderer;
27
- let playerMesh;
28
- const meshesToSync = []; // Holds { mesh: THREE.Mesh, body: CANNON.Body }
29
- const projectiles = []; // Holds { mesh, body, lifetime }
30
- let axesHelper;
31
-
32
- // --- Physics Setup ---
33
- let world;
34
- let playerBody;
35
- const physicsBodies = new Map(); // Use Map<id, CANNON.Body> for easier removal
36
- let groundMaterial, playerMaterial, wallMaterial, monsterMaterial, itemMaterial; // Physics materials
37
- let cannonDebugger = null;
38
-
39
- // --- Game State ---
40
- let gameState = {};
41
- const keysPressed = {};
42
- let gameLoopActive = false;
43
- let animationFrameId = null;
44
- let selectedTool = null; // For building tools later
45
-
46
- // --- Game Data (Ensure starting point 0,0 exists!) ---
47
- const gameData = {
48
- // Structure: "x,y": { type, features?, items?, monsters?, name? }
49
- "0,0": { type: 'city', features: ['door_north', 'item_Key'], name: "City Square"},
50
- "0,1": { type: 'forest', features: ['path_north', 'door_south', 'item_Healing_Potion'], name: "Forest Entrance" },
51
- "0,2": { type: 'forest', features: ['path_south', 'monster_goblin'], name: "Deep Forest"},
52
- "1,1": { type: 'forest', features: ['river', 'path_west'], name: "River Bend" },
53
- "-1,1": { type: 'ruins', features: ['path_east'], name: "Old Ruins"},
54
- "1,0": { type: 'plains', features: ['door_west'], name: "East Plains"},
55
- "-1,0": { type: 'plains', features: ['door_east'], name: "West Plains"},
56
- };
57
-
58
- const itemsData = { // Add 'name' for consistency
59
- "Healing Potion": { name: "Healing Potion", type: "consumable", description: "Restores 10 HP.", hpRestore: 10, model: 'sphere_red' },
60
- "Key": { name: "Key", type: "quest", description: "A rusty key.", model: 'box_gold'},
61
- };
62
-
63
- const monstersData = { // Add 'name'
64
- "goblin": { name: "Goblin", hp: 15, attack: 4, defense: 1, speed: 2.5, model: 'capsule_green', xp: 5 },
65
- };
66
-
67
- // --- Materials and Geometries (Defined once) ---
68
- // Using basic wireframe materials for initial debugging
69
- const debugMaterials = {
70
- player: new THREE.MeshBasicMaterial({ color: 0x0077ff, wireframe: true }),
71
- wall: new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true }),
72
- item: new THREE.MeshBasicMaterial({ color: 0x00ff00, wireframe: true }),
73
- monster: new THREE.MeshBasicMaterial({ color: 0xff00ff, wireframe: true }),
74
- projectile: new THREE.MeshBasicMaterial({ color: 0xffff00 }), // Keep projectiles solid
75
- floor_default: new THREE.MeshBasicMaterial({ color: 0x555555, wireframe: true }), // Wireframe floor
76
- };
77
- // Normal Materials (Use after debugging)
78
- // const normalMaterials = {
79
- // player: new THREE.MeshLambertMaterial({ color: 0x0077ff }),
80
- // wall: new THREE.MeshLambertMaterial({ color: 0x888888 }),
81
- // item_consumable: new THREE.MeshStandardMaterial({ color: 0xff0000, roughness: 0.6 }),
82
- // item_quest: new THREE.MeshStandardMaterial({ color: 0xffd700, roughness: 0.4 }),
83
- // monster_goblin: new THREE.MeshLambertMaterial({ color: 0x00ff00 }),
84
- // floor_city: new THREE.MeshLambertMaterial({ color: 0xdeb887 }),
85
- // floor_forest: new THREE.MeshLambertMaterial({ color: 0x228B22 }),
86
- // // ... add all floor types
87
- // floor_default: new THREE.MeshLambertMaterial({ color: 0xaaaaaa })
88
- // };
89
- const activeMaterials = debugMaterials; // Switch to normalMaterials when ready
90
-
91
- const geometries = { // Keep geometries simple
92
- floor: new THREE.PlaneGeometry(ROOM_SIZE, ROOM_SIZE),
93
- wallNS: new THREE.BoxGeometry(ROOM_SIZE, WALL_HEIGHT, WALL_THICKNESS),
94
- wallEW: new THREE.BoxGeometry(WALL_THICKNESS, WALL_HEIGHT, ROOM_SIZE),
95
- playerCylinder: new THREE.CylinderGeometry(PLAYER_RADIUS, PLAYER_RADIUS, PLAYER_HEIGHT - (PLAYER_RADIUS * 2), 8),
96
- playerSphere: new THREE.SphereGeometry(PLAYER_RADIUS, 8, 8),
97
- playerNose: new THREE.ConeGeometry(PLAYER_RADIUS * 0.3, PLAYER_RADIUS * 0.5, 4),
98
- monsterCapsuleBody: new THREE.CylinderGeometry(0.4, 0.4, 1.0, 8),
99
- monsterCapsuleHead: new THREE.SphereGeometry(0.4, 8, 8),
100
- itemSphere: new THREE.SphereGeometry(0.3, 8, 8),
101
- itemBox: new THREE.BoxGeometry(0.4, 0.4, 0.4),
102
- projectile: new THREE.SphereGeometry(PROJECTILE_RADIUS, 6, 6),
103
- };
104
-
105
-
106
- // --- Initialization ---
107
-
108
- function init() {
109
- console.log("--- Initializing Game ---");
110
- // Reset state and clear arrays/maps
111
- gameState = { inventory: [], stats: { hp: 30, maxHp: 30, strength: 7, wisdom: 5, courage: 6 }, monsters: [], items: [] };
112
- keysPressed = {};
113
- meshesToSync.length = 0;
114
- projectiles.length = 0;
115
- physicsBodies.clear(); // Clear the map
116
-
117
- // Clear previous scene if restarting
118
- if (scene) {
119
- while (scene.children.length > 0) scene.remove(scene.children[0]);
120
- } else {
121
- scene = new THREE.Scene(); // Create scene only if it doesn't exist
122
- }
123
- scene.background = new THREE.Color(0x1a1a1a);
124
-
125
- // Clear previous renderer if restarting
126
- if (renderer) {
127
- renderer.dispose();
128
- if (renderer.domElement.parentNode) {
129
- renderer.domElement.parentNode.removeChild(renderer.domElement);
130
- }
131
- }
132
-
133
- initThreeJS(); // Setup camera, renderer, lights
134
- initPhysics(); // Setup world, materials
135
- initPlayer(); // Setup player mesh + body
136
- generateMap(); // Setup static map meshes + bodies
137
- setupInputListeners();
138
- updateUI();
139
- addLog("Welcome! Move: QWEASDZXC, Jump: X, Attack: Space, Pickup: F", "info");
140
- console.log("--- Initialization Complete ---");
141
-
142
- if (animationFrameId) cancelAnimationFrame(animationFrameId);
143
- gameLoopActive = true;
144
- animate();
145
- }
146
 
147
  function initThreeJS() {
148
- console.log("Initializing Three.js...");
149
- const aspect = sceneContainer.clientWidth / sceneContainer.clientHeight;
150
- camera = new THREE.PerspectiveCamera(60, aspect, 0.1, 1000);
151
- // Set camera directly overhead looking down
152
- camera.position.set(0, CAMERA_Y_OFFSET, 0);
153
- camera.lookAt(0, 0, 0); // Look straight down at origin initially
154
- camera.rotation.x = -Math.PI / 2; // Explicitly set rotation if lookAt isn't enough
155
 
 
156
  renderer = new THREE.WebGLRenderer({ antialias: true });
157
  renderer.setSize(sceneContainer.clientWidth, sceneContainer.clientHeight);
158
- renderer.shadowMap.enabled = true;
159
- renderer.shadowMap.type = THREE.PCFSoftShadowMap;
160
  sceneContainer.appendChild(renderer.domElement);
161
 
162
- // Lighting
163
- scene.add(new THREE.AmbientLight(0xffffff, 0.7)); // Brighter ambient for debug
164
- const dirLight = new THREE.DirectionalLight(0xffffff, 1.0);
165
- dirLight.position.set(10, 30, 20); // Angled light
166
- dirLight.castShadow = true;
167
- dirLight.shadow.mapSize.width = 1024;
168
- dirLight.shadow.mapSize.height = 1024;
169
- scene.add(dirLight);
170
-
171
- // Axes Helper
172
- axesHelper = new THREE.AxesHelper(ROOM_SIZE * 0.5);
173
- axesHelper.position.set(0, 0.01, 0);
174
- scene.add(axesHelper);
175
- console.log("Three.js Initialized. Camera at:", camera.position);
176
 
177
- window.addEventListener('resize', onWindowResize, false);
178
- }
 
 
 
179
 
180
- function initPhysics() {
181
- console.log("Initializing Cannon-es...");
182
- world = new CANNON.World({ gravity: new CANNON.Vec3(0, -15, 0) });
183
- world.broadphase = new CANNON.SAPBroadphase(world);
184
- world.allowSleep = true;
185
-
186
- // Define materials
187
- groundMaterial = new CANNON.Material("ground");
188
- playerMaterial = new CANNON.Material("player");
189
- wallMaterial = new CANNON.Material("wall");
190
- monsterMaterial = new CANNON.Material("monster");
191
- itemMaterial = new CANNON.Material("item"); // Not used for physics bodies anymore
192
-
193
- // Ground physics body
194
- const groundShape = new CANNON.Plane();
195
- const groundBody = new CANNON.Body({ mass: 0, material: groundMaterial });
196
- groundBody.addShape(groundShape);
197
- groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0);
198
- world.addBody(groundBody);
199
- physicsBodies.set(groundBody.id, groundBody); // Track it
200
-
201
- // Contact Materials
202
- const playerGround = new CANNON.ContactMaterial(playerMaterial, groundMaterial, { friction: 0.1, restitution: 0.1 }); // Low friction
203
- const playerWall = new CANNON.ContactMaterial(playerMaterial, wallMaterial, { friction: 0.01, restitution: 0.1 }); // Very low friction vs walls
204
- const monsterGround = new CANNON.ContactMaterial(monsterMaterial, groundMaterial, { friction: 0.4, restitution: 0.1 });
205
- const monsterWall = new CANNON.ContactMaterial(monsterMaterial, wallMaterial, { friction: 0.1, restitution: 0.2 });
206
-
207
- world.addContactMaterial(playerGround);
208
- world.addContactMaterial(playerWall);
209
- world.addContactMaterial(monsterGround);
210
- world.addContactMaterial(monsterWall);
211
- console.log("Physics World Initialized.");
212
-
213
- // Optional: Physics Debugger Init
214
- // try { cannonDebugger = new CannonDebugger(scene, world, { color: 0x00ff00 }); console.log("Debugger Init."); }
215
- // catch (e) { console.error("Failed CannonDebugger.", e); }
216
- }
217
 
218
- // --- Primitive Assembly Functions ---
219
- function createPlayerMesh() {
220
- const group = new THREE.Group();
221
- const bodyMat = activeMaterials.player; // Use active material set
222
- const body = new THREE.Mesh(geometries.playerCylinder, bodyMat);
223
- body.position.y = PLAYER_RADIUS; body.castShadow = true;
224
- const head = new THREE.Mesh(geometries.playerSphere, bodyMat);
225
- head.position.y = PLAYER_HEIGHT - PLAYER_RADIUS; head.castShadow = true;
226
- group.add(body); group.add(head);
227
- const nose = new THREE.Mesh(geometries.playerNose, new THREE.MeshBasicMaterial({ color: 0xffff00 })); // Nose always bright yellow
228
- nose.position.set(0, PLAYER_HEIGHT * 0.6, PLAYER_RADIUS); // Point forward +Z
229
- // No rotation needed if pointing +Z
230
- group.add(nose);
231
- // Important: Set group's origin to the intended base/center of the physics body
232
- group.position.set(0, 0, 0); // Position will be controlled by sync
233
- return group;
234
- }
235
- function createSimpleMonsterMesh(modelType = 'capsule_green') {
236
- const group = new THREE.Group();
237
- const mat = activeMaterials.monster; // Use active debug/normal material
238
- if (modelType === 'capsule_green') {
239
- const body = new THREE.Mesh(geometries.monsterCapsuleBody, mat);
240
- const head = new THREE.Mesh(geometries.monsterCapsuleHead, mat);
241
- body.position.y = 0.5; head.position.y = 1.0 + 0.4;
242
- group.add(body); group.add(head);
243
- } else { /* Add other monster types if needed */ }
244
- group.traverse(child => { if (child.isMesh) child.castShadow = true; });
245
- group.position.set(0, 0, 0); // Position set by sync
246
- return group;
247
- }
248
- function createSimpleItemMesh(modelType = 'sphere_red') {
249
- let geom;
250
- const mat = activeMaterials.item; // Use active debug/normal material
251
- if(modelType === 'sphere_red') geom = geometries.itemSphere;
252
- else if (modelType === 'box_gold') geom = geometries.itemBox;
253
- else geom = geometries.itemSphere; // Default
254
- const mesh = new THREE.Mesh(geom, mat);
255
- mesh.position.y = PLAYER_RADIUS; // Default height
256
- mesh.castShadow = true;
257
- return mesh;
258
- }
259
- function createProjectileMesh() {
260
- const mat = activeMaterials.projectile; // Use active material
261
- const mesh = new THREE.Mesh(geometries.projectile, mat);
262
- return mesh;
263
- }
264
 
265
- // --- Player Setup ---
266
- function initPlayer() {
267
- console.log("Initializing Player...");
268
- // Visual Mesh
269
- playerMesh = createPlayerMesh();
270
- // Set initial position high to avoid spawning inside floor
271
- playerMesh.position.set(0, PLAYER_HEIGHT + 1, 0);
272
- scene.add(playerMesh);
273
- console.log("Player mesh added to scene at initial pos:", playerMesh.position);
274
-
275
- // Physics Body - Start at center of 0,0 cell, slightly above ground
276
- const startX = 0;
277
- const startZ = 0;
278
- const startY = PLAYER_HEIGHT * 1.5; // Start higher
279
- const playerShape = new CANNON.Sphere(PLAYER_RADIUS);
280
- playerBody = new CANNON.Body({
281
- mass: 70,
282
- shape: playerShape,
283
- position: new CANNON.Vec3(startX, startY, startZ),
284
- linearDamping: 0.95,
285
- angularDamping: 1.0, // Completely prevent angular rotation from physics
286
- material: playerMaterial // Use defined material
287
- });
288
- playerBody.allowSleep = false;
289
- playerBody.addEventListener("collide", handlePlayerCollision);
290
- world.addBody(playerBody);
291
- physicsBodies.set(playerBody.id, playerBody); // Track body using Map
292
- console.log(`Player physics body added at ${startX}, ${startY}, ${startZ}`);
293
-
294
- // Add to sync list
295
- meshesToSync.push({ mesh: playerMesh, body: playerBody });
296
- console.log("Player added to sync list.");
297
  }
298
 
299
- // --- Map Generation ---
300
- function generateMap() {
301
- console.log("Generating Map...");
302
- const wallPhysicsMaterial = world.materials.find(m => m.name === "wall");
303
- const groundPhysicsMaterial = world.materials.find(m => m.name === "ground");
304
-
305
- // DEBUG: Only generate the starting cell "0,0"
306
- const startCoord = "0,0";
307
- const data = gameData[startCoord];
308
- if (!data) {
309
- console.error("CRITICAL: No gameData found for starting cell '0,0'!");
310
- return;
311
- }
312
-
313
- const x = 0;
314
- const z = 0;
315
- const type = data.type || 'default';
316
- console.log(`Generating START cell: ${startCoord} (Type: ${type})`);
317
-
318
- // Create Floor Mesh
319
- const floorMat = activeMaterials[`floor_${type}`] || activeMaterials.floor_default; // Use debug mats
320
- const floorMesh = new THREE.Mesh(geometries.floor, floorMat);
321
- floorMesh.rotation.x = -Math.PI / 2;
322
- floorMesh.position.set(x * ROOM_SIZE, 0, z * ROOM_SIZE);
323
- floorMesh.receiveShadow = true; // Floors should receive shadows
324
- scene.add(floorMesh);
325
- console.log(`Added floor at ${x},${z}`);
326
-
327
- // Create Walls (Visual + Physics) for the single cell
328
- const features = data.features || [];
329
- const wallDefs = [
330
- ['north', geometries.wallNS, 0, -0.5], ['south', geometries.wallNS, 0, 0.5],
331
- ['east', geometries.wallEW, 0.5, 0], ['west', geometries.wallEW, -0.5, 0],
332
- ];
333
-
334
- wallDefs.forEach(([dir, geom, xOff, zOff]) => {
335
- const doorFeature = `door_${dir}`; const pathFeature = `path_${dir}`;
336
- if (!features.includes(doorFeature) && !features.includes(pathFeature)) {
337
- const wallX = x * ROOM_SIZE + xOff * ROOM_SIZE;
338
- const wallZ = z * ROOM_SIZE + zOff * ROOM_SIZE;
339
- const wallY = WALL_HEIGHT / 2;
340
-
341
- // Visual Wall (DEBUG)
342
- const wallMesh = new THREE.Mesh(geom, activeMaterials.wall); // Use debug wall mat
343
- wallMesh.position.set(wallX, wallY, wallZ);
344
- wallMesh.castShadow = true; wallMesh.receiveShadow = true;
345
- scene.add(wallMesh);
346
-
347
- // Physics Wall
348
- const wallShape = new CANNON.Box(new CANNON.Vec3(geom.parameters.width / 2, geom.parameters.height / 2, geom.parameters.depth / 2));
349
- const wallBody = new CANNON.Body({ mass: 0, shape: wallShape, position: new CANNON.Vec3(wallX, wallY, wallZ), material: wallPhysicsMaterial });
350
- world.addBody(wallBody);
351
- physicsBodies.set(wallBody.id, wallBody); // Track it
352
- // console.log(`Added ${dir} wall for cell ${x},${z}`);
353
- } else {
354
- console.log(`Skipping ${dir} wall for cell ${x},${z} due to feature.`);
355
- }
356
- });
357
-
358
- // Spawn Items & Monsters based on features for the single cell
359
- features.forEach(feature => {
360
- if (feature.startsWith('item_')) {
361
- const itemName = feature.substring(5).replace(/_/g, ' ');
362
- if (itemsData[itemName]) spawnItem(itemName, x, z);
363
- else console.warn(`Item feature found but no data for: ${itemName}`);
364
- } else if (feature.startsWith('monster_')) {
365
- const monsterType = feature.substring(8);
366
- if (monstersData[monsterType]) spawnMonster(monsterType, x, z);
367
- else console.warn(`Monster feature found but no data for: ${monsterType}`);
368
- }
369
- });
370
-
371
- console.log("Map Generation Complete (Debug Mode - Single Cell).");
372
  }
373
 
374
- // --- Item/Monster Spawning (Simplified for Pickup 'F') ---
375
- function spawnItem(itemName, gridX, gridZ) {
376
- const itemData = itemsData[itemName];
377
- if (!itemData) return;
378
- const x = gridX * ROOM_SIZE + (Math.random() - 0.5) * (ROOM_SIZE * 0.4);
379
- const z = gridZ * ROOM_SIZE + (Math.random() - 0.5) * (ROOM_SIZE * 0.4);
380
- const y = PLAYER_RADIUS; // Item height
381
-
382
- // Use DEBUG material
383
- const mesh = createSimpleItemMesh(itemData.model); // Use debug mat via create func
384
- if (!mesh) return; // Safety check
385
- mesh.position.set(x, y, z);
386
- mesh.userData = { type: 'item', name: itemName }; // Store data on mesh
387
- mesh.castShadow = true;
388
- scene.add(mesh);
389
-
390
- // Store item in game state WITHOUT physics body
391
- gameState.items.push({
392
- id: mesh.uuid, // Use mesh UUID as item ID
393
- name: itemName,
394
- mesh: mesh,
395
- position: mesh.position // Store position for proximity check
396
- });
397
- console.log(`Spawned item ${itemName} at ${x.toFixed(1)}, ${y.toFixed(1)}, ${z.toFixed(1)} (visual only)`);
398
- }
399
 
400
- function spawnMonster(monsterType, gridX, gridZ) {
401
- const monsterData = monstersData[monsterType];
402
- if (!monsterData) return;
403
- const x = gridX * ROOM_SIZE + (Math.random() - 0.5) * (ROOM_SIZE * 0.4);
404
- const z = gridZ * ROOM_SIZE + (Math.random() - 0.5) * (ROOM_SIZE * 0.4);
405
- const y = PLAYER_HEIGHT; // Start higher
406
-
407
- // Use DEBUG material
408
- const mesh = createSimpleMonsterMesh(monsterData.model); // Uses debug mat via create func
409
- if (!mesh) return; // Safety check
410
- mesh.position.set(x, y, z); // Initial visual position
411
- mesh.userData = { type: 'monster', monsterType: monsterType };
412
- scene.add(mesh);
413
-
414
- // Physics Body
415
- const shape = new CANNON.Sphere(PLAYER_RADIUS * 0.8);
416
- const body = new CANNON.Body({
417
- mass: 10, shape: shape, position: new CANNON.Vec3(x, y, z),
418
- linearDamping: 0.8, angularDamping: 0.9,
419
- material: world.materials.find(m => m.name === "monster") || new CANNON.Material("monster")
420
- });
421
- body.allowSleep = true;
422
- // Store reference to mesh and HP on body's userData
423
- body.userData = { type: 'monster', monsterType: monsterType, mesh: mesh, hp: monsterData.hp };
424
- world.addBody(body);
425
-
426
- gameState.monsters.push({ id: body.id, type: monsterType, hp: monsterData.hp, body: body, mesh: mesh });
427
- meshesToSync.push({ mesh: mesh, body: body });
428
- physicsBodies.set(body.id, body); // Use map for tracking
429
- console.log(`Spawned monster ${monsterType} at ${x.toFixed(1)}, ${y.toFixed(1)}, ${z.toFixed(1)}`);
430
- }
431
 
 
432
 
433
- // --- Input Handling (QWEASDZXC + Jump 'X' + F + Space) ---
434
- function setupInputListeners() { /* ... same ... */
435
- console.log("Setting up input listeners.");
436
- window.addEventListener('keydown', (event) => { keysPressed[event.key.toLowerCase()] = true; keysPressed[event.code] = true; if (['space', 'arrowup', 'arrowdown', 'arrowleft', 'arrowright', 'keyx', 'keyf'].includes(event.code.toLowerCase())) { event.preventDefault(); }});
437
- window.addEventListener('keyup', (event) => { keysPressed[event.key.toLowerCase()] = false; keysPressed[event.code] = false; });
438
  }
439
 
440
- function handleInput(deltaTime) {
441
- if (!playerBody) return;
442
-
443
- const moveSpeed = PLAYER_SPEED;
444
- // Correct forward/backward/strafe directions relative to world axes
445
- // Assume +Z is SOUTH, -Z is NORTH
446
- // Assume +X is EAST, -X is WEST
447
- let forceX = 0;
448
- let forceZ = 0;
449
-
450
- // Forward (-Z) / Backward (+Z)
451
- if (keysPressed['w']) forceZ -= 1; // W = North = -Z
452
- if (keysPressed['s']) forceZ += 1; // S = South = +Z
453
-
454
- // Strafe Left (-X) / Right (+X)
455
- if (keysPressed['a']) forceX -= 1; // A = West = -X
456
- if (keysPressed['d']) forceX += 1; // D = East = +X
457
-
458
- // Diagonals - combine basic directions
459
- if (keysPressed['q']) { forceZ -= 0.707; forceX -= 0.707; } // Q = NW
460
- if (keysPressed['e']) { forceZ -= 0.707; forceX += 0.707; } // E = NE
461
- if (keysPressed['z']) { forceZ += 0.707; forceX -= 0.707; } // Z = SW
462
- if (keysPressed['c']) { forceZ += 0.707; forceX += 0.707; } // C = SE
463
-
464
- // --- Calculate final velocity vector ---
465
- // We set velocity directly for more responsive control than forces
466
- const targetVelocity = new CANNON.Vec3(0, playerBody.velocity.y, 0); // Preserve Y velocity
467
-
468
- if (forceX !== 0 || forceZ !== 0) {
469
- const moveVec = new THREE.Vector2(forceX, forceZ);
470
- if (moveVec.lengthSq() > 1.0) { // Normalize only if combined magnitude > 1
471
- moveVec.normalize();
472
- }
473
- targetVelocity.x = moveVec.x * moveSpeed;
474
- targetVelocity.z = moveVec.y * moveSpeed;
475
-
476
- // --- Rotation ---
477
- // Rotate player mesh to face movement direction
478
- // Calculate angle from positive Z axis (adjust if your model faces differently)
479
- const angle = Math.atan2(targetVelocity.x, targetVelocity.z);
480
- const targetQuaternion = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), angle);
481
- // Slerp for smooth rotation
482
- playerMesh.quaternion.slerp(targetQuaternion, 0.15); // Adjust 0.15 for responsiveness
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
483
 
484
- } else {
485
- // No movement keys pressed - rely on linear damping to stop
486
- // Or force stop X/Z velocity:
487
- targetVelocity.x = 0;
488
- targetVelocity.z = 0;
489
- }
 
 
 
 
 
 
490
 
491
- playerBody.velocity.x = targetVelocity.x;
492
- playerBody.velocity.z = targetVelocity.z;
493
- // Y velocity is controlled by gravity + jump impulse
494
-
495
- // --- Jump (X) ---
496
- if (keysPressed['x'] || keysPressed['keyx']) { // Check code too
497
- // !! Basic jump - Needs ground check via raycast or contact materials !!
498
- // Add a simple cooldown or only allow if Y velocity is low
499
- if (Math.abs(playerBody.velocity.y) < 0.5) { // Crude check if mostly grounded
500
- console.log("JUMP!");
501
- addLog("Jump!", "info");
502
- // Apply impulse upwards
503
- playerBody.applyImpulse(new CANNON.Vec3(0, PLAYER_JUMP_IMPULSE, 0), playerBody.position);
504
- }
505
- keysPressed['x'] = false; keysPressed['keyx'] = false; // Consume jump input
506
  }
 
507
 
508
- // --- Pickup (F) ---
509
- if (keysPressed['f'] || keysPressed['keyf']) {
510
- pickupNearbyItem();
511
- keysPressed['f'] = false; keysPressed['keyf'] = false; // Consume pickup input
512
- }
513
 
514
- // --- Fire (Space) ---
515
- if (keysPressed['space']) {
516
- fireProjectile();
517
- keysPressed['space'] = false; // Consume fire input
518
- }
 
 
519
  }
520
 
521
- // --- Interaction Logic ---
522
- function pickupNearbyItem() {
523
- if (!playerBody) return;
524
- const playerPos = playerBody.position;
525
- let pickedUp = false;
526
- let closestItemIndex = -1;
527
- let minDistanceSq = PICKUP_RADIUS_SQ; // Use squared distance
528
-
529
- // Find the closest item within radius
530
- for (let i = 0; i < gameState.items.length; i++) {
531
- const item = gameState.items[i];
532
- const distanceSq = playerPos.distanceSquared(item.position);
533
- if (distanceSq < minDistanceSq) {
534
- minDistanceSq = distanceSq;
535
- closestItemIndex = i;
536
- }
537
- }
538
-
539
- // Pick up the closest item if found
540
- if (closestItemIndex > -1) {
541
- const item = gameState.items[closestItemIndex];
542
- if (!gameState.inventory.includes(item.name)) {
543
- gameState.inventory.push(item.name);
544
- addLog(`Picked up ${item.name}!`, "pickup");
545
- updateInventoryDisplay();
546
-
547
- // Remove item visually and from state
548
- if(item.mesh.parent) scene.remove(item.mesh);
549
- gameState.items.splice(closestItemIndex, 1);
550
- pickedUp = true;
551
- } else {
552
- addLog(`Already have ${item.name}.`, "info");
553
- }
554
  }
555
 
556
- if (!pickedUp) {
557
- addLog("Nothing nearby to pick up.", "info");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
558
  }
559
- }
560
 
561
 
562
- // --- Combat (Projectile logic remains similar) ---
563
- function fireProjectile() {
564
- if (!playerBody || !playerMesh) return;
565
- addLog("Pew!", "combat");
566
- const projectileMesh = createProjectileMesh();
567
- const projectileShape = new CANNON.Sphere(PROJECTILE_RADIUS);
568
- const projectileBody = new CANNON.Body({ mass: 0.1, shape: projectileShape, linearDamping: 0.01, angularDamping: 0.01 });
569
- projectileBody.addEventListener("collide", handleProjectileCollision);
570
-
571
- // Calculate start position and velocity based on player's *current* rotation
572
- const offsetDistance = PLAYER_RADIUS + PROJECTILE_RADIUS + 0.1;
573
- const direction = new THREE.Vector3(0, 0, 1); // Base direction +Z
574
- direction.applyQuaternion(playerMesh.quaternion); // Rotate based on player mesh
575
-
576
- const startPos = new CANNON.Vec3().copy(playerBody.position).vadd(
577
- new CANNON.Vec3(direction.x, 0, direction.z).scale(offsetDistance) // Offset horizontally
578
- );
579
- // Adjust start Y based on player body center + visual model height
580
- startPos.y = playerBody.position.y; // Fire from player center height
581
-
582
- projectileBody.position.copy(startPos);
583
- projectileMesh.position.copy(startPos);
584
-
585
- // Velocity in player facing direction
586
- projectileBody.velocity = new CANNON.Vec3(direction.x, 0, direction.z).scale(PROJECTILE_SPEED);
587
-
588
- scene.add(projectileMesh);
589
- world.addBody(projectileBody);
590
- const projectileData = { mesh: projectileMesh, body: projectileBody, lifetime: 2.0 }; // Shorter lifetime
591
- meshesToSync.push(projectileData);
592
- projectiles.push(projectileData);
593
- physicsBodies.set(projectileBody.id, projectileBody); // Track
594
- projectileBody.userData = { type: 'projectile', data: projectileData };
595
- projectileMesh.userData = { type: 'projectile', data: projectileData }; // No body ref needed on mesh
596
  }
597
 
598
- // --- Collision Handling ---
599
- function handlePlayerCollision(event) {
600
- const otherBody = event.body;
601
- if (!otherBody || !otherBody.userData || !playerBody) return;
602
-
603
- // Player <-> Monster (Example: Simple damage, could add knockback)
604
- if (otherBody.userData.type === 'monster') {
605
- // Check for cooldown before applying damage again?
606
- console.log("Player collided with monster", otherBody.id);
607
- // gameState.stats.hp -= 1;
608
- // addLog(`Hit by ${otherBody.userData.monsterType || 'monster'}! HP: ${gameState.stats.hp}`, "combat");
609
- // updateStatsDisplay();
610
- // if (gameState.stats.hp <= 0) { gameOver("Defeated by a monster!"); }
611
- // Apply small impulse away from monster
612
- const impulse = playerBody.position.vsub(otherBody.position).unit().scale(20); // Knockback force
613
- playerBody.applyImpulse(impulse, playerBody.position);
614
- }
615
- // Player <-> Wall (Handled by physics engine)
616
- // Player <-> Item (Handled by 'F' key)
617
- }
618
 
619
- function handleProjectileCollision(event) {
620
- const projectileBody = event.target;
621
- const otherBody = event.body;
622
- if (!projectileBody?.userData || !otherBody?.userData) return; // Null checks
623
-
624
- const projectileData = projectileBody.userData.data;
625
- let shouldRemoveProjectile = true; // Assume removal unless hitting player
626
-
627
- if (otherBody.userData.type === 'monster') {
628
- const monsterId = otherBody.id;
629
- const monsterIndex = gameState.monsters.findIndex(m => m.id === monsterId);
630
- if (monsterIndex > -1) {
631
- const monster = gameState.monsters[monsterIndex];
632
- const damage = gameState.stats.strength + Math.floor(Math.random() * 3); // Add randomness
633
- monster.hp -= damage;
634
- otherBody.userData.hp = monster.hp;
635
- addLog(`Hit ${otherBody.userData.monsterType} for ${damage} damage! (HP: ${monster.hp})`, "combat");
636
-
637
- // Apply impulse to monster
638
- const impulseDir = projectileBody.velocity.unit();
639
- otherBody.applyImpulse(impulseDir.scale(damage * 5), projectileBody.position); // Knockback scales with damage
640
-
641
-
642
- if (monster.hp <= 0) {
643
- addLog(`Defeated ${otherBody.userData.monsterType}!`, "info");
644
- // Safely remove monster after physics step using setTimeout
645
- setTimeout(() => {
646
- if(monster.mesh.parent) scene.remove(monster.mesh);
647
- if(world.bodies.includes(monster.body)) world.removeBody(monster.body);
648
- meshesToSync = meshesToSync.filter(sync => sync.body.id !== monster.body.id);
649
- physicsBodies.delete(monster.body.id);
650
- gameState.monsters = gameState.monsters.filter(m => m.id !== monsterId);
651
- }, 0);
652
- }
653
- }
654
- } else if (otherBody === playerBody) {
655
- shouldRemoveProjectile = false; // Don't destroy projectile if it hits the player who fired it
656
- console.log("Projectile hit player - ignored");
657
- } else if (otherBody.mass === 0) {
658
- // Hit a static object like a wall
659
- console.log("Projectile hit wall/static");
660
- // Optional: Add impact effect
661
  }
662
 
663
-
664
- if (shouldRemoveProjectile) {
665
- // Schedule removal might be safer than immediate
666
- setTimeout(() => removeProjectile(projectileData), 0);
 
667
  }
668
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
669
 
670
- function removeProjectile(projectileData) {
671
- if (!projectileData) return;
672
- const index = projectiles.indexOf(projectileData);
673
- if (index === -1) return;
 
 
674
 
675
- if (projectileData.mesh?.parent) scene.remove(projectileData.mesh);
676
- if (projectileData.body && world.bodies.includes(projectileData.body)) world.removeBody(projectileData.body);
677
 
678
- meshesToSync = meshesToSync.filter(sync => sync.body?.id !== projectileData.body?.id);
679
- if (projectileData.body) physicsBodies.delete(projectileData.body.id);
680
- projectiles.splice(index, 1);
681
  }
682
 
683
 
684
- // --- Monster AI ---
685
- function updateMonsters(deltaTime) {
686
- const agroRangeSq = (ROOM_SIZE * 2) ** 2; // Increased range
687
- if(!playerBody) return;
688
-
689
- gameState.monsters.forEach(monster => {
690
- if (!monster || !monster.body || monster.hp <= 0) return; // Skip dead or removed monsters
691
-
692
- const monsterPos = monster.body.position;
693
- const playerPos = playerBody.position;
694
- const distanceSq = playerPos.distanceSquared(monsterPos);
695
-
696
- if (distanceSq < agroRangeSq) { // If player is close
697
- const direction = playerPos.vsub(monsterPos);
698
- direction.y = 0; // Ignore height difference for movement plan
699
- if (distanceSq > (PLAYER_RADIUS * 2)**2 && direction.lengthSquared() > 0.1) { // If not too close and direction is valid
700
- direction.normalize();
701
- const monsterData = monstersData[monster.type];
702
- const speed = monsterData?.speed || 1;
703
-
704
- // Apply velocity for chasing
705
- monster.body.velocity.x = direction.x * speed;
706
- monster.body.velocity.z = direction.z * speed;
707
-
708
- // Rotation
709
- const angle = Math.atan2(direction.x, direction.z);
710
- const targetQuaternion = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), angle);
711
- monster.mesh.quaternion.slerp(targetQuaternion, 0.1);
712
- } else { // Too close or direction invalid, stop horizontal movement
713
- monster.body.velocity.x = 0;
714
- monster.body.velocity.z = 0;
715
- // TODO: Add attack logic here if close enough
716
- }
717
- } else { // Player too far, stop moving
718
- monster.body.velocity.x = 0;
719
- monster.body.velocity.z = 0;
720
- }
721
- // Wake up body if needed (should be awake if chasing)
722
- if(monster.body.sleepState === CANNON.Body.SLEEPING) monster.body.wakeUp();
723
- });
724
- }
725
-
726
- // --- UI Update Functions ---
727
- function updateUI() { updateStatsDisplay(); updateInventoryDisplay(); }
728
- function updateStatsDisplay() { /* ... same ... */
729
- let statsHTML = ''; statsHTML += `<span>HP: ${gameState.stats.hp}/${gameState.stats.maxHp}</span>`; statsHTML += `<span>Str: ${gameState.stats.strength}</span>`; statsHTML += `<span>Wis: ${gameState.stats.wisdom}</span>`; statsHTML += `<span>Cor: ${gameState.stats.courage}</span>`; statsElement.innerHTML = statsHTML;
730
- }
731
- function updateInventoryDisplay() { /* ... same ... */
732
- let inventoryHTML = ''; 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;
733
- }
734
- function addLog(message, type = "info") { /* ... same ... */
735
- const p = document.createElement('p'); p.classList.add(type); p.textContent = `[${new Date().toLocaleTimeString([], { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' })}] ${message}`; logElement.appendChild(p); logElement.scrollTop = logElement.scrollHeight;
736
  }
737
 
738
- // --- Game Over ---
739
- function gameOver(reason) { /* ... same ... */
740
- addLog(`GAME OVER: ${reason}`, "error"); console.log("Game Over:", reason);
741
- gameLoopActive = false; // Stop the game loop
742
- const restartButton = document.createElement('button'); restartButton.textContent = "RESTART GAME"; restartButton.style.cssText = `position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); padding: 20px 40px; font-size: 2em; cursor: pointer; z-index: 1000; background-color: #ffc107; border: none; border-radius: 5px; color: #333; font-family: 'Courier New', monospace;`;
743
- restartButton.onclick = () => { if (restartButton.parentNode) restartButton.parentNode.removeChild(restartButton); init(); }; // Re-initialize
744
- sceneContainer.appendChild(restartButton);
745
- }
746
-
747
- // --- Main Game Loop ---
748
- let lastTimestamp = 0;
749
- function animate(timestamp) {
750
- if (!gameLoopActive) return;
751
- animationFrameId = requestAnimationFrame(animate);
752
-
753
- const deltaTime = (timestamp - lastTimestamp) * 0.001;
754
- lastTimestamp = timestamp;
755
- const dtClamped = Math.min(deltaTime, 1 / 20); // Clamp delta time (max 20 FPS step)
756
-
757
- if (!world || !playerBody || !scene || !camera || !renderer) {
758
- console.error("Core component missing, stopping loop.");
759
- gameLoopActive = false;
760
- return;
761
  }
 
 
762
 
763
- // 1. Input
764
- handleInput(dtClamped);
765
-
766
- // 2. AI
767
- updateMonsters(dtClamped);
768
-
769
- // 3. Physics Step
770
- try { world.step(dtClamped); }
771
- catch (e) { console.error("Physics step error:", e); gameLoopActive = false; return; } // Stop loop on error
772
-
773
- // 4. Projectiles Update
774
- for (let i = projectiles.length - 1; i >= 0; i--) {
775
- const p = projectiles[i];
776
- if (p) { p.lifetime -= dtClamped; if (p.lifetime <= 0) removeProjectile(p); }
777
- }
778
 
779
- // 5. Sync Visuals
780
- meshesToSync.forEach(item => {
781
- if (item?.body && item?.mesh && item.mesh.parent) { // Check existence
782
- item.mesh.position.copy(item.body.position);
783
- item.mesh.quaternion.copy(item.body.quaternion);
784
- }
785
- });
786
-
787
- // 6. Update Camera
788
- if (playerBody && camera) {
789
- const targetCameraPos = new THREE.Vector3(
790
- playerBody.position.x,
791
- CAMERA_Y_OFFSET,
792
- playerBody.position.z // Look straight down from above player
793
- );
794
- camera.position.lerp(targetCameraPos, 0.1); // Smooth follow
795
- // Camera already looking down due to initial setup / rotation
796
- // camera.lookAt(playerBody.position.x, 0, playerBody.position.z); // Keep looking at player's feet
 
 
797
  }
 
798
 
799
- // 7. Physics Debugger (Optional)
800
- // if (cannonDebugger) cannonDebugger.update();
801
-
802
- // 8. Render
803
- renderer.render(scene, camera);
804
  }
805
 
806
- // --- Window Resize ---
807
- function onWindowResize() {
808
- if (!renderer || !camera) return;
809
- const width = sceneContainer.clientWidth;
810
- const height = sceneContainer.clientHeight;
811
- camera.aspect = width / height;
812
- camera.updateProjectionMatrix();
813
- renderer.setSize(width, height);
814
- console.log("Resized");
815
- }
816
 
817
- // --- Start Game ---
818
- init();
 
 
 
 
 
 
1
  import * as THREE from 'three';
2
+ // Optional: Add OrbitControls for debugging/viewing scene
3
+ // import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
4
 
5
  // --- DOM Elements ---
6
  const sceneContainer = document.getElementById('scene-container');
7
+ const storyTitleElement = document.getElementById('story-title');
8
+ const storyContentElement = document.getElementById('story-content');
9
+ const choicesElement = document.getElementById('choices');
10
  const statsElement = document.getElementById('stats-display');
11
  const inventoryElement = document.getElementById('inventory-display');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
  // --- Three.js Setup ---
14
+ let scene, camera, renderer, cube; // Basic scene object
15
+ // let controls; // Optional OrbitControls
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  function initThreeJS() {
18
+ // Scene
19
+ scene = new THREE.Scene();
20
+ scene.background = new THREE.Color(0x222222); // Match body background
21
+
22
+ // Camera
23
+ camera = new THREE.PerspectiveCamera(75, sceneContainer.clientWidth / sceneContainer.clientHeight, 0.1, 1000);
24
+ camera.position.z = 5;
25
 
26
+ // Renderer
27
  renderer = new THREE.WebGLRenderer({ antialias: true });
28
  renderer.setSize(sceneContainer.clientWidth, sceneContainer.clientHeight);
 
 
29
  sceneContainer.appendChild(renderer.domElement);
30
 
31
+ // Basic Lighting
32
+ const ambientLight = new THREE.AmbientLight(0xffffff, 0.6); // Soft white light
33
+ scene.add(ambientLight);
34
+ const directionalLight = new THREE.DirectionalLight(0xffffff, 1.0);
35
+ directionalLight.position.set(5, 10, 7.5);
36
+ scene.add(directionalLight);
 
 
 
 
 
 
 
 
37
 
38
+ // Basic Object (Placeholder for scene illustration)
39
+ const geometry = new THREE.BoxGeometry(1, 1, 1);
40
+ const material = new THREE.MeshStandardMaterial({ color: 0xcccccc }); // Default color
41
+ cube = new THREE.Mesh(geometry, material);
42
+ scene.add(cube);
43
 
44
+ // Optional Controls
45
+ // controls = new OrbitControls(camera, renderer.domElement);
46
+ // controls.enableDamping = true;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
+ // Handle Resize
49
+ window.addEventListener('resize', onWindowResize, false);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
+ // Start Animation Loop
52
+ animate();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  }
54
 
55
+ function onWindowResize() {
56
+ if (!renderer || !camera) return;
57
+ camera.aspect = sceneContainer.clientWidth / sceneContainer.clientHeight;
58
+ camera.updateProjectionMatrix();
59
+ renderer.setSize(sceneContainer.clientWidth, sceneContainer.clientHeight);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  }
61
 
62
+ function animate() {
63
+ requestAnimationFrame(animate);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
+ // Simple animation
66
+ if (cube) {
67
+ cube.rotation.x += 0.005;
68
+ cube.rotation.y += 0.005;
69
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
+ // if (controls) controls.update(); // If using OrbitControls
72
 
73
+ if (renderer && scene && camera) {
74
+ renderer.render(scene, camera);
75
+ }
 
 
76
  }
77
 
78
+ // --- Game Data (Ported from Python, simplified for now) ---
79
+ const gameData = {
80
+ "1": {
81
+ title: "The Beginning",
82
+ content: `<p>The Evil Power Master has been terrorizing the land... You stand at the entrance to Silverhold, ready to begin your quest.</p><p>How will you prepare?</p>`,
83
+ options: [
84
+ { text: "Visit the local weaponsmith", next: 2, /* addItem: "..." */ },
85
+ { text: "Seek wisdom at the temple", next: 3, /* addItem: "..." */ },
86
+ { text: "Meet the resistance leader", next: 4, /* addItem: "..." */ }
87
+ ],
88
+ illustration: "city-gates" // Key for Three.js scene
89
+ },
90
+ "2": {
91
+ title: "The Weaponsmith",
92
+ content: `<p>Gorn the weaponsmith welcomes you. "You'll need more than common steel," he says, offering weapons.</p>`,
93
+ options: [
94
+ { text: "Take the Flaming Sword", next: 5, addItem: "Flaming Sword" },
95
+ { text: "Choose the Whispering Bow", next: 5, addItem: "Whispering Bow" },
96
+ { text: "Select the Guardian Shield", next: 5, addItem: "Guardian Shield" }
97
+ ],
98
+ illustration: "weaponsmith"
99
+ },
100
+ "3": {
101
+ title: "The Ancient Temple",
102
+ content: `<p>High Priestess Alara greets you. "Prepare your mind and spirit." She offers to teach you a secret art.</p>`,
103
+ options: [
104
+ { text: "Learn Healing Light", next: 5, addItem: "Healing Light Spell" },
105
+ { text: "Master Shield of Faith", next: 5, addItem: "Shield of Faith Spell" },
106
+ { text: "Study Binding Runes", next: 5, addItem: "Binding Runes Scroll" }
107
+ ],
108
+ illustration: "temple"
109
+ },
110
+ "4": {
111
+ title: "The Resistance Leader",
112
+ content: `<p>Lyra, the resistance leader, shows you a map. "His fortress has three possible entry points." She offers an item.</p>`,
113
+ options: [
114
+ { text: "Take the Secret Tunnel Map", next: 5, addItem: "Secret Tunnel Map" },
115
+ { text: "Accept Poison Daggers", next: 5, addItem: "Poison Daggers" },
116
+ { text: "Choose the Master Key", next: 5, addItem: "Master Key" }
117
+ ],
118
+ illustration: "resistance-meeting"
119
+ },
120
+ "5": {
121
+ title: "The Journey Begins",
122
+ content: `<p>You leave Silverhold and enter the corrupted Shadowwood Forest. Strange sounds echo. Which path will you take?</p>`,
123
+ options: [
124
+ { text: "Take the main road", next: 6 }, // Leads to page 6 (Ambush)
125
+ { text: "Follow the river path", next: 7 }, // Leads to page 7 (River Spirit)
126
+ { text: "Brave the ruins shortcut", next: 8 } // Leads to page 8 (Ruins)
127
+ ],
128
+ illustration: "shadowwood-forest" // Key for Three.js scene
129
+ // Add more pages here...
130
+ },
131
+ // Add placeholder pages 6, 7, 8 etc. to continue the story
132
+ "6": {
133
+ title: "Ambush!",
134
+ content: "<p>Scouts jump out! 'Surrender!'</p>",
135
+ options: [{ text: "Fight!", next: 9 }, { text: "Try to flee!", next: 10 }], // Example links
136
+ illustration: "road-ambush"
137
+ },
138
+ // ... Add many more pages based on your Python data ...
139
+ "9": { // Example continuation
140
+ title: "Victory!",
141
+ content: "<p>You defeat the scouts and continue.</p>",
142
+ options: [{ text: "Proceed to the fortress plains", next: 15 }],
143
+ illustration: "forest-edge"
144
+ },
145
+ "10": { // Example continuation
146
+ title: "Captured!",
147
+ content: "<p>You failed to escape and are captured!</p>",
148
+ options: [{ text: "Accept fate (for now)", next: 20 }], // Go to prison wagon page
149
+ illustration: "prisoner-cell"
150
+ },
151
+ // Game Over placeholder
152
+ "99": {
153
+ title: "Game Over",
154
+ content: "<p>Your adventure ends here.</p>",
155
+ options: [{ text: "Restart", next: 1 }], // Link back to start
156
+ illustration: "game-over",
157
+ gameOver: true
158
+ }
159
+ };
160
 
161
+ const itemsData = { // Simplified item data
162
+ "Flaming Sword": { type: "weapon", description: "A fiery blade" },
163
+ "Whispering Bow": { type: "weapon", description: "A silent bow" },
164
+ "Guardian Shield": { type: "armor", description: "A protective shield" },
165
+ "Healing Light Spell": { type: "spell", description: "Mends minor wounds" },
166
+ "Shield of Faith Spell": { type: "spell", description: "Temporary shield" },
167
+ "Binding Runes Scroll": { type: "spell", description: "Binds an enemy" },
168
+ "Secret Tunnel Map": { type: "quest", description: "Shows a hidden path" },
169
+ "Poison Daggers": { type: "weapon", description: "Daggers with poison" },
170
+ "Master Key": { type: "quest", description: "Unlocks many doors" },
171
+ // Add other items...
172
+ };
173
 
174
+ // --- Game State ---
175
+ let gameState = {
176
+ currentPageId: 1,
177
+ inventory: [],
178
+ stats: {
179
+ courage: 7,
180
+ wisdom: 5,
181
+ strength: 6,
182
+ hp: 30,
183
+ maxHp: 30
 
 
 
 
 
184
  }
185
+ };
186
 
187
+ // --- Game Logic Functions ---
 
 
 
 
188
 
189
+ function startGame() {
190
+ gameState = { // Reset state
191
+ currentPageId: 1,
192
+ inventory: [],
193
+ stats: { courage: 7, wisdom: 5, strength: 6, hp: 30, maxHp: 30 }
194
+ };
195
+ renderPage(gameState.currentPageId);
196
  }
197
 
198
+ function renderPage(pageId) {
199
+ const page = gameData[pageId];
200
+ if (!page) {
201
+ console.error(`Error: Page data not found for ID: ${pageId}`);
202
+ storyTitleElement.textContent = "Error";
203
+ storyContentElement.innerHTML = "<p>Could not load page data. Adventure halted.</p>";
204
+ choicesElement.innerHTML = '<button class="choice-button" onclick="handleChoice(1)">Restart</button>'; // Provide restart option
205
+ updateScene('error'); // Show error scene
206
+ return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  }
208
 
209
+ // Update UI
210
+ storyTitleElement.textContent = page.title || "Untitled Page";
211
+ storyContentElement.innerHTML = page.content || "<p>...</p>";
212
+ updateStatsDisplay();
213
+ updateInventoryDisplay();
214
+
215
+ // Update Choices
216
+ choicesElement.innerHTML = ''; // Clear old choices
217
+ if (page.options && page.options.length > 0) {
218
+ page.options.forEach(option => {
219
+ const button = document.createElement('button');
220
+ button.classList.add('choice-button');
221
+ button.textContent = option.text;
222
+
223
+ // Check requirements (basic check for now)
224
+ let requirementMet = true;
225
+ if (option.requireItem && !gameState.inventory.includes(option.requireItem)) {
226
+ requirementMet = false;
227
+ button.title = `Requires: ${option.requireItem}`; // Tooltip
228
+ button.disabled = true;
229
+ }
230
+ // Add requireAnyItem check here later if needed
231
+
232
+ if (requirementMet) {
233
+ // Store data needed for handling the choice
234
+ button.dataset.nextPage = option.next;
235
+ if (option.addItem) {
236
+ button.dataset.addItem = option.addItem;
237
+ }
238
+ // Add other potential effects as data attributes if needed
239
+
240
+ button.onclick = () => handleChoiceClick(button.dataset);
241
+ }
242
+
243
+ choicesElement.appendChild(button);
244
+ });
245
+ } else if (page.gameOver) {
246
+ const button = document.createElement('button');
247
+ button.classList.add('choice-button');
248
+ button.textContent = "Restart Adventure";
249
+ button.dataset.nextPage = 1; // Restart goes to page 1
250
+ button.onclick = () => handleChoiceClick(button.dataset);
251
+ choicesElement.appendChild(button);
252
+ } else {
253
+ choicesElement.innerHTML = '<p><i>No further options available from here.</i></p>';
254
+ const button = document.createElement('button');
255
+ button.classList.add('choice-button');
256
+ button.textContent = "Restart Adventure";
257
+ button.dataset.nextPage = 1; // Restart goes to page 1
258
+ button.onclick = () => handleChoiceClick(button.dataset);
259
+ choicesElement.appendChild(button);
260
  }
 
261
 
262
 
263
+ // Update 3D Scene
264
+ updateScene(page.illustration || 'default');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  }
266
 
267
+ function handleChoiceClick(dataset) {
268
+ const nextPageId = parseInt(dataset.nextPage); // Ensure it's a number
269
+ const itemToAdd = dataset.addItem;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
 
271
+ if (isNaN(nextPageId)) {
272
+ console.error("Invalid nextPageId:", dataset.nextPage);
273
+ return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
274
  }
275
 
276
+ // --- Process Effects of Making the Choice ---
277
+ // Add item if specified and not already present
278
+ if (itemToAdd && !gameState.inventory.includes(itemToAdd)) {
279
+ gameState.inventory.push(itemToAdd);
280
+ console.log("Added item:", itemToAdd);
281
  }
282
+ // Add stat changes/hp loss *linked to the choice itself* here if needed
283
+
284
+ // --- Move to Next Page and Process Landing Effects ---
285
+ gameState.currentPageId = nextPageId;
286
+
287
+ const nextPageData = gameData[nextPageId];
288
+ if (nextPageData) {
289
+ // Apply HP loss defined on the *landing* page
290
+ if (nextPageData.hpLoss) {
291
+ gameState.stats.hp -= nextPageData.hpLoss;
292
+ console.log(`Lost ${nextPageData.hpLoss} HP.`);
293
+ if (gameState.stats.hp <= 0) {
294
+ console.log("Player died from HP loss!");
295
+ gameState.stats.hp = 0;
296
+ renderPage(99); // Go to a specific game over page ID
297
+ return; // Stop further processing
298
+ }
299
+ }
300
+ // Apply stat increase defined on the *landing* page
301
+ if (nextPageData.statIncrease) {
302
+ const stat = nextPageData.statIncrease.stat;
303
+ const amount = nextPageData.statIncrease.amount;
304
+ if (gameState.stats.hasOwnProperty(stat)) {
305
+ gameState.stats[stat] += amount;
306
+ console.log(`Stat ${stat} increased by ${amount}.`);
307
+ }
308
+ }
309
+ // Check if landing page is game over
310
+ if (nextPageData.gameOver) {
311
+ console.log("Reached Game Over page.");
312
+ renderPage(nextPageId);
313
+ return;
314
+ }
315
 
316
+ } else {
317
+ console.error(`Data for page ${nextPageId} not found!`);
318
+ // Optionally go to an error page or restart
319
+ renderPage(99); // Go to game over page as fallback
320
+ return;
321
+ }
322
 
 
 
323
 
324
+ // Render the new page
325
+ renderPage(nextPageId);
 
326
  }
327
 
328
 
329
+ function updateStatsDisplay() {
330
+ let statsHTML = '<strong>Stats:</strong> ';
331
+ statsHTML += `<span>HP: ${gameState.stats.hp}/${gameState.stats.maxHp}</span>`;
332
+ statsHTML += `<span>Str: ${gameState.stats.strength}</span>`;
333
+ statsHTML += `<span>Wis: ${gameState.stats.wisdom}</span>`;
334
+ statsHTML += `<span>Cor: ${gameState.stats.courage}</span>`;
335
+ statsElement.innerHTML = statsHTML;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
336
  }
337
 
338
+ function updateInventoryDisplay() {
339
+ let inventoryHTML = '<strong>Inventory:</strong> ';
340
+ if (gameState.inventory.length === 0) {
341
+ inventoryHTML += '<em>Empty</em>';
342
+ } else {
343
+ gameState.inventory.forEach(item => {
344
+ const itemInfo = itemsData[item] || { type: 'unknown', description: '???' };
345
+ // Add class based on item type for styling
346
+ const itemClass = `item-${itemInfo.type || 'unknown'}`;
347
+ inventoryHTML += `<span class="${itemClass}" title="${itemInfo.description}">${item}</span>`;
348
+ });
 
 
 
 
 
 
 
 
 
 
 
 
349
  }
350
+ inventoryElement.innerHTML = inventoryHTML;
351
+ }
352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
353
 
354
+ function updateScene(illustrationKey) {
355
+ console.log("Updating scene for:", illustrationKey);
356
+ if (!cube) return; // Don't do anything if cube isn't initialized
357
+
358
+ // Simple scene update: Change cube color based on key
359
+ let color = 0xcccccc; // Default grey
360
+ switch (illustrationKey) {
361
+ case 'city-gates': color = 0xaaaaaa; break;
362
+ case 'weaponsmith': color = 0x8B4513; break; // Brown
363
+ case 'temple': color = 0xFFFFE0; break; // Light yellow
364
+ case 'resistance-meeting': color = 0x696969; break; // Dim grey
365
+ case 'shadowwood-forest': color = 0x228B22; break; // Forest green
366
+ case 'road-ambush': color = 0xD2691E; break; // Chocolate (dirt road)
367
+ case 'river-spirit': color = 0xADD8E6; break; // Light blue
368
+ case 'ancient-ruins': color = 0x778899; break; // Light slate grey
369
+ case 'forest-edge': color = 0x90EE90; break; // Light green
370
+ case 'prisoner-cell': color = 0x444444; break; // Dark grey
371
+ case 'game-over': color = 0xff0000; break; // Red
372
+ case 'error': color = 0xffa500; break; // Orange
373
+ default: color = 0xcccccc; break; // Default grey for unknown
374
  }
375
+ cube.material.color.setHex(color);
376
 
377
+ // In a more complex setup, you would:
378
+ // 1. Remove old objects from the scene (scene.remove(object))
379
+ // 2. Load/create new objects based on illustrationKey
380
+ // 3. Add new objects to the scene (scene.add(newObject))
 
381
  }
382
 
 
 
 
 
 
 
 
 
 
 
383
 
384
+ // --- Initialization ---
385
+ initThreeJS();
386
+ startGame(); // Start the game after setting up Three.js
387
+
388
+ // Make handleChoiceClick globally accessible IF using inline onclick
389
+ // If using addEventListener, this is not needed.
390
+ // window.handleChoiceClick = handleChoiceClick;