-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharcadeEntity.js
More file actions
1995 lines (1656 loc) · 81.7 KB
/
Copy patharcadeEntity.js
File metadata and controls
1995 lines (1656 loc) · 81.7 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
/**
* Arcade Cabinet Entity for AI Alchemist's Lair
* Decorative arcade cabinet with interactive game selection functionality
*/
import { Entity } from './entity.js';
import { debug } from './utils.js';
import { getAssetPath } from './pathResolver.js';
class ArcadeEntity extends Entity {
/**
* Creates a new arcade cabinet entity
* @param {number} x - Grid X position
* @param {number} y - Grid Y position
* @param {string} assetKey - Key for the asset to use ('arcade1', etc)
* @param {object} options - Additional options
*/
constructor(x, y, assetKey = 'Arcade_1', options = {}) {
// Create an arcade with standard settings as a static entity
super(x, y, 1.0, 1.0, {
isStatic: true,
zHeight: 1.8,
collidable: true
});
// Store game reference if provided
this.game = options.game || null;
// Arcade-specific properties
this.assetKey = assetKey;
this.hasLoaded = false;
this.asset = null;
this.isInteractive = true;
this.interactionRadius = 4;
this.arcadeId = options.arcadeId || 'arcade-' + Math.floor(Math.random() * 10000);
// Visual properties
this.glowColor = '#00FFFF';
this.glowIntensity = 5;
this.maxGlowIntensity = 15;
this.glowSpeed = 0.1;
this.glowDirection = 1;
this.scaleX = .77;
this.scaleY = .77;
this.groundingFactor = 0.35; // Percentage of height that sits "in" the ground
// Apply positional offset like other decorative entities
// This corrects grid alignment based on patterns from other entities
this.x += -1.0;
this.y += -0.5;
// Interaction properties
this.isNearPlayer = false;
this.isInteracting = false;
this.interactionPromptAlpha = 0;
this.wasEnterPressed = false; // Track previous Enter key state for edge detection
// Animation properties
this.animationFrame = 0;
this.animationSpeed = 0.05;
this.screenGlow = 0;
this.screenGlowDirection = 1;
// Game selection properties
this.gameSelectVisible = false;
this.games = [
{
title: 'Neon Requiem',
description: 'Top-Down Corridor Shooter',
url: 'https://aialchemistart.github.io/NeonRequiem/',
imagePath: 'assets/Games/Game_1.png', // Updated casing from games to Games
image: null,
alternativeImagePaths: ['assets/Games/Game_1.png', 'assets/games/Game_1.png', 'assets/decor/Game_1.png']
},
{
title: 'Synth-Pocalypse Now!',
description: 'Typing/Bullet Hell',
url: 'https://aialchemistart.github.io/Synthpocalypse-Now-/',
imagePath: 'assets/Games/Game_2.png', // Updated casing from games to Games
image: null,
alternativeImagePaths: ['assets/Games/Game_2.png', 'assets/games/Game_2.png', 'assets/decor/Game_2.png']
},
{
title: 'Pixel Survivor',
description: 'Top-Down Survival Shooter',
url: 'https://pixel-survival.replit.app/',
imagePath: 'assets/Games/Game_3.png', // Updated casing from games to Games
image: null,
alternativeImagePaths: ['assets/Games/Game_3.png', 'assets/games/Game_3.png', 'assets/decor/Game_3.png']
},
{
title: 'Neon Swarm',
description: 'Top-Down Wave Shooter',
url: 'https://aialchemistart.github.io/SpaceInvaders/',
imagePath: 'assets/Games/Game_4.png', // Updated casing from games to Games
image: null,
alternativeImagePaths: ['assets/Games/Game_4.png', 'assets/games/Game_4.png', 'assets/decor/Game_4.png']
},
{
title: 'Pixel Farmer\'s Quest',
description: 'Farming Action/Survival',
url: 'https://pixel-harvest.replit.app/',
imagePath: 'assets/Games/Game_5.png', // Updated casing from games to Games
image: null,
alternativeImagePaths: ['assets/Games/Game_5.png', 'assets/games/Game_5.png', 'assets/decor/Game_5.png']
}
];
this.selectedGameIndex = 0;
this.gameImagesLoaded = false;
// Key state tracking
this.wasUpPressed = false;
this.wasDownPressed = false;
this.wasEscapePressed = false;
// Test loading immediately
this.testImageLoad();
// Flag for direct key listeners
this.hasKeyListeners = false;
this.menuKeyListeners = null;
// Sound effects
this.activateSound = null;
this.selectSound = null;
this.launchSound = null;
// Load sound effects
this.loadSoundEffects();
// Load game preview images
this.loadGameImages();
}
/**
* Load game preview images
*/
loadGameImages() {
console.log("🎮 Starting to load game images");
// Load images for each game
this.games.forEach((game, index) => {
if (game.imagePath) {
console.log(`🎮 Attempting to load game image: ${game.imagePath}`);
const img = new Image();
// Set up load event handler before setting src
img.onload = () => {
console.log(`🎮 Successfully loaded game image: ${game.imagePath}`);
game.image = img;
// Check if all images are loaded
if (this.games.every(g => g.image)) {
this.gameImagesLoaded = true;
console.log('🎮 All game images loaded successfully!');
}
};
// Set up error handler
img.onerror = () => {
console.error(`🎮 Failed to load game image: ${game.imagePath}`);
// Try alternative paths if available
if (game.alternativeImagePaths && game.alternativeImagePaths.length > 0) {
console.log(`🎮 Trying alternative paths for ${game.title}`);
this.tryAlternativeGameImagePaths(game, index);
} else {
// No alternatives, create fallback image
console.log(`🎮 No alternative paths for ${game.title}, creating fallback`);
this.createGameImage(game, index);
}
};
// Attempt to load the image with correct path for deployment
const resolvedPath = getAssetPath(game.imagePath);
console.log(`🎮 Resolved image path: ${resolvedPath} (original: ${game.imagePath})`);
img.src = resolvedPath;
} else {
console.warn(`🎮 No image path specified for game ${index}, creating fallback`);
this.createGameImage(game, index);
}
});
}
/**
* Create a game image
* @param {object} game - Game object to create image for
* @param {number} index - Index of the game
*/
createGameImage(game, index) {
console.log(`🎮 Creating fallback game image for ${game.title}`);
// Create a canvas element to draw our game image
const canvas = document.createElement('canvas');
canvas.width = 400;
canvas.height = 225; // 16:9 aspect ratio
const ctx = canvas.getContext('2d');
// Define color schemes for different games
const colorThemes = [
{ // Neon Requiem - Cyberpunk purple/blue
bg: 'linear-gradient(135deg, #1a0038 0%, #3a0068 100%)',
accent: '#00FFFF',
secondary: '#FF00FF'
},
{ // Synth-Pocalypse - Retro purple/pink
bg: 'linear-gradient(135deg, #2d004c 0%, #5d0066 100%)',
accent: '#FF00DD',
secondary: '#FFDD00'
},
{ // Pixel Survivor - Green/brown survival theme
bg: 'linear-gradient(135deg, #002200 0%, #184018 100%)',
accent: '#00FF66',
secondary: '#FFAA00'
},
{ // Neon Swarm - Space themed blue/purple
bg: 'linear-gradient(135deg, #000033 0%, #000066 100%)',
accent: '#00FFFF',
secondary: '#FF5500'
},
{ // Pixel Farmer - Earthy green/brown
bg: 'linear-gradient(135deg, #1a3300 0%, #336600 100%)',
accent: '#AAFF00',
secondary: '#FFAA00'
}
];
// Select theme based on index
const theme = colorThemes[index % colorThemes.length];
// Fill background with gradient
const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
gradient.addColorStop(0, theme.bg.split(', ')[1].split(' ')[0]);
gradient.addColorStop(1, theme.bg.split(', ')[2].split(' ')[0]);
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw decorative elements based on theme
// Grid lines
ctx.strokeStyle = theme.accent;
ctx.lineWidth = 1;
ctx.globalAlpha = 0.2;
// Horizontal grid lines
for (let y = 20; y < canvas.height; y += 40) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(canvas.width, y);
ctx.stroke();
}
// Vertical grid lines
for (let x = 20; x < canvas.width; x += 40) {
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
ctx.stroke();
}
// Reset alpha
ctx.globalAlpha = 1.0;
// Draw border
ctx.strokeStyle = theme.accent;
ctx.lineWidth = 4;
ctx.strokeRect(8, 8, canvas.width - 16, canvas.height - 16);
// Draw inner border
ctx.strokeStyle = theme.secondary;
ctx.lineWidth = 2;
ctx.strokeRect(16, 16, canvas.width - 32, canvas.height - 32);
// Draw game title with shadow
ctx.font = 'bold 36px "Courier New", monospace';
ctx.shadowColor = theme.accent;
ctx.shadowBlur = 15;
ctx.fillStyle = '#FFFFFF';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
// Draw title that fits within the canvas width
const title = game.title;
const maxWidth = canvas.width - 40;
// Measure text and scale down if needed
let fontSize = 36;
ctx.font = `bold ${fontSize}px "Courier New", monospace`;
while (ctx.measureText(title).width > maxWidth && fontSize > 18) {
fontSize -= 2;
ctx.font = `bold ${fontSize}px "Courier New", monospace`;
}
// Draw title
ctx.fillText(title, canvas.width / 2, canvas.height / 2 - 20);
// Draw game type with smaller font
ctx.shadowBlur = 5;
ctx.font = '18px "Arial", sans-serif';
ctx.fillStyle = theme.accent;
ctx.fillText(game.description, canvas.width / 2, canvas.height / 2 + 30);
// Reset shadow
ctx.shadowBlur = 0;
// Create an image from the canvas
const img = new Image();
img.src = canvas.toDataURL('image/png');
// Store in game object when loaded
img.onload = () => {
console.log(`🎮 Successfully created fallback game image for ${game.title}`);
game.image = img;
// Check if all images are loaded
if (this.games.every(g => g.image)) {
this.gameImagesLoaded = true;
console.log('🎮 All game images have been created!');
}
};
}
/**
* Create a fallback image for games without image assets
* @param {object} game - Game object
*/
createFallbackImage(game) {
console.log(`🎮 Creating fallback image for ${game.title}`);
// Create a canvas to generate an image
const canvas = document.createElement('canvas');
canvas.width = 300;
canvas.height = 200;
const ctx = canvas.getContext('2d');
// Fill background
ctx.fillStyle = '#000033';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Add border
ctx.strokeStyle = '#00FFFF';
ctx.lineWidth = 3;
ctx.strokeRect(5, 5, canvas.width - 10, canvas.height - 10);
// Add title
ctx.font = 'bold 24px "Courier New", monospace';
ctx.fillStyle = '#FFFFFF';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(game.title, canvas.width / 2, canvas.height / 2);
// Convert to an image
const img = new Image();
img.src = canvas.toDataURL();
game.image = img;
}
/**
* Test direct image loading outside the normal flow
*/
testImageLoad() {
debug(`🧪 ArcadeEntity: Testing direct image load with multiple paths...`);
// Try multiple different path formats
const pathsToTry = [
window.location.origin + '/assets/decor/Arcade_1.png',
'assets/decor/Arcade_1.png',
'./assets/decor/Arcade_1.png',
'/assets/decor/Arcade_1.png',
window.location.origin + '/assets/decor/Arcade%201.png',
window.location.origin + '/assets/decor/arcade-cabinet.png',
'assets/decor/arcade-cabinet.png'
];
// Try each path one after another
let pathIndex = 0;
const tryNextPath = () => {
if (pathIndex >= pathsToTry.length) {
debug('❌ All test paths failed, giving up');
return;
}
const path = pathsToTry[pathIndex];
debug(`🔄 Testing path ${pathIndex+1}/${pathsToTry.length}: ${path}`);
const testImg = new Image();
testImg.onload = () => {
debug(`✅ TEST SUCCESS: Loaded from ${path} (${testImg.width}x${testImg.height})`);
// If our test image loaded but the main asset didn't, use this one
if (!this.hasLoaded || !this.asset) {
debug(`🔄 Using test image as main asset since main asset failed to load`);
this.asset = testImg;
this.hasLoaded = true;
// Also store in asset loader
if (window.assetLoader) {
window.assetLoader.assets[this.assetKey] = testImg;
}
}
};
testImg.onerror = () => {
debug(`❌ TEST FAILED: Could not load from ${path}`);
pathIndex++;
setTimeout(tryNextPath, 100);
};
testImg.src = path;
};
// Start trying paths
tryNextPath();
}
/**
* Load the arcade cabinet asset
* @param {Function} assetLoader - Function to load assets
*/
loadAsset(assetLoader) {
debug(`ArcadeEntity: Attempting to load asset for ${this.assetKey}`);
// First check if asset is already loaded with this key
const existingAsset = assetLoader.getAsset(this.assetKey);
if (existingAsset) {
debug(`ArcadeEntity: Found existing asset for ${this.assetKey}`);
this.asset = existingAsset;
this.hasLoaded = true;
return;
}
// Directly attempt to load the image
debug(`ArcadeEntity: Asset not found in cache, attempting direct load`);
this.directLoadArcadeImage();
}
/**
* Directly load the arcade cabinet image without relying on asset loader
*/
directLoadArcadeImage() {
debug(`ArcadeEntity: Directly loading arcade image for key ${this.assetKey}`);
// Create a new image directly
const img = new Image();
img.onload = () => {
debug(`ArcadeEntity: SUCCESSFULLY loaded arcade image directly (${img.width}x${img.height})`);
this.asset = img;
this.hasLoaded = true;
// Store in asset loader for potential reuse
if (window.assetLoader) {
window.assetLoader.assets[this.assetKey] = img;
}
};
img.onerror = (err) => {
debug(`ArcadeEntity: FAILED to load arcade image directly from exact path, error: ${err}`);
this.tryAlternativePaths();
};
// Force to use the EXACT path that matches the file in the directory with GitHub Pages handling
// This is known to exist from the dir command
const exactPath = 'assets/decor/Arcade_1.png';
const resolvedPath = getAssetPath(exactPath);
debug(`ArcadeEntity: Attempting to load from resolved path: ${resolvedPath} (original: ${exactPath})`);
img.src = resolvedPath;
}
/**
* Try to load the arcade image from alternative paths
*/
tryAlternativePaths() {
debug(`ArcadeEntity: Trying alternative paths for image`);
// Try several alternative paths - we now know the exact filename is "Arcade 1.png"
// Generate both regular and GitHub Pages-resolved paths
const basePaths = [
`assets/decor/Arcade_1.png`, // Exact filename with space
`./assets/decor/Arcade_1.png`, // With leading ./ and space
`assets/decor/Arcade%201.png`, // URL encoded space
`assets/decor/Arcade-1.png`, // Hyphen instead of space
`assets/decor/Arcade1.png`, // No space
`assets/decor/arcade-cabinet.png`, // Generic name
`assets/decor/arcade.png` // Simple name
];
// Create alternative paths array with both regular and GitHub Pages versions
const alternativePaths = [];
basePaths.forEach(path => {
alternativePaths.push(path); // Regular path
alternativePaths.push(getAssetPath(path)); // GitHub Pages path
});
let pathIndex = 0;
const tryNextPath = () => {
if (pathIndex >= alternativePaths.length) {
debug(`ArcadeEntity: All alternative paths failed, creating fallback`);
this.createFallbackAsset();
return;
}
const path = alternativePaths[pathIndex];
debug(`ArcadeEntity: Trying alternative path (${pathIndex+1}/${alternativePaths.length}): ${path}`);
const altImg = new Image();
altImg.onload = () => {
debug(`ArcadeEntity: Successfully loaded from alternative path: ${path}`);
this.asset = altImg;
this.hasLoaded = true;
// Store in asset loader for potential reuse
if (window.assetLoader) {
window.assetLoader.assets[this.assetKey] = altImg;
}
};
altImg.onerror = () => {
debug(`ArcadeEntity: Failed to load from alternative path: ${path}`);
pathIndex++;
// Try the next path after a short delay
setTimeout(tryNextPath, 100);
};
// Note: No need to call getAssetPath again here, as we've already included
// both regular and GitHub Pages paths in the alternativePaths array
altImg.src = path;
};
// Start trying alternative paths
tryNextPath();
}
/**
* Create a fallback asset when loading fails
*/
createFallbackAsset() {
debug(`ArcadeEntity: Creating fallback asset`);
// Create a canvas to render the fallback asset
const canvas = document.createElement('canvas');
canvas.width = 100;
canvas.height = 160;
const ctx = canvas.getContext('2d');
// -- CABINET BODY --
// Draw a basic arcade cabinet shape (dark metal frame)
ctx.fillStyle = '#222222';
ctx.fillRect(15, 20, 70, 140); // Main cabinet body
// Cabinet top
ctx.fillStyle = '#333333';
ctx.fillRect(10, 10, 80, 15);
// -- SCREEN --
// Screen background
ctx.fillStyle = '#000000';
ctx.fillRect(25, 30, 50, 40);
// Screen content (game screen)
ctx.fillStyle = '#000066';
ctx.fillRect(27, 32, 46, 36);
// Add simple game graphics on screen
// Enemy characters
ctx.fillStyle = '#FF0000';
ctx.fillRect(30, 35, 8, 8);
ctx.fillRect(45, 35, 8, 8);
ctx.fillRect(60, 35, 8, 8);
// Player character
ctx.fillStyle = '#00FF00';
ctx.fillRect(45, 55, 10, 10);
// -- CONTROLS --
// Control panel
ctx.fillStyle = '#444444';
ctx.fillRect(25, 80, 50, 30);
// Joystick
ctx.fillStyle = '#000000';
ctx.beginPath();
ctx.arc(40, 95, 8, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = '#888888';
ctx.beginPath();
ctx.arc(40, 95, 6, 0, Math.PI * 2);
ctx.fill();
// Buttons
const buttonColors = ['#FF0000', '#FFFF00', '#00FF00', '#0000FF'];
for (let i = 0; i < 4; i++) {
ctx.fillStyle = buttonColors[i];
ctx.beginPath();
ctx.arc(60, 85 + i * 7, 5, 0, Math.PI * 2);
ctx.fill();
}
// -- DECORATIVE ELEMENTS --
// Coin slot
ctx.fillStyle = '#666666';
ctx.fillRect(40, 120, 20, 5);
// Marquee at top
ctx.fillStyle = '#9900FF';
ctx.fillRect(20, 15, 60, 10);
// Text on marquee
ctx.fillStyle = '#FFFFFF';
ctx.font = 'bold 8px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('ARCADE', 50, 23);
// Add neon glow effect
ctx.shadowColor = '#00FFFF';
ctx.shadowBlur = 10;
ctx.strokeStyle = '#00FFFF';
ctx.lineWidth = 2;
// Glow outline
ctx.beginPath();
ctx.rect(15, 20, 70, 140);
ctx.stroke();
// Screen glow outline
ctx.beginPath();
ctx.rect(25, 30, 50, 40);
ctx.stroke();
// Convert to an image
const img = new Image();
img.onload = () => {
debug(`ArcadeEntity: Fallback asset created successfully (${img.width}x${img.height})`);
this.asset = img;
this.hasLoaded = true;
// Also store in asset loader for potential reuse
if (window.assetLoader) {
window.assetLoader.assets[this.assetKey] = img;
}
};
img.src = canvas.toDataURL();
}
/**
* Check if player is near arcade cabinet
* @param {Entity} player - Player entity
* @returns {boolean} - Whether player is within interaction radius
*/
isPlayerNearby(player) {
if (!player) {
debug(`ArcadeEntity: No player provided to isPlayerNearby check`);
return false;
}
// Calculate distance between player and arcade cabinet
const dx = player.x - this.x;
const dy = player.y - this.y;
const distance = Math.sqrt(dx * dx + dy * dy);
// Check if player is within interaction radius
const isNear = distance <= this.interactionRadius;
// Log details about the proximity check
if (isNear) {
debug(`ArcadeEntity: Player is nearby (distance: ${distance.toFixed(2)})`);
}
// Debug player distance occasionally
if (Math.random() < 0.03) {
console.log(`🎮 Player distance: ${distance.toFixed(2)}, Interaction radius: ${this.interactionRadius}`);
}
return isNear;
}
/**
* Update the arcade cabinet state
* @param {number} deltaTime - Time since last update in seconds
* @param {object} input - Input state
* @param {Entity} player - Player entity
*/
update(deltaTime, player) {
// Check if player is near the arcade cabinet
if (player) {
const isNearPlayer = this.isPlayerNearby(player);
// Only trigger state change effects if proximity changed
if (isNearPlayer !== this.isNearPlayer) {
debug(`ArcadeEntity: Player proximity changed to ${isNearPlayer ? 'NEAR' : 'FAR'}`);
// Trigger a pulse effect and sound when proximity changes
if (isNearPlayer) {
this.pulseGlow();
this.playProximitySound();
}
}
// Update proximity state
this.isNearPlayer = isNearPlayer;
}
// Handle input when player is nearby and not already interacting
if (this.isNearPlayer && !this.gameSelectVisible) {
// Check for Enter key press - we check directly from the input system
const isEnterPressed = window.input && window.input.keys && window.input.keys['Enter'];
if (isEnterPressed && !this.wasEnterPressed) {
debug(`ArcadeEntity: Enter key pressed, starting interaction`);
this.startInteraction();
}
// Update previous key state
this.wasEnterPressed = isEnterPressed;
}
// Update glow effects
if (this.isNearPlayer) {
// Enhanced pulsing glow when player is nearby
this.glowIntensity += this.glowDirection * this.glowSpeed;
if (this.glowIntensity > this.maxGlowIntensity) {
this.glowIntensity = this.maxGlowIntensity;
this.glowDirection = -1;
} else if (this.glowIntensity < this.maxGlowIntensity / 2) {
this.glowIntensity = this.maxGlowIntensity / 2;
this.glowDirection = 1;
}
// Fade in interaction prompt - faster fade in for better visibility
this.interactionPromptAlpha = Math.min(1, this.interactionPromptAlpha + deltaTime * 4);
} else {
// Always maintain a base pulsing glow when player is away
// Pulse between 20-40% of max glow intensity when not in proximity
this.glowIntensity += this.glowDirection * (this.glowSpeed * 0.5);
if (this.glowIntensity > this.maxGlowIntensity * 0.4) {
this.glowIntensity = this.maxGlowIntensity * 0.4;
this.glowDirection = -1;
} else if (this.glowIntensity < this.maxGlowIntensity * 0.2) {
this.glowIntensity = this.maxGlowIntensity * 0.2;
this.glowDirection = 1;
}
// Fade out interaction prompt
this.interactionPromptAlpha = Math.max(0, this.interactionPromptAlpha - deltaTime * 4);
// If we're showing the game selection and player walks away, close it
if (this.gameSelectVisible) {
debug(`ArcadeEntity: Player walked away, closing game selection`);
this.hideGameSelection();
}
}
// Update screen animation
this.animationFrame += this.animationSpeed;
if (this.animationFrame > 1) {
this.animationFrame -= 1;
}
// Update screen glow
this.screenGlow += this.screenGlowDirection * deltaTime * 0.5;
if (this.screenGlow > 1) {
this.screenGlow = 1;
this.screenGlowDirection = -1;
} else if (this.screenGlow < 0.5) {
this.screenGlow = 0.5;
this.screenGlowDirection = 1;
}
// Occasionally log input state for debugging
if (Math.random() < 0.02 && this.isNearPlayer) {
console.log("======= ARCADE INPUT DEBUG =======");
console.log(`Player nearby: ${this.isNearPlayer}`);
console.log(`Game select visible: ${this.gameSelectVisible}`);
console.log(`Input object exists: ${!!window.input}`);
if (window.input) {
console.log(`Input keys object exists: ${!!window.input.keys}`);
if (window.input.keys) {
console.log(`Enter key state: ${window.input.keys['Enter'] ? 'PRESSED' : 'not pressed'}`);
console.log(`Space key state: ${window.input.keys[' '] ? 'PRESSED' : 'not pressed'}`);
// List all pressed keys for debugging
const pressedKeys = [];
for (const key in window.input.keys) {
if (window.input.keys[key]) {
pressedKeys.push(key);
}
}
console.log(`All pressed keys: ${pressedKeys.join(', ') || 'none'}`);
}
}
console.log("==================================");
}
// Check for Enter key to start interaction
let isEnterPressed = false;
// First try window.input.keys approach
if (window.input && window.input.keys) {
isEnterPressed = window.input.keys['Enter'] || window.input.keys[' '];
// Only detect a new press (not holding) to start interaction
if (isEnterPressed && !this.wasEnterPressed) {
console.log("🎮 ENTER KEY NEWLY PRESSED!");
if (this.isNearPlayer && !this.gameSelectVisible) {
console.log("🎮 STARTING INTERACTION!");
this.startInteraction();
}
}
// Update Enter key state for next frame
this.wasEnterPressed = isEnterPressed;
}
// Setup and handle menu-specific direct keyboard controls when game selection is visible
if (this.gameSelectVisible && !this.menuKeyListeners) {
// Set up direct key listeners specifically for the menu
console.log("🎮 Setting up direct menu key listeners");
// Create listeners for menu navigation
this.menuKeyListeners = {
keydown: (e) => {
console.log(`🎮 Menu keydown detected: ${e.key}`);
// Always prevent default for ANY key when menu is open
// This ensures no input gets to the game while in menu
e.preventDefault();
e.stopPropagation();
if (e.key === 'ArrowUp' || e.key === 'w' || e.key === 'W') {
console.log("🎮 UP key detected for menu");
this.selectedGameIndex = (this.selectedGameIndex - 1 + this.games.length) % this.games.length;
this.playSelectSound();
// Force redraw
this.drawGameSelectionInterface(null);
}
else if (e.key === 'ArrowDown' || e.key === 's' || e.key === 'S') {
console.log("🎮 DOWN key detected for menu");
this.selectedGameIndex = (this.selectedGameIndex + 1) % this.games.length;
this.playSelectSound();
// Force redraw
this.drawGameSelectionInterface(null);
}
else if (e.key === 'Enter' || e.key === ' ') {
console.log("🎮 ENTER key detected for menu selection");
this.launchGame();
}
else if (e.key === 'Escape') {
console.log("🎮 ESCAPE key detected for menu");
this.hideGameSelection();
}
// Also nullify the input system's knowledge of this key
if (window.input && window.input.keys) {
window.input.keys[e.key] = false;
}
},
// Also capture keyup events to prevent any lingering key states
keyup: (e) => {
// Block all keyup events while menu is open
e.preventDefault();
e.stopPropagation();
// Ensure the input system doesn't see this key as pressed
if (window.input && window.input.keys) {
window.input.keys[e.key] = false;
}
}
};
// Add the listeners to document with capture phase
// Using capture ensures our handlers run before the game's handlers
document.addEventListener('keydown', this.menuKeyListeners.keydown, true);
document.addEventListener('keyup', this.menuKeyListeners.keyup, true);
}
else if (!this.gameSelectVisible && this.menuKeyListeners) {
// Remove menu listeners when menu is no longer visible
console.log("🎮 Removing menu key listeners on hide");
document.removeEventListener('keydown', this.menuKeyListeners.keydown, true);
document.removeEventListener('keyup', this.menuKeyListeners.keyup, true);
this.menuKeyListeners = null;
}
// Setup interaction key listener when near player but not in menu
if (!this.hasKeyListeners && !this.gameSelectVisible && this.isNearPlayer) {
// Set up one-time key listeners when player is near
console.log("🎮 Setting up direct key listeners for arcade interaction");
this.hasKeyListeners = true;
// Add a direct document-level event listener as a fallback
document.addEventListener('keydown', this.handleKeyDown = (e) => {
console.log(`🎮 Direct keydown detected: ${e.key}`);
if ((e.key === 'Enter' || e.key === ' ') && this.isNearPlayer && !this.gameSelectVisible) {
console.log("🎮 DIRECT ENTER KEY DETECTED - Starting interaction");
this.startInteraction();
// Prevent default action
e.preventDefault();
}
});
} else if (this.hasKeyListeners && (!this.isNearPlayer || this.gameSelectVisible)) {
// Remove listeners when no longer needed
console.log("🎮 Removing direct key listeners for arcade");
document.removeEventListener('keydown', this.handleKeyDown);
this.hasKeyListeners = false;
}
// Draw the game selection UI if it's visible
// This needs to happen every frame to keep the UI updated
if (this.gameSelectVisible) {
// Get the canvas context for drawing
const canvas = document.getElementById('gameCanvas');
if (canvas) {
const ctx = canvas.getContext('2d');
if (ctx) {
this.drawGameSelectionInterface(ctx);
}
}
}
}
/**
* Handle player input for arcade cabinet interaction
* @param {object} input - Input state object
* @param {Entity} player - Player entity
*/
handleInput(input, player) {
// This method is no longer used, as we've integrated input handling directly in update()
// Keep it for backward compatibility but log a warning if it gets called
debug(`ArcadeEntity: WARNING - handleInput() is deprecated, input handling moved to update()`);
}
/**
* Start arcade cabinet interaction
*/
startInteraction() {
debug(`ArcadeEntity: Starting interaction`);
this.gameSelectVisible = true;
// Tell the game system we're in an interaction
// This prevents player movement during menu navigation
if (window.game && typeof window.game.setInteractionActive === 'function') {
window.game.setInteractionActive(true);
debug(`ArcadeEntity: Set game interaction state to active`);
} else {
console.warn(`ArcadeEntity: Game interaction system not available!`);
}
// Play sound
this.playActivateSound();
}
/**
* Hide game selection menu
*/
hideGameSelection() {
debug(`ArcadeEntity: Hiding game selection`);
// Play a sound effect when closing the menu
this.playMenuCloseSound();
this.gameSelectVisible = false;
// Tell the game system interaction is over
// This allows player movement again
if (window.game && typeof window.game.setInteractionActive === 'function') {
window.game.setInteractionActive(false);
debug(`ArcadeEntity: Set game interaction state to inactive`);
}
// Remove menu key listeners if they exist
if (this.menuKeyListeners) {
console.log("🎮 Removing menu key listeners on hide");
document.removeEventListener('keydown', this.menuKeyListeners.keydown, true);
document.removeEventListener('keyup', this.menuKeyListeners.keyup, true);
this.menuKeyListeners = null;
}
// Remove the overlay canvas if it exists
const overlayCanvas = document.getElementById('arcadeMenuOverlay');
if (overlayCanvas) {
overlayCanvas.parentElement.removeChild(overlayCanvas);
}
// Clear any lingering key states in the input system
if (window.input && window.input.keys) {
// Reset common control keys to prevent stuck keys
const keysToReset = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight',
'w', 'a', 's', 'd', 'W', 'A', 'S', 'D',
'Enter', ' ', 'Escape'];