-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.html
More file actions
1109 lines (969 loc) · 51.3 KB
/
game.html
File metadata and controls
1109 lines (969 loc) · 51.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3D几何形状探索 - 学习游戏</title>
<link href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-100-M/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
<link href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/tailwindcss/2.2.19/tailwind.min.css" rel="stylesheet">
<style>
@import url('https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;700&family=Noto+Sans+SC:wght@400;700&display=swap');
body {
margin: 0;
overflow: hidden;
font-family: 'Noto Sans SC', sans-serif;
background-color: #f0f0f0;
-webkit-user-select: none; /* Safari */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+ */
user-select: none; /* Standard */
}
#game-container {
position: relative;
width: 100vw;
height: 100vh;
background-color: #e0e0e0; /* Fallback background */
}
canvas {
display: block;
width: 100% !important;
height: 100% !important;
position: absolute;
top: 0;
left: 0;
/* Ensure canvas interaction is enabled by default */
pointer-events: auto;
}
#overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none; /* Allows clicks to pass through to canvas by default */
z-index: 10;
font-family: 'Noto Sans SC', sans-serif;
}
.ui-panel {
pointer-events: auto; /* Re-enable pointer events for UI elements */
background: rgba(255, 255, 255, 0.9);
backdrop-filter: blur(5px);
border-radius: 8px;
padding: 1rem;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
color: #333;
}
#task-display {
position: absolute;
top: 20px;
left: 20px;
}
#score-display {
position: absolute;
top: 20px;
right: 20px;
}
#progress-bar-container {
position: absolute;
top: 20px;
left: 50%;
transform: translateX(-50%);
width: 200px;
height: 15px;
background-color: rgba(255, 255, 255, 0.9);
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
pointer-events: auto;
}
#progress-bar {
height: 100%;
width: 0%;
background-color: #4CAF50;
border-radius: 8px;
transition: width 0.5s ease-in-out;
}
#info-modal {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 90%;
max-width: 500px;
display: none;
pointer-events: auto;
font-family: 'Noto Serif SC', serif;
}
#info-modal h3 {
font-family: 'Noto Serif SC', serif;
margin-top: 0;
margin-bottom: 0.5rem;
font-weight: 700;
font-size: 1.5rem;
}
#info-modal p {
font-family: 'Noto Serif SC', serif;
line-height: 1.6;
}
.close-button {
position: absolute;
top: 10px;
right: 10px;
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: #666;
transition: color 0.2s;
}
.close-button:hover {
color: #333;
}
#pause-button {
position: absolute;
bottom: 20px;
left: 20px;
pointer-events: auto;
font-size: 2rem;
color: #666;
cursor: pointer;
transition: color 0.2s;
}
#pause-button:hover {
color: #333;
}
#pause-menu {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 90%;
max-width: 400px;
display: none;
text-align: center;
pointer-events: auto;
}
.game-button {
display: block;
width: 80%;
margin: 1rem auto;
padding: 0.8rem;
font-size: 1.2rem;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
transition: background-color 0.2s;
}
.game-button:hover {
background-color: #45a049;
}
.game-button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
#completion-modal {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 90%;
max-width: 500px;
display: none;
text-align: center;
pointer-events: auto;
font-family: 'Noto Serif SC', serif;
}
#completion-modal h3 {
font-family: 'Noto Serif SC', serif;
margin-top: 0;
margin-bottom: 1rem;
font-weight: 700;
font-size: 2rem;
}
/* Add a subtle highlight effect for interactive objects */
.interactive-object {
cursor: pointer; /* Indicate interactivity */
}
</style>
</head>
<body>
<div id="game-container">
</div>
<div id="overlay">
<div id="task-display" class="ui-panel">
<p>任务:<span id="current-task">加载中...</span></p>
</div>
<div id="score-display" class="ui-panel">
<p>分数:<span id="current-score">0</span></p>
</div>
<div id="progress-bar-container">
<div id="progress-bar"></div>
</div>
<div id="info-modal" class="ui-panel">
<button class="close-button" id="close-info-modal"><i class="fas fa-times"></i></button>
<h3 id="info-modal-title">知识点</h3>
<p id="info-modal-content">...</p>
<button class="game-button mt-4" id="continue-button">继续</button>
</div>
<div id="pause-button"><i class="fas fa-pause-circle"></i></div>
<div id="pause-menu" class="ui-panel">
<h3>暂停</h3>
<button class="game-button" id="resume-button">继续游戏</button>
<button class="game-button" id="restart-button">重新开始</button>
</div>
<div id="completion-modal" class="ui-panel">
<h3 id="completion-title">恭喜完成!</h3>
<p id="completion-message">您已经成功探索了所有基本形状!</p>
<button class="game-button" id="play-again-button">再玩一次</button>
</div>
</div>
<script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/three.js/110/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r110/examples/js/controls/OrbitControls.js"></script>
<script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/gsap/3.9.1/gsap.min.js"></script>
<script>
// Declare variables at the very top to prevent reference errors
let scene, camera, renderer;
let raycaster;
let mouse;
let interactiveObjects = []; // Array to store clickable meshes
let gamePaused = false;
let currentTargetHighlightTween = null;
let hoveredObject = null;
let controls; // Declare OrbitControls variable
let cameraAnimationTween = null; // To keep track of the GSAP camera animation
// Game State
const gameData = {
tasks: [
{ id: 'findCube', target: 'cubeMesh', text: '找到立方体', info: { title: '关于立方体', content: '立方体有6个面,12条边,8个顶点。所有面都是正方形,所有边长度相等。' }, score: 10 },
{ id: 'findSphere', target: 'sphereMesh', text: '找到球体', info: { title: '关于球体', content: '球体是一个完全圆形的几何对象,它是完全对称的。球体没有边和顶点。' }, score: 15 },
{ id: 'findCylinder', target: 'cylinderMesh', text: '找到圆柱体', info: { title: '关于圆柱体', content: '圆柱体由两个平行的圆形底面和连接它们的一个弯曲表面组成。它有2个边(圆周),没有顶点。' }, score: 12 },
{ id: 'findPyramid', target: 'pyramidMesh', text: '找到棱锥', info: { title: '关于棱锥', content: '棱锥有一个多边形底面和三角形侧面,这些侧面在顶点(称为锥顶)处相遇。侧面的数量取决于底面的边数。' }, score: 18 }
],
currentTaskIndex: 0,
score: 0,
completedTasks: [],
knowledgeCollected: {} // Store knowledge points collected
};
// UI Elements
const taskDisplay = document.getElementById('current-task');
const scoreDisplay = document.getElementById('current-score');
const progressBar = document.getElementById('progress-bar');
const infoModal = document.getElementById('info-modal');
const infoModalTitle = document.getElementById('info-modal-title');
const infoModalContent = document.getElementById('info-modal-content');
const closeInfoModalButton = document.getElementById('close-info-modal');
const continueButton = document.getElementById('continue-button');
const pauseButton = document.getElementById('pause-button');
const pauseMenu = document.getElementById('pause-menu');
const resumeButton = document.getElementById('resume-button');
const restartButton = document.getElementById('restart-button');
const completionModal = document.getElementById('completion-modal');
const playAgainButton = document.getElementById('play-again-button');
// Initialize the game
// Add try...catch around init call to catch early errors
try {
init();
animate();
} catch (error) {
console.error("Error during game initialization or animation setup:", error);
// Optionally display a user-friendly error message on the UI
if(taskDisplay) {
taskDisplay.innerText = '加载失败!';
}
const errorDiv = document.createElement('div');
errorDiv.style.cssText = 'position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: rgba(255, 0, 0, 0.8); color: white; padding: 20px; border-radius: 10px; z-index: 100;';
errorDiv.innerText = '游戏加载失败。请检查控制台获取详情。';
document.body.appendChild(errorDiv);
}
function init() {
console.log("Initializing game...");
// Scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0xcce0ff); // Light blue sky
// Camera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 5, 15);
camera.lookAt(0, 0, 0);
console.log("Camera initialized at", camera.position.toArray());
// Renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
const gameContainer = document.getElementById('game-container');
if(gameContainer){
gameContainer.appendChild(renderer.domElement);
console.log("Renderer canvas appended to game-container.");
} else {
console.error("Error: Could not find #game-container div!");
// Throwing an error here will be caught by the outer try/catch
throw new Error("Game container div not found.");
}
console.log("Renderer initialized.");
// OrbitControls - Initialize controls AFTER camera and renderer
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // Smooth camera movement
controls.dampingFactor = 0.25;
controls.screenSpacePanning = false; // Keep panning in object's x-y plane
controls.maxPolarAngle = Math.PI / 2; // Limit vertical rotation to prevent flipping
controls.target.set(0, 0, 0); // Set initial control target to origin
console.log("OrbitControls initialized.");
// Add event listener to controls to stop camera animation if user takes control
if (controls) {
controls.addEventListener('start', () => {
console.log("User started interacting with controls, stopping camera animation.");
if (cameraAnimationTween) {
cameraAnimationTween.kill();
cameraAnimationTween = null; // Clear the tween variable
}
});
}
// Lighting
const ambientLight = new THREE.AmbientLight(0x404040); // Soft white light
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(1, 1, 1).normalize();
scene.add(directionalLight);
console.log("Lighting added.");
// Geometry and Materials
const planeGeometry = new THREE.PlaneGeometry(50, 50);
const planeMaterial = new THREE.MeshLambertMaterial({ color: 0x90ee90 }); // Light green grass
const plane = new THREE.Mesh(planeGeometry, planeMaterial);
plane.rotation.x = -Math.PI / 2; // Rotate to be horizontal
scene.add(plane);
console.log("Ground plane added.");
const cubeGeometry = new THREE.BoxGeometry(2, 2, 2);
const cubeMaterial = new THREE.MeshLambertMaterial({ color: 0xff0000 }); // Red
const cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
cube.position.set(-5, 1, 0);
cube.name = 'cubeMesh'; // Assign a name for identification
cube.userData = { type: 'shape', name: '立方体' };
interactiveObjects.push(cube);
scene.add(cube);
console.log("Cube added at", cube.position.toArray());
const sphereGeometry = new THREE.SphereGeometry(1.5, 32, 32);
const sphereMaterial = new THREE.MeshLambertMaterial({ color: 0x0000ff }); // Blue
const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphere.position.set(5, 1.5, -5);
sphere.name = 'sphereMesh';
sphere.userData = { type: 'shape', name: '球体' };
interactiveObjects.push(sphere);
scene.add(sphere);
console.log("Sphere added at", sphere.position.toArray());
const cylinderGeometry = new THREE.CylinderGeometry(1.5, 1.5, 3, 32);
const cylinderMaterial = new THREE.MeshLambertMaterial({ color: 0xffff00 }); // Yellow
const cylinder = new THREE.Mesh(cylinderGeometry, cylinderMaterial);
cylinder.position.set(0, 1.5, 5); // Positioned at (0, 1.5, 5)
cylinder.name = 'cylinderMesh';
cylinder.userData = { type: 'shape', name: '圆柱体' };
interactiveObjects.push(cylinder); // Added to interactiveObjects
scene.add(cylinder);
console.log("Cylinder added at", cylinder.position.toArray(), "Name:", cylinder.name);
const pyramidGeometry = new THREE.ConeGeometry(2, 3, 4); // Base radius, height, segments
const pyramidMaterial = new THREE.MeshLambertMaterial({ color: 0xffa500 }); // Orange
const pyramid = new THREE.Mesh(pyramidGeometry, pyramidMaterial);
pyramid.position.set(0, 1.5, -10);
pyramid.name = 'pyramidMesh';
pyramid.userData = { type: 'shape', name: '棱锥' };
interactiveObjects.push(pyramid);
scene.add(pyramid);
console.log("Pyramid added at", pyramid.position.toArray());
console.log("All interactive objects:", interactiveObjects.map(obj => obj.name));
// Raycaster for interactions
raycaster = new THREE.Raycaster();
mouse = new THREE.Vector2();
// Event Listeners
window.addEventListener('resize', onWindowResize, false);
renderer.domElement.addEventListener('click', onCanvasClick, false);
// Add hover effect listener (optional, for visual feedback)
renderer.domElement.addEventListener('mousemove', onCanvasMouseMove, false);
// UI Event Listeners
closeInfoModalButton.addEventListener('click', hideInfoModal);
continueButton.addEventListener('click', handleContinue);
pauseButton.addEventListener('click', togglePauseMenu);
resumeButton.addEventListener('click', togglePauseMenu); // Resume button also just closes the menu
restartButton.addEventListener('click', restartGame);
playAgainButton.addEventListener('click', restartGame);
console.log("Event listeners added.");
// Initial Game State Setup
updateUI();
console.log("Initial UI updated.");
loadGame(); // Attempt to load previous progress
console.log("Attempting to load game...");
console.log("GameData score after init/loadGame call:", gameData.score); // Log score after load attempt
}
function animate() {
if (gamePaused) {
requestAnimationFrame(animate);
return;
}
requestAnimationFrame(animate);
// Update controls in the animate loop
if (controls) {
controls.update();
}
renderer.render(scene, camera);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onCanvasClick(event) {
console.log("Canvas click detected."); // Log at the start of click handler
// Do not process clicks on 3D objects if game is paused or a modal is open
if (gamePaused || infoModal.style.display !== 'none' || completionModal.style.display !== 'none') {
console.log("Click ignored: game paused or modal open."); // Log if click is ignored
return;
}
// Calculate mouse position in normalized device coordinates (-1 to +1)
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
console.log("Mouse position:", mouse.x, mouse.y);
// Update the picking ray with the camera and mouse position
raycaster.setFromCamera(mouse, camera);
console.log("Raycaster updated from camera.");
// Calculate objects intersecting the picking ray
const intersects = raycaster.intersectObjects(interactiveObjects, true); // Check interactiveObjects array
console.log("Intersects found:", intersects.length);
if (intersects.length > 0) {
const clickedObject = intersects[0].object;
console.log('Clicked on object with name:', clickedObject.name); // Debugging
// Check if the clicked object is the target for the current task
const currentTask = gameData.tasks[gameData.currentTaskIndex];
console.log("Current task target:", currentTask.target);
if (clickedObject.name === currentTask.target) {
console.log('Condition met: Clicked object matches current task target. Calling handleTaskCompletion.'); // *** Added Log ***
handleTaskCompletion(currentTask, clickedObject);
} else {
console.log('Wrong object clicked.'); // Debugging
// Optional: Provide visual/audio feedback for wrong click
// new Audio('wrong_answer.mp3').play(); // Requires audio file
gsap.to(clickedObject.scale, { x: 1.1, y: 1.1, z: 1.1, duration: 0.1, yoyo: true, repeat: 1 });
}
// Regardless of correct/wrong, show info if it's an interactive object that has associated info
const clickedTask = gameData.tasks.find(t => t.target === clickedObject.name);
if(clickedTask && clickedTask.info){
console.log("Info found for clicked object, showing modal."); // *** Added Log ***
showInfoModal(clickedObject);
} else {
console.log("No info found for clicked object or not an info-linked object."); // *** Added Log ***
}
} else {
console.log('No interactive object clicked.'); // Debugging
}
}
function onCanvasMouseMove(event) {
// Disable hover effects if game is paused or a modal is open
if (gamePaused || infoModal.style.display !== 'none' || completionModal.style.display !== 'none') {
if (hoveredObject) {
resetObjectHighlight(hoveredObject);
hoveredObject = null;
}
return;
}
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(interactiveObjects, true);
if (intersects.length > 0) {
const object = intersects[0].object;
if (hoveredObject !== object) {
if (hoveredObject) {
resetObjectHighlight(hoveredObject);
}
highlightObject(object);
hoveredObject = object;
}
} else {
if (hoveredObject) {
resetObjectHighlight(hoveredObject);
hoveredObject = null;
}
}
}
function highlightObject(object) {
// Don't highlight if it's already the pulsing target highlight
if (currentTargetHighlightTween && currentTargetHighlightTween.vars.target === object.material) {
return;
}
if (object.originalMaterial === undefined) {
object.originalMaterial = object.material;
}
// Use a subtle emissive color or outline effect
const highlightMaterial = object.originalMaterial.clone();
highlightMaterial.emissive = new THREE.Color(0x00ff00); // Green glow
highlightMaterial.emissiveIntensity = 0.2;
object.material = highlightMaterial;
document.body.style.cursor = 'pointer'; // Change cursor
}
function resetObjectHighlight(object) {
// Don't reset if it's the currently pulsing target highlight
if (currentTargetHighlightTween && currentTargetHighlightTween.vars.target === object.material) {
return;
}
if (object && object.originalMaterial !== undefined) {
object.material = object.originalMaterial;
delete object.originalMaterial; // Clean up
}
document.body.style.cursor = 'default'; // Reset cursor
}
function showInfoModal(object) {
console.log("showInfoModal called for object:", object ? object.name : 'null'); // *** Added Log ***
const task = gameData.tasks.find(t => t.target === object.name);
if (task && task.info) {
infoModalTitle.innerText = task.info.title;
infoModalContent.innerText = task.info.content;
infoModal.style.display = 'block';
// Prevent canvas interaction while modal is open - this also disables controls
renderer.domElement.style.pointerEvents = 'none';
if(controls) controls.enabled = false; // Explicitly disable controls
console.log("Info modal shown, controls disabled.");
// Optional: Play sound or animation for modal appearance
// new Audio('modal_open.mp3').play(); // Requires audio file
gsap.fromTo(infoModal, { opacity: 0, scale: 0.8 }, { opacity: 1, scale: 1, duration: 0.3 });
} else {
// This case should theoretically be caught by the check in onCanvasClick,
// but adding a log here just in case.
console.log("showInfoModal called but no specific info defined for this object.");
}
}
function hideInfoModal() {
// Optional: Play sound or animation for modal disappearance
gsap.to(infoModal, { opacity: 0, scale: 0.8, duration: 0.3, onComplete: () => {
infoModal.style.display = 'none';
// Re-enable canvas interaction and controls
renderer.domElement.style.pointerEvents = 'auto';
if(controls) controls.enabled = true; // Explicitly re-enable controls
console.log("Info modal hidden, controls enabled.");
// new Audio('modal_close.mp3').play(); // Requires audio file
} });
}
function handleContinue() {
// Logic to continue after reading info - currently handled by hideInfoModal
console.log("Continue button clicked."); // Log continue click
hideInfoModal();
// In a more complex game, 'continue' might trigger the next step or quiz
}
function handleTaskCompletion(task, object) {
console.log("Attempting to complete task:", task.id, "Current task index BEFORE increment:", gameData.currentTaskIndex); // Log at the start of task completion
if (!gameData.completedTasks.includes(task.id)) {
console.log("Task", task.id, "not yet completed.");
gameData.completedTasks.push(task.id);
gameData.score += task.score; // This line executes (score updates)
gameData.knowledgeCollected[task.id] = task.info; // Store collected knowledge
console.log("Task completed:", task.id, "Score:", gameData.score); // This should log if score updates
// Optional: Play sound or animation for success
// new Audio('task_complete.mp3').play(); // Requires audio file
gsap.to(object.scale, { x: 1.2, y: 1.2, z: 1.2, duration: 0.2, yoyo: true, repeat: 1 });
// Reset highlight on the completed object
resetHighlightOnCompletion(object); // This should execute
// Move to the next task
gameData.currentTaskIndex++; // This line executes if score updates
console.log("Task index incremented to:", gameData.currentTaskIndex); // Log the new index
if (gameData.currentTaskIndex < gameData.tasks.length) { // Condition for setting next task
console.log("Condition met: Moving to next task. gameData.currentTaskIndex < gameData.tasks.length is true (", gameData.currentTaskIndex, "<", gameData.tasks.length, ")"); // *** Added Log Here ***
setTask(gameData.currentTaskIndex); // <-- This should be called
highlightCurrentTarget(); // <-- This should be called
// Optional: Camera animation to new target
const nextTargetObject = scene.getObjectByName(gameData.tasks[gameData.currentTaskIndex].target);
if(nextTargetObject){
animateCameraToTarget(nextTargetObject.position);
} else {
console.error("handleTaskCompletion Error: Next target object not found in scene:", gameData.tasks[gameData.currentTaskIndex].target);
}
} else {
console.log("Condition met: All tasks completed. gameData.currentTaskIndex < gameData.tasks.length is false (", gameData.currentTaskIndex, ">=", gameData.tasks.length, ")"); // *** Added Log Here ***
// Game Completed
endGame();
}
updateUI(); // <-- This should be called after task completion logic
saveGame(); // <-- This should be called
} else {
console.log("Task already completed:", task.id); // Debugging
// Optional: Provide feedback that task is already done
}
}
function setTask(index) {
console.log("Attempting to set task for index:", index, "gameData.tasks.length:", gameData.tasks.length); // Add log here
if (index < gameData.tasks.length && index >= 0) { // Add bounds check
if(taskDisplay) { // Ensure taskDisplay element exists
taskDisplay.innerText = gameData.tasks[index].text; // <-- This line updates the text
console.log("Current Task text set to:", gameData.tasks[index].text); // <-- Should see this log
console.log("Current Task target:", gameData.tasks[index].target);
} else {
console.error("setTask Error: taskDisplay element not found.");
}
} else if (index >= gameData.tasks.length) {
if(taskDisplay) taskDisplay.innerText = '游戏完成!';
console.log("Task index is out of bounds, game finished state.");
} else {
if(taskDisplay) taskDisplay.innerText = '加载失败或无任务'; // Indicate a potential issue
console.error("Error: Invalid task index received by setTask:", index, ". gameData.tasks.length:", gameData.tasks.length);
}
}
function updateUI() {
if(scoreDisplay) scoreDisplay.innerText = gameData.score;
if(progressBar && gameData.tasks.length > 0) {
const progress = (gameData.completedTasks.length / gameData.tasks.length) * 100;
progressBar.style.width = `${progress}%`;
console.log("UI updated. Score:", gameData.score, "Progress:", progress);
} else {
console.log("UI updated. Score:", gameData.score, "Progress bar not updated (tasks.length is 0 or progressBar not found).");
}
if (gameData.currentTaskIndex < gameData.tasks.length) {
// Ensure task display is updated correctly here too, although setTask is primary
// taskDisplay.innerText = gameData.tasks[gameData.currentTaskIndex].text; // Removed redundant update
console.log("updateUI confirms current task index:", gameData.currentTaskIndex);
} else {
if(taskDisplay) taskDisplay.innerText = '游戏完成!';
console.log("updateUI confirms game completion state.");
}
}
// Variable to store the current camera animation tween
// Declared at the top: let cameraAnimationTween = null;
function animateCameraToTarget(targetPosition) {
console.log("Animating camera to target position:", targetPosition.toArray());
// Disable controls during animation
if (controls) {
controls.enabled = false;
console.log("Controls disabled during camera animation.");
}
// Kill any existing camera animation tween
if (cameraAnimationTween) {
cameraAnimationTween.kill();
cameraAnimationTween = null;
console.log("Killed existing camera animation tween.");
}
// Create a timeline for sequential position and rotation animation if needed,
// but for simplicity, we can run them in parallel and manage the onComplete on one.
const positionTween = gsap.to(camera.position, {
x: targetPosition.x,
y: camera.position.y, // Maintain current height, or set a target height
z: targetPosition.z + 10, // Move to be in front of the target
duration: 1.5,
ease: "power2.inOut",
onUpdate: () => {
camera.lookAt(targetPosition.x, targetPosition.y, targetPosition.z);
}
});
const targetQuaternion = new THREE.Quaternion().setFromRotationMatrix(
new THREE.Matrix4().lookAt(camera.position, targetPosition, camera.up)
);
const rotationTween = gsap.to(camera.quaternion, {
x: targetQuaternion.x,
y: targetQuaternion.y,
z: targetQuaternion.z,
w: targetQuaternion.w,
duration: 1.5,
ease: "power2.inOut",
onComplete: () => {
console.log("Camera animation complete.");
// Re-enable controls after animation
if (controls) {
controls.enabled = true;
// Force controls update to reflect final camera state
controls.update();
console.log("Controls re-enabled after camera animation.");
}
cameraAnimationTween = null; // Clear the tween variable
}
});
// Store the rotation tween as the main one to track completion status
cameraAnimationTween = rotationTween;
// Update controls target to the object's position after the animation starts
if(controls) {
// Animate controls target as well for a smoother transition if user takes over during animation
gsap.to(controls.target, {
x: targetPosition.x,
y: targetPosition.y, // Or targetPosition.y + something for height
z: targetPosition.z,
duration: 1.5,
ease: "power2.inOut"
});
}
}
function togglePauseMenu() {
gamePaused = !gamePaused;
pauseMenu.style.display = gamePaused ? 'block' : 'none';
// Disable/Enable canvas interaction and controls based on pause state
renderer.domElement.style.pointerEvents = gamePaused ? 'none' : 'auto';
if(controls) controls.enabled = !gamePaused; // Disable controls when paused
console.log("Game paused state:", gamePaused, "Controls enabled:", controls.enabled);
// Optional: Play sound
// new Audio(gamePaused ? 'pause.mp3' : 'resume.mp3').play(); // Requires audio file
}
function restartGame() {
console.log("Restarting game...");
// Stop any current camera animation
if (cameraAnimationTween) {
cameraAnimationTween.kill();
cameraAnimationTween = null;
console.log("Killed camera animation tween during restart.");
}
// Reset game state
gameData.currentTaskIndex = 0;
gameData.score = 0; // Ensure score is reset to 0
gameData.completedTasks = [];
gameData.knowledgeCollected = {};
console.log("Game state reset:", {
currentTaskIndex: gameData.currentTaskIndex,
score: gameData.score,
completedTasks: gameData.completedTasks.length
});
// Hide modals
infoModal.style.display = 'none';
pauseMenu.style.display = 'none';
completionModal.style.display = 'none';
// Reset Three.js scene elements if needed (not strictly necessary for simple shape positions)
interactiveObjects.forEach(obj => {
if (obj.originalMaterial !== undefined) {
obj.material = obj.originalMaterial;
delete obj.originalMaterial;
}
// Reset any scale changes from feedback
gsap.killTweensOf(obj.scale);
obj.scale.set(1, 1, 1);
});
console.log("Scene elements reset.");
// Update UI and set first task
updateUI(); // This will show score 0 and update progress
console.log("restartGame logic reached point before setting task.");
setTask(gameData.currentTaskIndex); // Set the first task
// Reset camera position and rotation with animation
console.log("Resetting camera to initial position and rotation...");
const initialPosition = new THREE.Vector3(0, 5, 15);
const initialQuaternion = new THREE.Quaternion().setFromRotationMatrix(
new THREE.Matrix4().lookAt(initialPosition, new THREE.Vector3(0, 0, 0), camera.up)
);
// Temporarily disable controls during restart animation
if(controls) controls.enabled = false;
const restartPositionTween = gsap.to(camera.position, {
x: initialPosition.x,
y: initialPosition.y,
z: initialPosition.z,
duration: 1.5,
ease: "power2.inOut",
onComplete: () => { // Re-enable controls after position animation (or the longer one if using timeline)
if (controls) {
controls.enabled = true;
controls.update(); // Ensure controls are synced after animation
console.log("Controls re-enabled after restart position animation.");
}
}
});
const restartRotationTween = gsap.to(camera.quaternion, {
x: initialQuaternion.x,
y: initialQuaternion.y,
z: initialQuaternion.z,
w: initialQuaternion.w,
duration: 1.5,
ease: "power2.inOut"
});
// Reset controls target to origin after restart animation starts
if(controls) {
gsap.to(controls.target, {
x: 0, y: 0, z: 0, duration: 1.5, ease: "power2.inOut"
});
}
highlightCurrentTarget(); // Highlight the first target
// Ensure game is not paused
gamePaused = false;
renderer.domElement.style.pointerEvents = 'auto'; // Ensure canvas is interactable
saveGame(); // Save initial state
console.log("Game restarted. Score is:", gameData.score); // Log score after restart
console.log("Game restarted.");
}
function endGame() {
console.log("Ending game...");
gamePaused = true; // Pause the game
completionModal.style.display = 'block';
// Disable canvas interaction and controls
renderer.domElement.style.pointerEvents = 'none';
if(controls) controls.enabled = false;
console.log("Game ended, controls disabled.");
// Stop highlighting the last target and reset its material
const lastTaskIndex = gameData.tasks.length - 1;
if(lastTaskIndex >= 0 && gameData.tasks[lastTaskIndex]) { // Ensure there was at least one task
const lastTargetObjectName = gameData.tasks[lastTaskIndex].target;
if(lastTargetObjectName){
const lastTargetObject = scene.getObjectByName(lastTargetObjectName);
resetHighlightOnCompletion(lastTargetObject); // Explicitly reset highlight
}
}
// Ensure any pending highlight tween is killed
if (currentTargetHighlightTween) {
currentTargetHighlightTween.kill();
currentTargetHighlightTween = null;
}
console.log("Highlighting stopped on completion.");
// Optional: Play celebratory sound/animation
// new Audio('game_complete.mp3').play(); // Requires audio file
gsap.fromTo(completionModal, { opacity: 0, scale: 0.8 }, { opacity: 1, scale: 1, duration: 0.5 });
console.log("Completion modal shown.");
}
function saveGame() {
try {
const gameProgress = {
currentTaskIndex: gameData.currentTaskIndex,
score: gameData.score,
completedTasks: gameData.completedTasks,
knowledgeCollected: gameData.knowledgeCollected,
cameraPosition: camera.position.toArray(),
cameraQuaternion: camera.quaternion.toArray(), // Save quaternion instead of rotation
controlsTarget: controls ? controls.target.toArray() : new THREE.Vector3(0,0,0).toArray() // Save controls target
};
localStorage.setItem('learningGameProgress', JSON.stringify(gameProgress));
console.log("Game saved successfully. Current score:", gameData.score); // Log saved score
} catch (e) {
console.error("Could not save game:", e);
}
}
function loadGame() {
try {
console.log("Executing loadGame...");
const savedProgress = localStorage.getItem('learningGameProgress');
if (savedProgress) {
console.log("Found saved game data.");
const gameProgress = JSON.parse(savedProgress);
gameData.currentTaskIndex = gameProgress.currentTaskIndex || 0;
gameData.score = gameProgress.score || 0; // Load saved score
gameData.completedTasks = gameProgress.completedTasks || [];
gameData.knowledgeCollected = gameProgress.knowledgeCollected || {};
// Restore camera position and rotation
if (gameProgress.cameraPosition) {
camera.position.fromArray(gameProgress.cameraPosition);
console.log("Loaded camera position:", camera.position.toArray());
}
if (gameProgress.cameraQuaternion) {
camera.quaternion.fromArray(gameProgress.cameraQuaternion);
console.log("Loaded camera quaternion:", camera.quaternion.toArray());
} else if (gameProgress.cameraRotation) { // Fallback for older saves
camera.rotation.fromArray(gameProgress.cameraRotation);
// Note: Loading Euler rotations can be problematic, converting to quaternion is safer
console.log("Loaded camera rotation (fallback):", camera.rotation.toArray());
}
// Restore controls target
if(controls && gameProgress.controlsTarget){
controls.target.fromArray(gameProgress.controlsTarget);
console.log("Loaded controls target:", controls.target.toArray());
} else if (controls) {
// If no saved target, set to origin
controls.target.set(0,0,0);
console.log("No saved controls target, setting to origin.");
}
if(controls) controls.update(); // Update controls after loading state
console.log("Game data loaded successfully. State:", {
currentTaskIndex: gameData.currentTaskIndex,
score: gameData.score, // Log loaded score
completedTasks: gameData.completedTasks.length
});
// If game was completed on last save, show completion modal
if (gameData.currentTaskIndex >= gameData.tasks.length) {
console.log("Loaded game state is completed, ending game.");
endGame();
} else {
console.log("loadGame logic reached point before setting task/updating UI.");
setTask(gameData.currentTaskIndex); // Set the task based on loaded index
updateUI(); // updateUI also shows the loaded score
highlightCurrentTarget(); // Highlight the current task's target after loading
}
} else {