-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
1190 lines (987 loc) · 35.9 KB
/
game.js
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
// game.js
// ====================================
// 1. Define All Levels and Map Variables
// ====================================
const levels = [
// Level 1 - Easy
[
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,1,1,1,0,1,1,1,1,1,1,1,1,0,1],
[1,0,1,0,1,0,0,0,0,0,0,0,0,1,0,1],
[1,0,1,0,1,0,1,1,1,1,1,1,0,1,0,1],
[1,0,1,0,0,0,1,0,0,0,0,1,0,1,0,1],
[1,0,1,1,1,1,1,0,1,1,1,1,0,1,0,1],
[1,0,0,0,0,0,0,0,1,0,0,0,0,1,0,1],
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
],
// Level 2
[
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1],
[1,0,1,1,1,1,0,1,0,1,1,1,1,1,0,1],
[1,0,1,0,0,1,0,0,0,0,0,0,0,1,0,1],
[1,0,1,0,0,1,1,1,1,1,0,1,0,1,0,1],
[1,0,1,1,0,0,0,1,0,0,0,1,0,1,0,1],
[1,0,0,1,1,1,0,0,0,1,1,0,0,1,0,1],
[1,0,0,0,0,0,0,1,1,1,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
],
// Level 3
[
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,0,1,1,1,1,1,1,1,0,1],
[1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1],
[1,0,1,1,0,1,1,1,1,1,1,1,0,1,0,1],
[1,0,1,0,0,0,0,0,0,1,0,0,0,1,0,1],
[1,0,1,1,1,1,1,1,0,1,1,1,1,1,0,1],
[1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
],
[
// Level 4
[1,1,1,1,1,1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,1,0,0,1,0,0,0,0,0,1],
[1,0,1,0,0,0,1,0,0,1,0,0,0,0,0,1],
[1,0,1,0,0,0,1,0,1,1,1,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
]
];
// Initialize map variables
let map = [];
let mapWidth = 0;
let mapHeight = 0;
// ========================
// 2. Initialize the Canvas
// ========================
const canvas = document.getElementById('gameCanvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext('2d');
// ========================
// 3. Texture Loading
// ========================
const textures = {
256: new Image(),
128: new Image(),
64: new Image(),
32: new Image(),
16: new Image()
};
textures[256].src = 'textures/wall.png'; // Highest resolution
textures[128].src = 'textures/wall_128.png';
textures[64].src = 'textures/wall_64.png';
textures[32].src = 'textures/wall_32.png';
textures[16].src = 'textures/wall_16.png'; // Lowest resolution
let texturesLoaded = false;
let texturesToLoad = 5;
for (let size in textures) {
textures[size].onload = function() {
texturesToLoad--;
if (texturesToLoad === 0) {
texturesLoaded = true;
}
};
}
// ========================
// 4. Load Sprite Images
// ========================
const enemySprite = new Image();
enemySprite.src = 'textures/enemy.png';
const weaponSprite = new Image();
weaponSprite.src = 'textures/weapon.png';
const swordSprite = new Image();
swordSprite.src = 'textures/sword.png'; // Ensure this image exists
const potionSprite = new Image();
potionSprite.src = 'textures/potion.png'; // Add a potion sprite image
// ========================
// 5. Sound Manager
// ========================
// Sound Manager using Web Audio API
class SoundManager {
constructor() {
this.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
// Method to play a beep sound
playBeep(frequency = 440, duration = 0.1, volume = 0.5) {
const oscillator = this.audioCtx.createOscillator();
const gainNode = this.audioCtx.createGain();
oscillator.type = 'sine';
oscillator.frequency.setValueAtTime(frequency, this.audioCtx.currentTime); // Frequency in Hz
gainNode.gain.setValueAtTime(volume, this.audioCtx.currentTime); // Volume (0 to 1)
oscillator.connect(gainNode);
gainNode.connect(this.audioCtx.destination);
oscillator.start();
oscillator.stop(this.audioCtx.currentTime + duration);
}
// Method to play a short square wave (useful for attack sounds)
playAttackSound() {
this.playBeep(600, 0.1, 0.7);
}
// Method to play a pickup sound
playPickupSound() {
this.playBeep(300, 0.2, 0.5);
}
// Method to play a damage sound
playDamageSound() {
this.playBeep(200, 0.1, 0.6);
}
// Method to play a defeat sound (lower frequency)
playDefeatSound() {
this.playBeep(100, 0.3, 0.8);
}
}
// Instantiate the Sound Manager
const soundManager = new SoundManager();
// ========================
// 6. Define the Player Object
// ========================
let swordItem = localStorage.getItem('sword');
const player = {
x: 1.5, // starting x position
y: 1.5, // starting y position
dir: 0, // direction the player is facing (in radians)
fov: Math.PI / 3, // field of view (60 degrees)
speed: 0.03, // movement speed
turnSpeed: 0.02, // turning speed
radius: 0.2, // Player's collision radius
health: 100, // Player's health
sword: swordItem && swordItem.toLowerCase() === 'true'
? true
: false,
swordLevel: parseInt(localStorage.getItem('swordLevel')) || 1
};
// ========================
// 7. Initialize Game Variables
// ========================
// Initialize score
let score = parseInt(localStorage.getItem('score')) || 0;
// Initialize level
let currentLevel = parseInt(localStorage.getItem('currentLevel')) || 1;
const maxLevel = 10;
// Enemies array
let enemies = [];
// Weapons array
let weapons = [];
// Health Potions array
let healthPotions = [];
// Player's weapon
let playerWeapon = localStorage.getItem('weapon') || null;
// Game State
let gameState = 'running'; // 'running', 'gameover', 'levelcomplete', 'victory'
// ========================
// 8. Define Enemy Class
// ========================
class Enemy {
constructor(x, y, health = 100) {
this.x = x; // Enemy's position on the map
this.y = y;
this.health = health; // Enemy's health
this.speed = 0.02; // Movement speed
this.alive = true; // Is the enemy alive?
}
update() {
if (!this.alive) return;
// Simple AI to move towards the player
const dx = player.x - this.x;
const dy = player.y - this.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance > 0.5) {
// Move towards the player
const moveX = (dx / distance) * this.speed;
const moveY = (dy / distance) * this.speed;
const newX = this.x + moveX;
const newY = this.y + moveY;
// Check collision with walls for newX
if (map[Math.floor(this.y)][Math.floor(newX)] === 0) {
this.x = newX;
}
// Check collision with walls for newY
if (map[Math.floor(newY)][Math.floor(this.x)] === 0) {
this.y = newY;
}
} else {
// Attack the player
player.health -= 0.1; // Adjust damage as needed
soundManager.playDamageSound(); // Play damage sound
if (player.health <= 0) {
player.health = 0;
console.log('Player defeated!');
soundManager.playDefeatSound(); // Play defeat sound
// Trigger Game Over
showGameOver();
}
}
}
}
// ========================
// 9. Define Weapon Class
// ========================
class Weapon {
constructor(x, y) {
this.x = x;
this.y = y;
this.pickedUp = false;
}
}
// ========================
// 10. Define HealthPotion Class
// ========================
class HealthPotion {
constructor(x, y, healingAmount = 30) {
this.x = x;
this.y = y;
this.healingAmount = healingAmount;
this.pickedUp = false;
}
}
// ========================
// 11. Level Management Functions
// ========================
// Function to place enemies randomly
function placeEnemies(numEnemies, enemyHealth) {
enemies = []; // Reset enemies array
for (let i = 0; i < numEnemies; i++) {
let placed = false;
while (!placed) {
const x = Math.floor(Math.random() * mapWidth);
const y = Math.floor(Math.random() * mapHeight);
if (map[y][x] === 0 && (Math.abs(x - player.x) > 2 || Math.abs(y - player.y) > 2)) {
enemies.push(new Enemy(x + 0.5, y + 0.5, enemyHealth));
placed = true;
}
}
}
}
// Function to place weapons randomly
function placeWeaponsFunc(numWeapons) {
weapons = []; // Reset weapons array
for (let i = 0; i < numWeapons; i++) {
let placed = false;
while (!placed) {
const x = Math.floor(Math.random() * mapWidth);
const y = Math.floor(Math.random() * mapHeight);
if (map[y][x] === 0 && (Math.abs(x - player.x) > 2 || Math.abs(y - player.y) > 2)) {
weapons.push(new Weapon(x + 0.5, y + 0.5));
placed = true;
}
}
}
}
// Function to place health potions randomly
function placeHealthPotions(numPotions) {
healthPotions = []; // Reset health potions array
for (let i = 0; i < numPotions; i++) {
let placed = false;
while (!placed) {
const x = Math.floor(Math.random() * mapWidth);
const y = Math.floor(Math.random() * mapHeight);
if (map[y][x] === 0 && (Math.abs(x - player.x) > 2 || Math.abs(y - player.y) > 2)) {
healthPotions.push(new HealthPotion(x + 0.5, y + 0.5));
placed = true;
}
}
}
}
// Function to load a specific level
function loadLevel(levelNumber) {
if (levelNumber > levels.length) {
console.error('Level not defined!');
return;
}
// Set the current map
map.splice(0, map.length, ...levels[levelNumber - 1]);
// Set map dimensions
mapHeight = map.length;
mapWidth = map[0].length;
// Increase difficulty: more enemies and higher health
const numEnemies = 5 + levelNumber * 2; // Example: starting at 5, increasing by 2 each level
const enemyHealth = 100 + levelNumber * 20; // Example: starting at 100, increasing by 20 each level
placeEnemies(numEnemies, enemyHealth);
// Increase weapons: optional, can keep constant or increase
const numWeapons = 3 + Math.floor(levelNumber / 2); // Example: starting at 3, increasing by 1 every 2 levels
placeWeaponsFunc(numWeapons);
// Increase health potions: more potions in higher levels
const numPotions = 2 + Math.floor(levelNumber / 3); // Example: starting at 2, increasing by 1 every 3 levels
placeHealthPotions(numPotions);
// Reset player position and health
player.x = 1.5;
player.y = 1.5;
player.dir = 0;
player.health = 100;
// Preserve the sword and its power level if the player has acquired one
if (player.sword) {
drawSword();
console.log('Sword carried over to the next level with power:', player.swordLevel);
}
if (levelNumber === 1) {
// Reset sword level
player.swordLevel = 1;
// Reset score
score = 0;
}
// Store current level and score in Local Storage
localStorage.setItem('currentLevel', levelNumber);
localStorage.setItem('score', score);
}
// ========================
// 12. Raycasting Function
// ========================
function castRays() {
const numRays = canvas.width;
const angleStep = player.fov / numRays;
const zBuffer = []; // To keep track of wall distances for sprites
for (let i = 0; i < numRays; i++) {
const rayAngle = player.dir - (player.fov / 2) + (i * angleStep);
let distanceToWall = 0;
let hitWall = false;
let textureX = 0;
const eyeX = Math.cos(rayAngle);
const eyeY = Math.sin(rayAngle);
while (!hitWall && distanceToWall < 16) {
distanceToWall += 0.05;
const testX = player.x + eyeX * distanceToWall;
const testY = player.y + eyeY * distanceToWall;
const mapX = Math.floor(testX);
const mapY = Math.floor(testY);
if (mapX < 0 || mapX >= mapWidth || mapY < 0 || mapY >= mapHeight) {
hitWall = true;
distanceToWall = 16;
} else {
if (map[mapY][mapX] === 1) {
hitWall = true;
const blockX = testX % 1;
const blockY = testY % 1;
if (Math.abs(blockX - 1) < 0.0001 || blockX < 0.0001) {
textureX = blockY;
} else {
textureX = blockX;
}
textureX = textureX % 1;
}
}
}
// Correct fisheye distortion
const angleDifference = rayAngle - player.dir;
const correctedDistance = distanceToWall * Math.cos(angleDifference);
// Calculate wall height based on corrected distance
const lineHeight = (canvas.height / correctedDistance);
const drawStart = Math.floor(-lineHeight / 2 + canvas.height / 2);
const drawEnd = Math.floor(lineHeight / 2 + canvas.height / 2);
// Choose texture level based on corrected distance (mipmapping)
let textureSize;
if (correctedDistance < 2) {
textureSize = 256;
} else if (correctedDistance < 4) {
textureSize = 128;
} else if (correctedDistance < 8) {
textureSize = 64;
} else if (correctedDistance < 12) {
textureSize = 32;
} else {
textureSize = 16;
}
const texture = textures[textureSize];
// Draw the textured wall slice
if (texturesLoaded) {
ctx.drawImage(
texture,
Math.floor(textureX * texture.width), 0, 1, texture.height,
i, drawStart, 1, drawEnd - drawStart
);
} else {
// Texture not loaded yet; draw a plain wall
ctx.fillStyle = 'grey';
ctx.fillRect(i, drawStart, 1, drawEnd - drawStart);
}
zBuffer[i] = correctedDistance; // Save distance for sprite rendering
}
// Render sprites (enemies, weapons, and health potions)
renderSprites(zBuffer);
}
// ========================
// 13. Render Sprites Function
// ========================
function renderSprites(zBuffer) {
const sprites = [];
// Add enemies to sprites array
enemies.forEach(enemy => {
if (enemy.alive) {
const dx = enemy.x - player.x;
const dy = enemy.y - player.y;
const distance = Math.sqrt(dx * dx + dy * dy);
let angle = Math.atan2(dy, dx) - player.dir;
// Normalize angle between -PI and PI
while (angle < -Math.PI) angle += 2 * Math.PI;
while (angle > Math.PI) angle -= 2 * Math.PI;
// Sprite is within FOV
if (angle > -player.fov / 2 && angle < player.fov / 2) {
sprites.push({
type: 'enemy',
x: enemy.x,
y: enemy.y,
distance: distance,
angle: angle
});
}
}
});
// Add weapons to sprites array
weapons.forEach(weapon => {
if (!weapon.pickedUp) {
const dx = weapon.x - player.x;
const dy = weapon.y - player.y;
const distance = Math.sqrt(dx * dx + dy * dy);
let angle = Math.atan2(dy, dx) - player.dir;
// Normalize angle between -PI and PI
while (angle < -Math.PI) angle += 2 * Math.PI;
while (angle > Math.PI) angle -= 2 * Math.PI;
// Sprite is within FOV
if (angle > -player.fov / 2 && angle < player.fov / 2) {
sprites.push({
type: 'weapon',
x: weapon.x,
y: weapon.y,
distance: distance,
angle: angle
});
}
}
});
// Add health potions to sprites array
healthPotions.forEach(potion => {
if (!potion.pickedUp) {
const dx = potion.x - player.x;
const dy = potion.y - player.y;
const distance = Math.sqrt(dx * dx + dy * dy);
let angle = Math.atan2(dy, dx) - player.dir;
// Normalize angle between -PI and PI
while (angle < -Math.PI) angle += 2 * Math.PI;
while (angle > Math.PI) angle -= 2 * Math.PI;
// Sprite is within FOV
if (angle > -player.fov / 2 && angle < player.fov / 2) {
sprites.push({
type: 'potion',
x: potion.x,
y: potion.y,
distance: distance,
angle: angle
});
}
}
});
// Sort sprites by distance (furthest first)
sprites.sort((a, b) => b.distance - a.distance);
sprites.forEach(sprite => {
// Projection calculations
const spriteScreenX = (canvas.width / 2) * (1 + (Math.sin(sprite.angle) / Math.tan(player.fov / 2)));
const spriteSize = (canvas.height / sprite.distance);
const drawStartY = Math.floor((canvas.height / 2) - spriteSize / 2);
const drawEndY = drawStartY + spriteSize;
const drawStartX = Math.floor(spriteScreenX - spriteSize / 2);
const drawEndX = Math.floor(spriteScreenX + spriteSize / 2);
// Ensure sprite is within screen bounds
if (drawEndX < 0 || drawStartX >= canvas.width || drawEndY < 0 || drawStartY >= canvas.height) {
return; // Skip rendering this sprite
}
// Check z-buffer to see if sprite is behind a wall
const spriteMiddleX = Math.floor(spriteScreenX);
if (spriteMiddleX >= 0 && spriteMiddleX < canvas.width) {
if (sprite.distance < zBuffer[spriteMiddleX]) {
// Calculate sprite size and position
const scaledWidth = spriteSize;
const scaledHeight = spriteSize;
// Draw the sprite image
if (sprite.type === 'enemy' && enemySprite.complete) {
ctx.drawImage(
enemySprite,
0, 0, enemySprite.width, enemySprite.height,
drawStartX, drawStartY, scaledWidth, scaledHeight
);
// Draw enemy health indicator
drawEnemyHealth(sprite, drawStartX, drawStartY, scaledWidth);
} else if (sprite.type === 'weapon' && weaponSprite.complete) {
ctx.drawImage(
weaponSprite,
0, 0, weaponSprite.width, weaponSprite.height,
drawStartX, drawStartY, scaledWidth, scaledHeight
);
} else if (sprite.type === 'potion' && potionSprite.complete) {
ctx.drawImage(
potionSprite,
0, 0, potionSprite.width, potionSprite.height,
drawStartX, drawStartY, scaledWidth, scaledHeight
);
} else {
// Fallback to colored rectangle
if (sprite.type === 'enemy') {
ctx.fillStyle = 'red';
} else if (sprite.type === 'weapon') {
ctx.fillStyle = 'yellow';
} else if (sprite.type === 'potion') {
ctx.fillStyle = 'purple';
}
ctx.fillRect(drawStartX, drawStartY, scaledWidth, scaledHeight);
}
}
}
});
}
// ========================
// 14. Function to Draw Enemy Health Indicators
// ========================
function drawEnemyHealth(sprite, drawStartX, drawStartY, spriteWidth) {
const healthBarWidth = spriteWidth;
const healthBarHeight = 5; // Thickness of the health bar
// Find the corresponding enemy object
const enemy = enemies.find(e => e.x === sprite.x && e.y === sprite.y && e.alive);
if (enemy) {
const healthPercent = Math.max(0, Math.min(1, enemy.health / 100));
// Position the health bar above the sprite
const healthBarX = drawStartX;
const healthBarY = drawStartY - 10; // 10 pixels above the sprite
// Background of the health bar (gray)
ctx.fillStyle = 'gray';
ctx.fillRect(healthBarX, healthBarY, healthBarWidth, healthBarHeight);
// Health portion (green)
ctx.fillStyle = 'green';
ctx.fillRect(healthBarX, healthBarY, healthBarWidth * healthPercent, healthBarHeight);
}
}
// ========================
// 15. Function to Draw the Sword in the Player's View
// ========================
function drawSword() {
if (playerWeapon && swordSprite.complete) {
const swordWidth = 100; // Adjust size as needed
const swordHeight = 200; // Adjust size as needed
const swordX = (canvas.width / 2) - (swordWidth / 2);
const swordY = canvas.height - swordHeight - 50; // Positioning above bottom edge
// Save the current context state
ctx.save();
// Translate to the pivot point (e.g., bottom center of the sword)
ctx.translate(swordX + swordWidth / 2, swordY + swordHeight);
// Calculate rotation angle
let rotation = -Math.PI / 6; // Default angle (30 degrees upwards)
if (isAttacking) {
// Swing the sword by rotating it
rotation += (Math.PI / 4) * (attackFrame / maxAttackFrames); // Swing 45 degrees
}
// Rotate the context
ctx.rotate(rotation);
// Draw the sword image centered at the pivot
ctx.drawImage(
swordSprite,
-swordWidth / 2, -swordHeight,
swordWidth, swordHeight
);
// Restore the context to its original state
ctx.restore();
}
}
// ========================
// 16. Handle Player Input and Movement
// ========================
const keys = {};
window.addEventListener('keydown', function(e) {
keys[e.code] = true;
// Handle attack with spacebar
if (e.code === 'Space') {
e.preventDefault(); // Prevent page from scrolling
attack();
}
});
window.addEventListener('keyup', function(e) {
keys[e.code] = false;
});
// Sword attack animation variables
let isAttacking = false; // Flag to indicate if the player is attacking
let attackFrame = 0; // Current frame of the attack animation
const maxAttackFrames = 10; // Total frames for the attack animation
function movePlayer() {
let moveStep = 0;
if (keys['ArrowUp'] || keys['KeyW']) {
moveStep = player.speed;
}
if (keys['ArrowDown'] || keys['KeyS']) {
moveStep = -player.speed;
}
// Calculate new position
const newX = player.x + Math.cos(player.dir) * moveStep;
const newY = player.y + Math.sin(player.dir) * moveStep;
// Collision detection with consideration of player's radius
if (isWalkable(newX, player.y)) {
player.x = newX;
}
if (isWalkable(player.x, newY)) {
player.y = newY;
}
if (keys['ArrowLeft'] || keys['KeyA']) {
player.dir -= player.turnSpeed;
}
if (keys['ArrowRight'] || keys['KeyD']) {
player.dir += player.turnSpeed;
}
// Keep the angle between 0 and 2PI
if (player.dir < 0) {
player.dir += 2 * Math.PI;
}
if (player.dir > 2 * Math.PI) {
player.dir -= 2 * Math.PI;
}
}
function isWalkable(x, y) {
const margin = player.radius;
const minX = x - margin;
const maxX = x + margin;
const minY = y - margin;
const maxY = y + margin;
const mapMinX = Math.floor(minX);
const mapMaxX = Math.floor(maxX);
const mapMinY = Math.floor(minY);
const mapMaxY = Math.floor(maxY);
// Check all corners around the player for collisions
return (
map[mapMinY][mapMinX] === 0 &&
map[mapMinY][mapMaxX] === 0 &&
map[mapMaxY][mapMinX] === 0 &&
map[mapMaxY][mapMaxX] === 0
);
}
// ========================
// 17. Weapon Pickup Function
// ========================
function checkWeaponPickup() {
weapons.forEach(weapon => {
if (!weapon.pickedUp) {
const dx = player.x - weapon.x;
const dy = player.y - weapon.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < 0.5) {
weapon.pickedUp = true;
playerWeapon = weapon;
if (player.sword) {
player.swordLevel += 1; // Increase sword power if the player already has one
console.log('Sword power increased to:', player.swordLevel);
} else {
player.sword = true; // Assign the sword to the player
player.swordLevel = 1; // Start with power level 1
console.log('Sword picked up with power level:', player.swordLevel);
}
soundManager.playPickupSound(); // Play pickup sound
}
}
});
}
// ========================
// 18. Health Potion Pickup Function
// ========================
function checkHealthPotionPickup() {
healthPotions.forEach(potion => {
if (!potion.pickedUp) {
const dx = player.x - potion.x;
const dy = player.y - potion.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < 0.5) {
potion.pickedUp = true;
player.health += potion.healingAmount;
player.health = Math.min(player.health, 100); // Cap health at 100
soundManager.playPickupSound(); // Play pickup sound
console.log('Health Potion picked up! Health:', player.health);
}
}
});
}
// ========================
// 19. Attack Function
// ========================
function attack() {
if (!playerWeapon) {
console.log('No weapon to attack with!');
return;
}
if (isAttacking) return; // Prevent multiple attacks at the same time
isAttacking = true;
attackFrame = 0; // Reset attack animation
soundManager.playAttackSound(); // Play attack sound
// Cast a ray straight ahead to see if an enemy is in front
const rayAngle = player.dir;
let distanceToEnemy = 0;
let hitEnemy = null;
const eyeX = Math.cos(rayAngle);
const eyeY = Math.sin(rayAngle);
while (!hitEnemy && distanceToEnemy < 2) {
distanceToEnemy += 0.1;
const testX = player.x + eyeX * distanceToEnemy;
const testY = player.y + eyeY * distanceToEnemy;
// Check for enemy collision
enemies.forEach(enemy => {
if (enemy.alive) {
const dx = enemy.x - testX;
const dy = enemy.y - testY;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < 0.5) {
hitEnemy = enemy;
}
}
});
// Check for wall collision to stop the attack ray
if (map[Math.floor(testY)][Math.floor(testX)] === 1) {
break;
}
}
if (hitEnemy) {
// Calculate damage based on sword level
const damage = 50 * player.swordLevel;
hitEnemy.health -= damage;
console.log(`Hit enemy! Damage: ${damage}. Health remaining: ${hitEnemy.health}`);
if (hitEnemy.health <= 0) {
hitEnemy.alive = false;
score += 1; // Increment score
soundManager.playDamageSound(); // Play damage sound
console.log('Enemy defeated! Total Score:', score);
} else {
soundManager.playDamageSound(); // Play damage sound even if not defeated
}
} else {
console.log('Missed!');
}
}
// ========================
// 20. Mini-Map Function
// ========================
const miniMapScale = 20; // Scale down the map
const miniMapX = 20; // X position on the canvas
const miniMapY = 20; // Y position on the canvas