File size: 58,257 Bytes
8cdfdf8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4dda8ae
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Byte-Sized Brawl: Code Chaos</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
    <style>
        body {
            margin: 0;
            overflow: hidden;
            font-family: 'Inter', sans-serif;
            background-color: #1a1a2e; /* Dark background */
            color: #e0e0e0; /* Light text */
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: flex-start; /* Align items to the top to ensure space for description */
            min-height: 100vh;
        }

        #game-container {
            position: relative;
            width: 100vw;
            height: 80vh; /* Make game container take 80% of viewport height */
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #1f1f3f; /* Slightly different background to see container boundaries */
        }

        canvas {
            display: block;
            background-color: #2a2a4a; /* Slightly lighter dark blue for canvas */
            border-radius: 15px; /* Rounded corners for canvas */
            box-shadow: 0 0 20px rgba(0, 255, 255, 0.5); /* Glowing effect */
            width: 100%; /* Ensure canvas fills container width */
            height: 100%; /* Ensure canvas fills container height */
        }

        #ui-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none; /* Allow mouse events to pass through to canvas */
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            padding: 20px;
            box-sizing: border-box;
        }

        .player-stats {
            display: flex;
            justify-content: space-between;
            width: 100%;
        }

        .player-info {
            background-color: rgba(0, 0, 0, 0.6);
            padding: 10px 15px;
            border-radius: 10px;
            border: 1px solid #00ffff; /* Cyan border */
            box-shadow: 0 0 10px rgba(0, 255, 255, 0.3);
            pointer-events: auto; /* Allow interaction with these elements */
            font-size: 1.1em;
            display: flex;
            flex-direction: column;
            gap: 5px;
            min-width: 150px;
            text-align: center;
        }

        .health-bar-container {
            width: 100%;
            background-color: #555;
            border-radius: 5px;
            height: 10px;
            overflow: hidden;
            border: 1px solid #00ffff;
        }

        .health-bar {
            height: 100%;
            background-color: #00ff00; /* Green health */
            width: 100%; /* Will be updated by JS */
            transition: width 0.2s ease-out;
        }

        #reset-button-container {
            width: 100%;
            display: flex;
            justify-content: center;
            pointer-events: auto; /* Allow interaction with button */
        }

        #resetButton {
            background-color: #4CAF50; /* Green */
            color: white;
            padding: 12px 25px;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-size: 1.2em;
            box-shadow: 0 5px #388e3c; /* Darker green shadow */
            transition: all 0.2s ease;
            pointer-events: auto; /* Allow interaction */
        }

        #resetButton:hover {
            background-color: #45a049;
            box-shadow: 0 3px #388e3c;
            transform: translateY(2px);
        }

        #resetButton:active {
            background-color: #3e8e41;
            box-shadow: 0 0 #388e3c;
            transform: translateY(5px);
        }

        #floating-message {
            position: absolute;
            top: 20%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(0, 0, 0, 0.8);
            padding: 15px 25px;
            border-radius: 10px;
            border: 2px solid #00ffff;
            box-shadow: 0 0 15px rgba(0, 255, 255, 0.7);
            text-align: center;
            font-size: 1.3em;
            color: #ffffff;
            z-index: 1000;
            opacity: 0; /* Hidden by default */
            transition: opacity 0.3s ease-in-out;
            pointer-events: none; /* Allow mouse events to pass through */
        }

        .game-description-container {
            width: 80%;
            max-width: 900px;
            background-color: rgba(0, 0, 0, 0.6);
            padding: 20px;
            border-radius: 15px;
            border: 1px solid #00ffff;
            box-shadow: 0 0 15px rgba(0, 255, 255, 0.4);
            margin-top: 20px;
            text-align: left;
            overflow-y: auto; /* Enable scrolling for long descriptions */
            max-height: 18vh; /* Adjust max-height to fit remaining space */
            margin-bottom: 20px; /* Add some margin at the bottom */
        }

        .game-description-container h2 {
            color: #00ffff;
            margin-top: 0;
            text-align: center;
        }

        .game-description-container h3 {
            color: #99ffff;
            margin-top: 15px;
        }

        .game-description-container ul {
            list-style-type: disc;
            margin-left: 20px;
        }

        .game-description-container li {
            margin-bottom: 5px;
        }

        /* Responsive adjustments */
        @media (max-width: 768px) {
            .player-info {
                font-size: 0.9em;
                padding: 8px 10px;
                min-width: unset;
            }
            #resetButton {
                padding: 10px 20px;
                font-size: 1em;
            }
            .game-description-container {
                width: 95%;
                padding: 15px;
                font-size: 0.9em;
                max-height: 25vh; /* Adjust max-height for smaller screens */
            }
            #game-container {
                height: 65vh; /* Adjust game container height for smaller screens */
            }
            #floating-message {
                font-size: 1em;
                padding: 10px 15px;
            }
        }
    </style>
</head>
<body>
    <div id="game-container">
        <canvas id="gameCanvas"></canvas>
        <div id="ui-overlay">
            <div class="player-stats">
                <div class="player-info">
                    Player 1 (WASD/E)<br>
                    Life: <span id="player1Life">100</span>
                    <div class="health-bar-container"><div id="player1HealthBar" class="health-bar"></div></div>
                    KOs: <span id="player1KOs">0</span>
                </div>
                <div class="player-info">
                    Player 2 (IJKL/U)<br>
                    Life: <span id="player2Life">100</span>
                    <div class="health-bar-container"><div id="player2HealthBar" class="health-bar"></div></div>
                    KOs: <span id="player2KOs">0</span>
                </div>
            </div>
            <div id="reset-button-container">
                <button id="resetButton">Reset Game</button>
            </div>
        </div>
        <div id="floating-message"></div>
    </div>

    <div class="game-description-container">
        <h2>Byte-Sized Brawl: Code Chaos</h2>
        <p>Welcome to "Byte-Sized Brawl: Code Chaos"! Dive into a retro-futuristic 3D arena, a simulated MMO testing ground where glitches are the least of your worries. Team up or face off against a friend in this top-down action-RPG, engaging in chaotic combat, solving byte-sized puzzles, and navigating a world on the brink of a digital meltdown!</p>

        <h3>Game Parts:</h3>
        <ul>
            <li><strong>Playable Characters:</strong> Two stylized humanoid figures (Player 1 and Player 2), assembled from 3D primitives, ready for action.</li>
            <li><strong>Glitch Bots:</strong> Various enemies constructed from primitive shapes, each with unique (and sometimes buggy) attack patterns.</li>
            <li><strong>Interactive Environment:</strong> A 3D arena with obstacles, movable blocks, and pressure plates that might just lead to digital treasure... or a trap!</li>
            <li><strong>NPCs (Non-Playable Code):</strong> Simple primitive figures offering cryptic quests and dialogue that might just make sense in the matrix.</li>
            <li><strong>Skill Tree (Conceptual):</strong> While not fully implemented in this demo, imagine a branching path of digital upgrades to enhance your character's abilities.</li>
            <li><strong>Digital Loot:</strong> Primitive-assembled items and equipment to boost your stats.</li>
            <li><strong>Life/Score Display:</strong> Keep track of your vital signs and KOs with clear displays at the top of the screen.</li>
            <li><strong>"Reset" Button:</strong> Your ultimate debug tool! Heals both players to full life and resets the current area, perfect for when things get too chaotic.</li>
        </ul>

        <h3>Method Steps:</h3>
        <ul>
            <li><strong>Explore the Digital Frontier:</strong> Navigate the top-down, full-screen 3D scene.</li>
            <li><strong>Player 1 Controls (WASD):</strong> Move your character with precision.</li>
            <li><strong>Player 2 Controls (IJKL):</strong> Guide your companion through the chaos.</li>
            <li><strong>Left Player Action (E):</strong> Unleash a digital attack, activate objects, or try to understand the NPCs.</li>
            <li><strong>Right Player Action (U):</strong> Perform your own digital assault, interact with the environment, or just flail wildly.</li>
            <li><strong>Solve Byte-Sized Puzzles:</strong> Push blocks, activate pressure plates, and bypass laser grids (if they were here!).</li>
            <li><strong>Complete Quests (Theoretically):</strong> Accept challenges from NPCs and try not to break the simulation.</li>
            <li><strong>Level Up (Imagination Required):</strong> Gain experience and unlock new skills from your conceptual skill tree.</li>
            <li><strong>Hit the Reset Button:</strong> When all else fails, use the "Reset Game" button to get a fresh start.</li>
        </ul>

        <h3>Rules of Engagement:</h3>
        <ul>
            <li><strong>Combat Rewards:</strong> Defeat Glitch Bots to earn experience and digital loot.</li>
            <li><strong>Skill Gates:</strong> Certain areas or puzzles might require specific skills or items (in a full version!).</li>
            <li><strong>Narrative Glitches:</strong> Dialogue choices might impact the story (or just confuse you further).</li>
            <li><strong>Co-op or Compete:</strong> Work together to achieve common goals, or compete for the most KOs and resources.</li>
            <li><strong>Incapacitation Protocol:</strong> If your life bar depletes, you're incapacitated! Your partner can revive you by getting close and using their action button, or you can both use the "Reset" button. If both players are down, it's game over!</li>
        </ul>

        <h3>What Makes It Fun:</h3>
        <ul>
            <li><strong>Retro-Futuristic Mashup:</strong> A unique blend of nostalgic 2D action-RPG vibes with modern 3D chaos.</li>
            <li><strong>Dynamic Duo Gameplay:</strong> The cooperative/competitive modes add layers of strategy and hilarious interactions.</li>
            <li><strong>Varied Digital Mayhem:</strong> From combat to puzzles and the promise of skill progression, there's always something to do.</li>
            <li><strong>Witty Narrative:</strong> The "futuristic MMO testing ground" setting provides a fun, self-aware backdrop for your adventures.</li>
        </ul>
    </div>

    <script>
        // Global variables for Three.js
        let scene, camera, renderer;
        let player1, player2;
        let enemies = [];
        let movableBlock;
        let pressurePlate;
        let wallToOpen; // The wall that opens when pressure plate is activated
        let powerups = []; // Array to hold power-up objects
        let shieldVisual; // Visual representation of the co-op shield
        let activeExplosions = []; // To manage particle explosions
        let activeShieldParticles = []; // To manage shield healing particles

        // Game state variables
        const MAX_HEALTH = 100;
        let player1Health = MAX_HEALTH;
        let player2Health = MAX_HEALTH;
        let player1KOs = 0;
        let player2KOs = 0;
        let player1Incapacitated = false;
        let player2Incapacitated = false;
        let pressurePlateActivated = false;
        let isShieldActive = false; // New: Co-op shield state

        // Wave and Scoring
        let currentWave = 1;
        let enemiesInCurrentWave = 0;
        let enemiesDefeatedInWave = 0;
        let scorePerEnemy = 10;
        let totalScore = 0;

        // Player movement and action states
        const keys = {
            w: false, a: false, s: false, d: false, e: false, // Player 1
            i: false, j: false, k: false, l: false, u: false  // Player 2
        };
        const PLAYER_SPEED = 0.5;
        const BASE_ATTACK_RANGE = 10; // Base attack range
        const COOP_ATTACK_RANGE_BOOST = 15; // Additional range when co-op shield is active
        const ATTACK_COOLDOWN = 500; // milliseconds
        const ATTACK_DURATION = 200; // milliseconds for attack animation
        let player1LastAttackTime = 0;
        let player2LastAttackTime = 0;
        const ENEMY_SPEED = 0.1; // Slower enemy speed
        const POWERUP_DURATION = 5000; // 5 seconds for attack/magic/armor boost
        const SHIELD_RANGE = 20; // Distance for co-op shield activation
        const COOP_ATTACK_WINDOW = 300; // Time window for combined attack (milliseconds)
        const PARTICLE_LIFESPAN = 1000; // Particle system lifespan in ms

        // UI elements
        const player1LifeSpan = document.getElementById('player1Life');
        const player2LifeSpan = document.getElementById('player2Life');
        const player1KOsSpan = document.getElementById('player1KOs');
        const player2KOsSpan = document.getElementById('player2KOs');
        const player1HealthBar = document.getElementById('player1HealthBar');
        const player2HealthBar = document.getElementById('player2HealthBar');
        const resetButton = document.getElementById('resetButton');
        const floatingMessage = document.getElementById('floating-message');
        let messageTimeout; // To clear previous message timeouts

        // Function to show a custom message box (now disappearing text)
        function showMessage(message) {
            clearTimeout(messageTimeout); // Clear any existing timeout
            floatingMessage.textContent = message;
            floatingMessage.style.opacity = 1;
            messageTimeout = setTimeout(() => {
                floatingMessage.style.opacity = 0;
            }, 2000); // Disappear after 2 seconds
        }

        // --- Wave and Enemy Spawning Functions ---
        function spawnEnemiesForWave(waveNumber) {
            // Clear existing enemies
            enemies.forEach(enemy => scene.remove(enemy));
            enemies = [];

            const numEnemies = Math.min(15, 3 + waveNumber * 2); // Max 15 enemies, scaling
            scorePerEnemy = 10 * waveNumber; // Score increases per wave

            for (let i = 0; i < numEnemies; i++) {
                const x = (Math.random() - 0.5) * 100;
                const z = (Math.random() - 0.5) * 100;
                enemies.push(createEnemy(0x00ff00, x, 0, z));
            }
            enemies.forEach(enemy => scene.add(enemy));
            enemiesInCurrentWave = numEnemies;
            enemiesDefeatedInWave = 0;
            showMessage(`Wave ${waveNumber} started! Score per enemy: ${scorePerEnemy}`);
        }

        function checkWaveCompletion() {
            if (enemiesDefeatedInWave >= enemiesInCurrentWave) {
                currentWave++;
                showMessage(`Wave ${currentWave - 1} completed! Preparing Wave ${currentWave}...`);
                setTimeout(() => spawnEnemiesForWave(currentWave), 2000); // Delay for next wave
            }
        }
        // --- End Wave and Enemy Spawning Functions ---


        // Initialize the game
        window.onload = function() {
            checkCanvasDimensions();
        };

        function checkCanvasDimensions() {
            const canvas = document.getElementById('gameCanvas');
            if (canvas.clientWidth > 0 && canvas.clientHeight > 0) {
                console.log('Canvas dimensions are valid. Initializing Three.js...');
                initThreeJS();
                spawnEnemiesForWave(1); // Start the first wave
                animate();
            } else {
                console.log('Canvas dimensions not yet valid. Retrying in 100ms...');
                setTimeout(checkCanvasDimensions, 100);
            }
        }

        function initThreeJS() {
            console.log('initThreeJS called.');

            scene = new THREE.Scene();
            scene.background = new THREE.Color(0x2a2a4a);

            const canvas = document.getElementById('gameCanvas');
            const canvasWidth = canvas.clientWidth;
            const canvasHeight = canvas.clientHeight;

            console.log('initThreeJS - Canvas Width:', canvasWidth, 'Canvas Height:', canvasHeight);

            const aspect = canvasWidth / canvasHeight;
            const frustumSize = 120;

            camera = new THREE.OrthographicCamera(
                frustumSize * aspect / -2,
                frustumSize * aspect / 2,
                frustumSize / 2,
                frustumSize / -2,
                1,
                1000
            );
            camera.position.set(0, 70, 0);
            camera.lookAt(0, 0, 0);

            renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true });
            renderer.setSize(canvasWidth, canvasHeight);
            renderer.setPixelRatio(window.devicePixelRatio);

            const ambientLight = new THREE.AmbientLight(0x606060);
            scene.add(ambientLight);
            const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
            directionalLight.position.set(1, 1, 1).normalize();
            scene.add(directionalLight);

            const groundGeometry = new THREE.PlaneGeometry(150, 150);
            const groundMaterial = new THREE.MeshLambertMaterial({ color: 0x4a4a6a, side: THREE.DoubleSide });
            const ground = new THREE.Mesh(groundGeometry, groundMaterial);
            ground.rotation.x = Math.PI / 2;
            scene.add(ground);

            const gridHelper = new THREE.GridHelper(100, 10, 0x00ffff, 0x888888);
            scene.add(gridHelper);

            const axesHelper = new THREE.AxesHelper(50);
            scene.add(axesHelper);

            player1 = createPlayer(0xff0000, -20, 0, 0);
            player2 = createPlayer(0x0000ff, 20, 0, 0);
            scene.add(player1);
            scene.add(player2);

            // Create shield visual (initially hidden)
            const shieldGeometry = new THREE.CylinderGeometry(SHIELD_RANGE, SHIELD_RANGE, 1, 32);
            const shieldMaterial = new THREE.MeshBasicMaterial({ color: 0x00ffff, transparent: true, opacity: 0.2 });
            shieldVisual = new THREE.Mesh(shieldGeometry, shieldMaterial);
            shieldVisual.position.y = 5; // Place slightly above ground
            shieldVisual.visible = false; // Hide initially
            scene.add(shieldVisual);

            // Initialize puzzle elements and powerups here, so they are always defined
            movableBlock = createMovableBlock(0xffff00, -10, 0, -10);
            scene.add(movableBlock);
            pressurePlate = createPressurePlate(0x888888, 10, 0, -10);
            scene.add(pressurePlate);
            wallToOpen = createWall(0x663300, 10, 0, -20);
            scene.add(wallToOpen);

            powerups.push(createPowerup('health', -40, 0, 40));
            powerups.push(createPowerup('attack', 40, 0, 40));
            powerups.push(createPowerup('magic', -40, 0, -40));
            powerups.push(createPowerup('armor', 40, 0, -40));
            powerups.push(createPowerup('health', 0, 0, 0));
            powerups.forEach(powerup => scene.add(powerup));


            window.addEventListener('resize', onWindowResize, false);
            document.addEventListener('keydown', onKeyDown, false);
            document.addEventListener('keyup', onKeyUp, false);
            resetButton.addEventListener('click', resetGame);

            updateUI();
            onWindowResize();
        }

        // --- Object Creation Functions ---

        function createPlayer(color, x, y, z) {
            const playerGroup = new THREE.Group();

            // Body (Box)
            const bodyGeometry = new THREE.BoxGeometry(4, 8, 4);
            const bodyMaterial = new THREE.MeshLambertMaterial({ color: color });
            const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
            body.position.y = 4; // Center on ground
            playerGroup.add(body);

            // Head (Sphere)
            const headGeometry = new THREE.SphereGeometry(2, 16, 16);
            const headMaterial = new THREE.MeshLambertMaterial({ color: 0xffe0bd }); // Skin color
            const head = new THREE.Mesh(headGeometry, headMaterial);
            head.position.y = 10; // On top of body
            playerGroup.add(head);

            // Arms (Cylinders) - Now part of the player group for independent rotation
            // Right arm (for weapon)
            const armRightGroup = new THREE.Group();
            const armGeometry = new THREE.CylinderGeometry(1, 1, 6, 8);
            const armMaterial = new THREE.MeshLambertMaterial({ color: color });
            const armRightMesh = new THREE.Mesh(armGeometry, armMaterial);
            armRightMesh.position.set(0, 3, 0); // Position relative to arm group's pivot
            armRightGroup.add(armRightMesh);
            armRightGroup.position.set(3, 7, 0); // Position arm group relative to player body
            armRightGroup.rotation.z = -Math.PI / 4; // Initial rotation
            playerGroup.add(armRightGroup);
            playerGroup.userData.armRight = armRightGroup; // Store reference for animation

            // Weapon (simple box for now)
            const weaponGeometry = new THREE.BoxGeometry(1, 1, 5);
            const weaponMaterial = new THREE.MeshLambertMaterial({ color: 0x888888 });
            const weapon = new THREE.Mesh(weaponGeometry, weaponMaterial);
            weapon.position.set(0, 3, 2.5); // Position at the end of the arm
            armRightGroup.add(weapon);
            playerGroup.userData.weapon = weapon; // Store reference

            // Left arm
            const armLeft = new THREE.Mesh(armGeometry, armMaterial);
            armLeft.position.set(-3, 7, 0);
            armLeft.rotation.z = Math.PI / 4;
            playerGroup.add(armLeft);

            // Legs (Cylinders)
            const legGeometry = new THREE.CylinderGeometry(1.5, 1.5, 4, 8);
            const legMaterial = new THREE.MeshLambertMaterial({ color: 0x000000 }); // Dark color for pants
            const legLeft = new THREE.Mesh(legGeometry, legMaterial);
            legLeft.position.set(-1.5, 2, 0);
            playerGroup.add(legLeft);

            const legRight = new THREE.Mesh(legGeometry, legMaterial);
            legRight.position.set(1.5, 2, 0);
            playerGroup.add(legRight);

            playerGroup.position.set(x, y, z);
            playerGroup.userData.health = MAX_HEALTH;
            playerGroup.userData.isPlayer = true;
            playerGroup.userData.incapacitated = false;
            playerGroup.userData.isAttacking = false;
            playerGroup.userData.attackBoost = 0; // No attack boost initially
            playerGroup.userData.magicBoost = 0; // No magic boost initially
            playerGroup.userData.armorBoost = 0; // No armor boost initially
            return playerGroup;
        }

        function createEnemy(color, x, y, z) {
            const enemyGroup = new THREE.Group();

            // Main Body (Rounded Box)
            const bodyGeometry = new THREE.BoxGeometry(6, 6, 6);
            const bodyMaterial = new THREE.MeshLambertMaterial({ color: color });
            const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
            body.position.y = 3; // Center on ground
            enemyGroup.add(body);

            // Head (Octahedron for a more robotic/glitchy look)
            const headGeometry = new THREE.OctahedronGeometry(3);
            const headMaterial = new THREE.MeshLambertMaterial({ color: 0x888888 }); // Grey
            const head = new THREE.Mesh(headGeometry, headMaterial);
            head.position.y = 8; // On top of body
            enemyGroup.add(head);

            // Eyes (Small Spheres)
            const eyeGeometry = new THREE.SphereGeometry(0.8, 8, 8);
            const eyeMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 }); // Red eyes
            const eyeLeft = new THREE.Mesh(eyeGeometry, eyeMaterial);
            eyeLeft.position.set(-1.5, 9, 2.5);
            head.add(eyeLeft);
            const eyeRight = new THREE.Mesh(eyeGeometry, eyeMaterial);
            eyeRight.position.set(1.5, 9, 2.5);
            head.add(eyeRight);

            // Legs (Thin Cylinders)
            const legGeometry = new THREE.CylinderGeometry(0.8, 0.8, 4, 8);
            const legMaterial = new THREE.MeshLambertMaterial({ color: 0x555555 });
            const legFrontLeft = new THREE.Mesh(legGeometry, legMaterial);
            legFrontLeft.position.set(-2, 0, -2);
            enemyGroup.add(legFrontLeft);
            const legFrontRight = new THREE.Mesh(legGeometry, legMaterial);
            legFrontRight.position.set(2, 0, -2);
            enemyGroup.add(legFrontRight);
            const legBackLeft = new THREE.Mesh(legGeometry, legMaterial);
            legBackLeft.position.set(-2, 0, 2);
            enemyGroup.add(legBackLeft);
            const legBackRight = new THREE.Mesh(legGeometry, legMaterial);
            legBackRight.position.set(2, 0, 2);
            enemyGroup.add(legBackRight);

            // Antennas (Thin Cylinders on head)
            const antennaGeometry = new THREE.CylinderGeometry(0.3, 0.3, 3, 8);
            const antennaMaterial = new THREE.MeshLambertMaterial({ color: 0xaaaaaa });
            const antennaLeft = new THREE.Mesh(antennaGeometry, antennaMaterial);
            antennaLeft.position.set(-1.5, 11, 0);
            antennaLeft.rotation.x = Math.PI / 4;
            enemyGroup.add(antennaLeft);
            const antennaRight = new THREE.Mesh(antennaGeometry, antennaMaterial);
            antennaRight.position.set(1.5, 11, 0);
            antennaRight.rotation.x = -Math.PI / 4;
            enemyGroup.add(antennaRight);


            enemyGroup.position.set(x, y, z);
            enemyGroup.userData.health = 50; // Enemies have less health
            enemyGroup.userData.isEnemy = true;
            return enemyGroup;
        }

        function createMovableBlock(color, x, y, z) {
            const geometry = new THREE.DodecahedronGeometry(6); // More interesting shape
            const material = new THREE.MeshLambertMaterial({ color: color });
            const block = new THREE.Mesh(geometry, material);
            block.position.set(x, y + 6, z); // Center on ground
            block.userData.isMovable = true;
            return block;
        }

        function createPressurePlate(color, x, y, z) {
            const geometry = new THREE.TorusGeometry(4, 1, 8, 32); // Flat torus shape
            const material = new THREE.MeshLambertMaterial({ color: color });
            const plate = new THREE.Mesh(geometry, material);
            plate.rotation.x = Math.PI / 2; // Lay flat
            plate.position.set(x, y + 0.5, z); // Slightly above ground
            plate.userData.isPressurePlate = true;
            return plate;
        }

        function createWall(color, x, y, z) {
            // A more stylized barrier with multiple boxes
            const wallGroup = new THREE.Group();
            const segmentGeometry = new THREE.BoxGeometry(5, 15, 5);
            const segmentMaterial = new THREE.MeshLambertMaterial({ color: color });

            for (let i = -2; i <= 2; i++) {
                const segment = new THREE.Mesh(segmentGeometry, segmentMaterial);
                segment.position.set(i * 6, 7.5, 0); // Spaced segments
                wallGroup.add(segment);
            }
            wallGroup.position.set(x, y, z);
            wallGroup.userData.isWall = true;
            return wallGroup;
        }

        function createPowerup(type, x, y, z) {
            let geometry;
            let material;
            let powerupMesh;

            switch (type) {
                case 'health':
                    geometry = new THREE.SphereGeometry(3, 16, 16);
                    material = new THREE.MeshLambertMaterial({ color: 0xff0000 }); // Red sphere for health
                    powerupMesh = new THREE.Mesh(geometry, material);
                    break;
                case 'attack':
                    geometry = new THREE.ConeGeometry(3, 6, 8);
                    material = new THREE.MeshLambertMaterial({ color: 0x00ffff }); // Cyan cone for attack boost
                    powerupMesh = new THREE.Mesh(geometry, material);
                    powerupMesh.rotation.x = Math.PI / 2; // Point it horizontally
                    break;
                case 'magic':
                    geometry = new THREE.TetrahedronGeometry(4); // Pyramid for magic
                    material = new THREE.MeshLambertMaterial({ color: 0x8A2BE2 }); // Purple for magic
                    powerupMesh = new THREE.Mesh(geometry, material);
                    break;
                case 'armor':
                    geometry = new THREE.BoxGeometry(5, 5, 5);
                    material = new THREE.MeshLambertMaterial({ color: 0x708090 }); // Slate gray for armor
                    powerupMesh = new THREE.Mesh(geometry, material);
                    break;
                default:
                    geometry = new THREE.BoxGeometry(4, 4, 4);
                    material = new THREE.MeshLambertMaterial({ color: 0xcccccc });
                    powerupMesh = new THREE.Mesh(geometry, material);
                    break;
            }

            powerupMesh.position.set(x, y + (geometry.parameters.height ? geometry.parameters.height / 2 : 2), z);
            powerupMesh.userData.isPowerup = true;
            powerupMesh.userData.type = type;
            return powerupMesh;
        }

        function createExplosionParticles(position, color) {
            const particleCount = 50;
            const positions = new Float32Array(particleCount * 3);
            const colors = new Float32Array(particleCount * 3);
            const sizes = new Float32Array(particleCount);

            const pColor = new THREE.Color(color);

            for (let i = 0; i < particleCount; i++) {
                // Random position within a small sphere
                positions[i * 3] = position.x + (Math.random() - 0.5) * 10;
                positions[i * 3 + 1] = position.y + (Math.random() - 0.5) * 10 + 5; // Slightly above ground
                positions[i * 3 + 2] = position.z + (Math.random() - 0.5) * 10;

                colors[i * 3] = pColor.r;
                colors[i * 3 + 1] = pColor.g;
                colors[i * 3 + 2] = pColor.b;

                sizes[i] = Math.random() * 2 + 1; // Random size
            }

            const geometry = new THREE.BufferGeometry();
            geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
            geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
            geometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1)); // Custom attribute for size

            const material = new THREE.PointsMaterial({
                size: 1, // Base size, actual size controlled by 'size' attribute
                vertexColors: true,
                transparent: true,
                opacity: 1,
                blending: THREE.AdditiveBlending,
                sizeAttenuation: true // Particles closer to camera appear larger
            });

            const particles = new THREE.Points(geometry, material);
            particles.userData.spawnTime = Date.now();
            particles.userData.lifespan = PARTICLE_LIFESPAN;
            particles.userData.velocity = [];
            for (let i = 0; i < particleCount; i++) {
                particles.userData.velocity.push(
                    new THREE.Vector3((Math.random() - 0.5) * 0.5, Math.random() * 0.5 + 0.1, (Math.random() - 0.5) * 0.5)
                );
            }
            scene.add(particles);
            activeExplosions.push(particles);
        }

        function createShieldHealingParticles(position) {
            const particleCount = 5; // Fewer particles for healing
            const positions = new Float32Array(particleCount * 3);
            const colors = new Float32Array(particleCount * 3);
            const sizes = new Float32Array(particleCount);

            const pColor = new THREE.Color(0x00ff00); // Green for healing

            for (let i = 0; i < particleCount; i++) {
                positions[i * 3] = position.x + (Math.random() - 0.5) * 5;
                positions[i * 3 + 1] = position.y + (Math.random() - 0.5) * 5 + 5;
                positions[i * 3 + 2] = position.z + (Math.random() - 0.5) * 5;

                colors[i * 3] = pColor.r;
                colors[i * 3 + 1] = pColor.g;
                colors[i * 3 + 2] = pColor.b;

                sizes[i] = Math.random() * 1 + 0.5;
            }

            const geometry = new THREE.BufferGeometry();
            geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
            geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
            geometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1));

            const material = new THREE.PointsMaterial({
                size: 1,
                vertexColors: true,
                transparent: true,
                opacity: 0.8,
                blending: THREE.AdditiveBlending,
                sizeAttenuation: true
            });

            const particles = new THREE.Points(geometry, material);
            particles.userData.spawnTime = Date.now();
            particles.userData.lifespan = PARTICLE_LIFESPAN;
            particles.userData.velocity = [];
            for (let i = 0; i < particleCount; i++) {
                particles.userData.velocity.push(
                    new THREE.Vector3(0, Math.random() * 0.2 + 0.05, 0) // Move mostly upwards
                );
            }
            scene.add(particles);
            activeShieldParticles.push(particles);
        }


        // --- Game Logic Functions ---

        function onWindowResize() {
            const canvas = document.getElementById('gameCanvas');
            const newWidth = canvas.clientWidth;
            const newHeight = canvas.clientHeight;

            console.log('Resizing - Canvas Width:', newWidth, 'Canvas Height:', newHeight);

            if (newWidth > 0 && newHeight > 0) {
                const aspect = newWidth / newHeight;
                const frustumSize = 120;

                camera.left = frustumSize * aspect / -2;
                camera.right = frustumSize * aspect / 2;
                camera.top = frustumSize / 2;
                camera.bottom = frustumSize / -2;
                camera.updateProjectionMatrix();

                renderer.setSize(newWidth, newHeight);
            }
        }

        function onKeyDown(event) {
            switch (event.key) {
                case 'w': keys.w = true; break; case 'a': keys.a = true; break;
                case 's': keys.s = true; break; case 'd': keys.d = true; break;
                case 'e': keys.e = true; break;

                case 'i': keys.i = true; break; case 'j': keys.j = true; break;
                case 'k': keys.k = true; break; case 'l': keys.l = true; break;
                case 'u': keys.u = true; break;
            }
        }

        function onKeyUp(event) {
            switch (event.key) {
                case 'w': keys.w = false; break; case 'a': keys.a = false; break;
                case 's': keys.s = false; break; case 'd': keys.d = false; break;
                case 'e': keys.e = false; break;

                case 'i': keys.i = false; break; case 'j': keys.j = false; break;
                case 'k': keys.k = false; break; case 'l': keys.l = false; break;
                case 'u': keys.u = false; break;
            }
        }

        function updatePlayerMovement(player, deltaX, deltaZ) {
            if (player.userData.incapacitated) return;

            const newX = player.position.x + deltaX;
            const newZ = player.position.z + deltaZ;

            const boundary = 70;
            if (Math.abs(newX) < boundary && Math.abs(newZ) < boundary) {
                player.position.x = newX;
                player.position.z = newZ;
            }
        }

        function handlePlayerActions() {
            const currentTime = Date.now();

            // Player 1 Action (E)
            if (keys.e && !player1Incapacitated) {
                if (player2Incapacitated && player1.position.distanceTo(player2.position) < 10) {
                    player2Incapacitated = false;
                    player2Health = Math.min(MAX_HEALTH, player2Health + MAX_HEALTH / 2); // Revive with half health
                    updateUI();
                    showMessage("Player 1 revived Player 2!");
                } else if (!player1.userData.isAttacking && currentTime - player1LastAttackTime > ATTACK_COOLDOWN) {
                    player1.userData.isAttacking = true;
                    player1.userData.attackStartTime = currentTime;
                    player1LastAttackTime = currentTime;
                }
            }

            // Player 2 Action (U)
            if (keys.u && !player2Incapacitated) {
                if (player1Incapacitated && player2.position.distanceTo(player1.position) < 10) {
                    player1Incapacitated = false;
                    player1Health = Math.min(MAX_HEALTH, player1Health + MAX_HEALTH / 2); // Revive with half health
                    updateUI();
                    showMessage("Player 2 revived Player 1!");
                } else if (!player2.userData.isAttacking && currentTime - player2LastAttackTime > ATTACK_COOLDOWN) {
                    player2.userData.isAttacking = true;
                    player2.userData.attackStartTime = currentTime;
                    player2LastAttackTime = currentTime;
                }
            }
        }

        function animatePlayerAttack(player) {
            if (!player.userData.isAttacking) return;

            const currentTime = Date.now();
            const elapsedTime = currentTime - player.userData.attackStartTime;
            const progress = Math.min(1, elapsedTime / ATTACK_DURATION);

            const startAngle = -Math.PI / 4;
            const endAngle = Math.PI * 3 / 4;

            if (progress < 0.5) {
                player.userData.armRight.rotation.z = startAngle + (endAngle - startAngle) * (progress * 2);
            } else {
                player.userData.armRight.rotation.z = endAngle - (endAngle - startAngle) * ((progress - 0.5) * 2);
            }

            if (progress >= 0.25 && progress <= 0.75 && !player.userData.damageDealtThisSwing) {
                let currentAttackRange = BASE_ATTACK_RANGE;
                if (isShieldActive) {
                    currentAttackRange += COOP_ATTACK_RANGE_BOOST;
                }
                if (player.userData.magicBoost > currentTime) { // Magic boost increases range
                    currentAttackRange *= 1.5;
                }

                enemies.forEach(enemy => {
                    if (enemy.userData.health > 0 && player.position.distanceTo(enemy.position) < currentAttackRange) {
                        // Check for combined attack
                        const otherPlayer = (player === player1) ? player2 : player1;
                        const otherPlayerLastAttackTime = (player === player1) ? player2LastAttackTime : player1LastAttackTime;

                        if (isShieldActive && otherPlayer.userData.isAttacking && (currentTime - otherPlayerLastAttackTime < COOP_ATTACK_WINDOW)) {
                            showMessage("Combined Attack! Monster Instantly Defeated!");
                            enemy.userData.health = 0; // Instant kill
                        } else {
                            showMessage("Monster Instantly Defeated!");
                            enemy.userData.health = 0; // Instant kill
                        }

                        if (enemy.userData.health <= 0) {
                            scene.remove(enemy);
                            createExplosionParticles(enemy.position, 0xffa500); // Orange explosion
                            if (player === player1) player1KOs++;
                            else player2KOs++;
                            totalScore += scorePerEnemy; // Add score
                            enemiesDefeatedInWave++;
                            checkWaveCompletion();
                        }
                        updateUI();
                    }
                });
                player.userData.damageDealtThisSwing = true;
            }

            if (progress >= 1) {
                player.userData.isAttacking = false;
                player.userData.armRight.rotation.z = startAngle;
                player.userData.damageDealtThisSwing = false;
            }
        }

        function updateEnemyLogic() {
            enemies.forEach(enemy => {
                if (enemy.userData.health <= 0) return;

                let targetPlayer = null;
                const distToP1 = enemy.position.distanceTo(player1.position);
                const distToP2 = enemy.position.distanceTo(player2.position);

                if (!player1Incapacitated && !player2Incapacitated) {
                    targetPlayer = (distToP1 < distToP2) ? player1 : player2;
                } else if (!player1Incapacitated) {
                    targetPlayer = player1;
                } else if (!player2Incapacitated) {
                    targetPlayer = player2;
                } else {
                    return;
                }

                if (targetPlayer) {
                    const direction = new THREE.Vector3().subVectors(targetPlayer.position, enemy.position).normalize();
                    enemy.position.addScaledVector(direction, ENEMY_SPEED);

                    if (enemy.position.distanceTo(targetPlayer.position) < 8) {
                        let damage = 0.5;
                        if (isShieldActive) {
                            damage *= 0.1; // Reduce damage significantly if shield is active
                        }
                        if (targetPlayer.userData.armorBoost > Date.now()) { // Armor boost reduces damage
                            damage *= 0.5;
                        }

                        if (targetPlayer === player1 && !player1Incapacitated) {
                            player1Health -= damage;
                            if (player1Health <= 0) {
                                player1Health = 0;
                                player1Incapacitated = true;
                                showMessage("Player 1 incapacitated! Player 2, revive them or reset!");
                            }
                        } else if (targetPlayer === player2 && !player2Incapacitated) {
                            player2Health -= damage;
                            if (player2Health <= 0) {
                                player2Health = 0;
                                player2Incapacitated = true;
                                showMessage("Player 2 incapacitated! Player 1, revive them or reset!");
                            }
                        }
                        updateUI();
                    }
                }
            });
        }

        function handleMovableBlock() {
            // Simplified collision check for pushing block
            const players = [player1, player2];
            players.forEach(player => {
                if (player.userData.incapacitated) return;
                const distToBlock = player.position.distanceTo(movableBlock.position);
                if (distToBlock < 10) {
                    const direction = new THREE.Vector3().subVectors(movableBlock.position, player.position).normalize();
                    movableBlock.position.addScaledVector(direction, PLAYER_SPEED * 0.5); // Push slower than player movement
                    // Basic boundary for block
                    const blockBoundary = 60;
                    movableBlock.position.x = Math.max(-blockBoundary, Math.min(blockBoundary, movableBlock.position.x));
                    movableBlock.position.z = Math.max(-blockBoundary, Math.min(blockBoundary, movableBlock.position.z));
                }
            });

            const distanceToPlate = movableBlock.position.distanceTo(pressurePlate.position);
            if (distanceToPlate < 5 && !pressurePlateActivated) {
                pressurePlateActivated = true;
                scene.remove(wallToOpen);
                showMessage("A path has opened!");
            } else if (distanceToPlate >= 5 && pressurePlateActivated) {
                // Optional: wall reappears if block leaves plate
                // if (!scene.children.includes(wallToOpen)) {
                //     scene.add(wallToOpen);
                // }
                // pressurePlateActivated = false;
            }
        }

        function checkPowerupCollisions() {
            const currentTime = Date.now();
            const players = [player1, player2];

            for (let i = powerups.length - 1; i >= 0; i--) {
                const powerup = powerups[i];
                powerup.rotation.y += 0.02;

                players.forEach(player => {
                    if (player.position.distanceTo(powerup.position) < 5) {
                        switch (powerup.userData.type) {
                            case 'health':
                                if (player === player1) player1Health = Math.min(MAX_HEALTH, player1Health + 30);
                                else player2Health = Math.min(MAX_HEALTH, player2Health + 30);
                                showMessage(`${player === player1 ? 'Player 1' : 'Player 2'} picked up Health!`);
                                break;
                            case 'attack':
                                player.userData.attackBoost = currentTime + POWERUP_DURATION;
                                showMessage(`${player === player1 ? 'Player 1' : 'Player 2'} picked up Attack Boost!`);
                                break;
                            case 'magic':
                                player.userData.magicBoost = currentTime + POWERUP_DURATION;
                                showMessage(`${player === player1 ? 'Player 1' : 'Player 2'} picked up Magic Boost!`);
                                break;
                            case 'armor':
                                player.userData.armorBoost = currentTime + POWERUP_DURATION;
                                showMessage(`${player === player1 ? 'Player 1' : 'Player 2'} picked up Armor Boost!`);
                                break;
                        }
                        scene.remove(powerup);
                        powerups.splice(i, 1);
                        updateUI();
                    }
                });
            }

            // Decay boosts
            players.forEach(player => {
                if (player.userData.attackBoost > 0 && currentTime > player.userData.attackBoost) {
                    player.userData.attackBoost = 0;
                    showMessage(`${player === player1 ? 'Player 1' : 'Player 2'}'s Attack Boost expired!`);
                }
                if (player.userData.magicBoost > 0 && currentTime > player.userData.magicBoost) {
                    player.userData.magicBoost = 0;
                    showMessage(`${player === player1 ? 'Player 1' : 'Player 2'}'s Magic Boost expired!`);
                }
                if (player.userData.armorBoost > 0 && currentTime > player.userData.armorBoost) {
                    player.userData.armorBoost = 0;
                    showMessage(`${player === player1 ? 'Player 1' : 'Player 2'}'s Armor Boost expired!`);
                }
            });
        }

        function updateCoopShield() {
            const distanceBetweenPlayers = player1.position.distanceTo(player2.position);
            const wasShieldActive = isShieldActive;

            if (distanceBetweenPlayers < SHIELD_RANGE && !player1Incapacitated && !player2Incapacitated) {
                isShieldActive = true;
                shieldVisual.position.copy(player1.position).lerp(player2.position, 0.5);
                shieldVisual.visible = true;

                // Continuously spawn healing particles
                if (Math.random() < 0.1) { // Spawn rate
                    createShieldHealingParticles(player1.position);
                    createShieldHealingParticles(player2.position);
                }

                if (!wasShieldActive) {
                    showMessage("Co-op Shield Activated!");
                }
            } else {
                isShieldActive = false;
                shieldVisual.visible = false;
                if (wasShieldActive) {
                    showMessage("Co-op Shield Deactivated.");
                }
            }
        }

        function updateParticleSystems() {
            const currentTime = Date.now();

            // Update explosion particles
            for (let i = activeExplosions.length - 1; i >= 0; i--) {
                const particles = activeExplosions[i];
                const elapsedTime = currentTime - particles.userData.spawnTime;
                const progress = elapsedTime / particles.userData.lifespan;

                if (progress >= 1) {
                    scene.remove(particles);
                    activeExplosions.splice(i, 1);
                    continue;
                }

                // Update particle positions and opacity
                const positions = particles.geometry.attributes.position.array;
                const sizes = particles.geometry.attributes.size.array;
                const velocities = particles.userData.velocity;
                const material = particles.material;

                material.opacity = 1 - progress; // Fade out

                for (let j = 0; j < positions.length / 3; j++) {
                    positions[j * 3] += velocities[j].x;
                    positions[j * 3 + 1] += velocities[j].y;
                    positions[j * 3 + 2] += velocities[j].z;
                    // Make particles shrink
                    sizes[j] = (1 - progress) * (particles.userData.initialSizes ? particles.userData.initialSizes[j] : sizes[j]);
                }
                particles.geometry.attributes.position.needsUpdate = true;
                particles.geometry.attributes.size.needsUpdate = true;
            }

            // Update shield healing particles
            for (let i = activeShieldParticles.length - 1; i >= 0; i--) {
                const particles = activeShieldParticles[i];
                const elapsedTime = currentTime - particles.userData.spawnTime;
                const progress = elapsedTime / particles.userData.lifespan;

                if (progress >= 1) {
                    scene.remove(particles);
                    activeShieldParticles.splice(i, 1);
                    continue;
                }

                const positions = particles.geometry.attributes.position.array;
                const velocities = particles.userData.velocity;
                const material = particles.material;

                material.opacity = 1 - progress;

                for (let j = 0; j < positions.length / 3; j++) {
                    positions[j * 3] += velocities[j].x;
                    positions[j * 3 + 1] += velocities[j].y;
                    positions[j * 3 + 2] += velocities[j].z;
                }
                particles.geometry.attributes.position.needsUpdate = true;
            }
        }


        function updateUI() {
            player1LifeSpan.textContent = Math.max(0, Math.floor(player1Health));
            player2LifeSpan.textContent = Math.max(0, Math.floor(player2Health));
            // For now, let's just use player1KOs as total score
            document.getElementById('player1KOs').textContent = totalScore;
            document.getElementById('player2KOs').textContent = `Wave: ${currentWave}`;


            player1HealthBar.style.width = `${(player1Health / MAX_HEALTH) * 100}%`;
            player2HealthBar.style.width = `${(player2Health / MAX_HEALTH) * 100}%`;

            player1.visible = !player1Incapacitated;
            player2.visible = !player2Incapacitated;

            if (player1Incapacitated && player2Incapacitated) {
                showMessage("Game Over! Both players incapacitated. Press Reset to restart.");
                // Prevent further game logic until reset
                return;
            }
        }

        function resetGame() {
            player1Health = MAX_HEALTH;
            player2Health = MAX_HEALTH;
            player1KOs = 0;
            player2KOs = 0;
            totalScore = 0; // Reset total score
            currentWave = 1; // Reset wave
            player1Incapacitated = false;
            player2Incapacitated = false;
            pressurePlateActivated = false;
            isShieldActive = false;

            player1.position.set(-20, 0, 0);
            player2.position.set(20, 0, 0);
            player1.userData.isAttacking = false;
            player2.userData.isAttacking = false;
            player1.userData.attackBoost = 0;
            player2.userData.attackBoost = 0;
            player1.userData.magicBoost = 0;
            player2.userData.magicBoost = 0;
            player1.userData.armorBoost = 0;
            player2.userData.armorBoost = 0;
            player1.userData.armRight.rotation.z = -Math.PI / 4;
            player2.userData.armRight.rotation.z = -Math.PI / 4;

            enemies.forEach(enemy => scene.remove(enemy));
            enemies = [];
            powerups.forEach(powerup => scene.remove(powerup));
            powerups = [];
            activeExplosions.forEach(p => scene.remove(p));
            activeExplosions = [];
            activeShieldParticles.forEach(p => scene.remove(p));
            activeShieldParticles = [];

            // Remove old puzzle elements from scene if they exist
            if (movableBlock && movableBlock.parent) scene.remove(movableBlock);
            if (pressurePlate && pressurePlate.parent) scene.remove(pressurePlate);
            if (wallToOpen && wallToOpen.parent) scene.remove(wallToOpen);

            // Re-create and add initial puzzle elements
            movableBlock = createMovableBlock(0xffff00, -10, 0, -10);
            scene.add(movableBlock);
            pressurePlate = createPressurePlate(0x888888, 10, 0, -10);
            scene.add(pressurePlate);
            wallToOpen = createWall(0x663300, 10, 0, -20);
            scene.add(wallToOpen);
            pressurePlateActivated = false; // Ensure wall is reset to its original state

            powerups.push(createPowerup('health', -40, 0, 40));
            powerups.push(createPowerup('attack', 40, 0, 40));
            powerups.push(createPowerup('magic', -40, 0, -40));
            powerups.push(createPowerup('armor', 40, 0, -40));
            powerups.push(createPowerup('health', 0, 0, 0));
            powerups.forEach(powerup => scene.add(powerup));

            shieldVisual.visible = false;

            spawnEnemiesForWave(currentWave); // Start the first wave again
            updateUI();
        }

        // Animation loop
        function animate() {
            requestAnimationFrame(animate);

            // Only update game logic if not game over
            if (!(player1Incapacitated && player2Incapacitated)) {
                if (keys.w) updatePlayerMovement(player1, 0, -PLAYER_SPEED);
                if (keys.s) updatePlayerMovement(player1, 0, PLAYER_SPEED);
                if (keys.a) updatePlayerMovement(player1, -PLAYER_SPEED, 0);
                if (keys.d) updatePlayerMovement(player1, PLAYER_SPEED, 0);

                if (keys.i) updatePlayerMovement(player2, 0, -PLAYER_SPEED);
                if (keys.k) updatePlayerMovement(player2, 0, PLAYER_SPEED);
                if (keys.j) updatePlayerMovement(player2, -PLAYER_SPEED, 0);
                if (keys.l) updatePlayerMovement(player2, PLAYER_SPEED);

                handlePlayerActions();
                animatePlayerAttack(player1);
                animatePlayerAttack(player2);
                updateEnemyLogic();
                handleMovableBlock();
                checkPowerupCollisions();
                updateCoopShield();
            }
            updateParticleSystems(); // Always update particles, even if game over
            updateUI();

            renderer.render(scene, camera);
        }
    </script>
</body>
</html>