-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcannonCPU.html
More file actions
1335 lines (1154 loc) · 56.7 KB
/
cannonCPU.html
File metadata and controls
1335 lines (1154 loc) · 56.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cannon Game</title>
<style>
/* Basic reset and font */
body {
margin: 0;
padding: 0;
font-family: "Inter", sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
background-color: #f0f4f8; /* Light background for the page */
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: 100vh;
overflow: hidden; /* Prevent body scroll bars */
color: #333;
}
/* Main container for the game and controls */
.game-container {
position: relative;
width: 95%; /* Responsive width */
max-width: 900px; /* Max width for larger screens */
background-color: #ffffff;
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
padding: 20px;
display: flex; /* Use flexbox for layout */
flex-direction: column; /* Default to column for small screens */
align-items: center;
gap: 20px; /* Space between canvas and controls */
}
@media (min-width: 768px) { /* For larger screens, arrange side-by-side */
.game-container {
flex-direction: row;
justify-content: center;
align-items: flex-start; /* Align items to the top */
}
}
h1 {
font-size: 2.25rem; /* 36px */
font-weight: 700; /* bold */
margin-bottom: 1.5rem; /* 24px */
color: #2d3748; /* gray-800 */
}
canvas {
background-color: transparent; /* Background will be drawn by JS */
display: block;
border-radius: 10px; /* Rounded corners for the canvas */
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* Subtle shadow for canvas */
width: 100%; /* Make canvas fill its container width */
max-width: 600px; /* Max width for canvas */
aspect-ratio: 1 / 1; /* Maintain 1:1 aspect ratio */
}
@media (min-width: 768px) {
canvas {
width: calc(100% - 250px); /* Adjust width to make space for settings */
}
}
/* Message box for audio prompt */
#messageBox {
position: absolute;
inset: 0; /* Cover the entire parent */
background-color: rgba(0, 0, 0, 0.75);
display: flex;
align-items: center;
justify-content: center;
border-radius: 10px;
z-index: 10; /* Ensure it's on top */
text-align: center;
}
#messageBox p {
color: #ffffff;
font-size: 1.25rem; /* 20px */
font-weight: 600; /* semibold */
padding: 1rem; /* 16px */
border-radius: 6px;
background-color: #4a5568; /* gray-700 */
}
/* Settings controls */
.settings-container {
width: 100%;
max-width: 220px; /* Max width for settings column */
display: flex;
flex-direction: column;
gap: 15px;
padding-top: 10px;
padding-left: 10px; /* Add some padding if next to canvas */
}
.setting-item {
display: flex;
flex-direction: column;
align-items: flex-start;
width: 100%;
}
.setting-item label {
font-size: 1rem;
font-weight: 500;
margin-bottom: 5px;
display: flex;
align-items: center;
gap: 8px;
}
.setting-item input[type="range"] {
width: 100%;
-webkit-appearance: none; /* Remove default slider styles */
height: 8px;
background: #d1d5db; /* light gray */
border-radius: 5px;
outline: none;
opacity: 0.7;
transition: opacity .2s;
}
.setting-item input[type="range"]:hover {
opacity: 1;
}
.setting-item input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 20px;
height: 20px;
border-radius: 50%;
background: #4f46e5; /* indigo-600 */
cursor: pointer;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.setting-item input[type="range"]::-moz-range-thumb {
width: 20px;
height: 20px;
border-radius: 50%;
background: #4f46e5; /* indigo-600 */
cursor: pointer;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.setting-item span {
font-size: 0.9rem;
color: #6b7280; /* gray-500 */
margin-top: 5px;
}
.setting-item input[type="checkbox"] {
width: 18px;
height: 18px;
cursor: pointer;
accent-color: #4f46e5; /* indigo-600 */
}
.action-button {
background-color: #ef4444; /* Red color for delete */
color: white;
padding: 10px 15px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
font-weight: 600;
transition: background-color 0.2s ease;
width: 100%;
margin-top: 10px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.action-button:hover {
background-color: #dc2626; /* Darker red on hover */
}
</style>
</head>
<body>
<h1>Cannon Game</h1>
<div class="game-container">
<canvas id="gameCanvas"></canvas>
<div id="messageBox" style="display: none;">
<p>Please click anywhere to start the game and enable sound!</p>
</div>
<div class="settings-container">
<div class="setting-item">
<label for="muteAudioToggle">
<input type="checkbox" id="muteAudioToggle">
Mute Audio
</label>
</div>
<div class="setting-item">
<label for="shotPowerSlider">Shot Power:</label>
<input type="range" id="shotPowerSlider" min="1" max="20" value="6.5" step="0.5">
<span id="shotPowerValue">6.5</span>
</div>
<div class="setting-item">
<label for="fireRateSlider">Fire Rate:</label>
<input type="range" id="fireRateSlider" min="100" max="2000" value="200" step="100">
<span id="fireRateValue">0.2 sec</span>
</div>
<div class="setting-item">
<label for="gravitySlider">Gravity:</label>
<input type="range" id="gravitySlider" min="0.01" max="0.2" value="0.05" step="0.01">
<span id="gravityValue">0.05</span>
</div>
<div class="setting-item">
<label for="mortarToggle">
<input type="checkbox" id="mortarToggle" checked>
Mortars
</label>
</div>
<div class="setting-item">
<label for="bombToggle">
<input type="checkbox" id="bombToggle">
Bombs
</label>
</div>
<div class="setting-item">
<label for="darkModeToggle">
<input type="checkbox" id="darkModeToggle">
Dark Mode
</label>
</div>
<button id="restartBtn" class="action-button">Restart</button>
</div>
</div>
<script>
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const messageBox = document.getElementById("messageBox");
// Settings elements
const muteAudioToggle = document.getElementById("muteAudioToggle");
const shotPowerSlider = document.getElementById("shotPowerSlider");
const shotPowerValueSpan = document.getElementById("shotPowerValue");
const fireRateSlider = document.getElementById("fireRateSlider");
const fireRateValueSpan = document.getElementById("fireRateValue");
const gravitySlider = document.getElementById("gravitySlider");
const gravityValueSpan = document.getElementById("gravityValue");
const mortarToggle = document.getElementById("mortarToggle");
const bombToggle = document.getElementById("bombToggle");
const darkModeToggle = document.getElementById("darkModeToggle");
const restartBtn = document.getElementById("restartBtn");
// Game State Variables
let mousePos = null;
let angle = null;
let canShoot = true;
let shotPower = parseFloat(shotPowerSlider.value);
let gravityValue = parseFloat(gravitySlider.value);
let fireRateDelay = parseInt(fireRateSlider.value); // Milliseconds
let isMuted = muteAudioToggle.checked;
let isMortarMode = mortarToggle.checked;
let isBombMode = bombToggle.checked;
let isDarkMode = darkModeToggle.checked;
// Cannon movement
let cannonMoveSpeed = 5; // Pixels per frame
let keysPressed = {}; // To track multiple key presses
// Arrays for game objects
let cannonBalls = [];
let explosionPieces = [];
// --- Web Audio API for Sound Effects ---
let audioContext;
let cannonOscillator;
let cannonGain;
let collisionOscillator1, collisionOscillator2;
let collisionGain;
let explosionOscillator;
let explosionGain;
let sizzleNoiseBuffer; // For bomb fuse sizzle (reusable buffer)
let sizzleFilter;
let sizzleGain;
let sizzleBufferSource = null; // To control start/stop of sizzle
/**
* Initializes the Web Audio API context and nodes.
* This must be called after a user gesture.
*/
function initializeAudio() {
if (!audioContext) {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Cannon Sound (low tone beep)
cannonOscillator = audioContext.createOscillator();
cannonOscillator.type = 'sine';
cannonOscillator.frequency.setValueAtTime(100, audioContext.currentTime);
cannonOscillator.start();
cannonGain = audioContext.createGain();
cannonGain.gain.setValueAtTime(0, audioContext.currentTime);
cannonOscillator.connect(cannonGain);
cannonGain.connect(audioContext.destination);
// Collision Sound (metallic percussive)
collisionOscillator1 = audioContext.createOscillator();
collisionOscillator1.type = 'triangle';
collisionOscillator1.frequency.setValueAtTime(200, audioContext.currentTime);
collisionOscillator1.start();
collisionOscillator2 = audioContext.createOscillator();
collisionOscillator2.type = 'square';
collisionOscillator2.frequency.setValueAtTime(400, audioContext.currentTime);
collisionOscillator2.start();
collisionGain = audioContext.createGain();
collisionGain.gain.setValueAtTime(0, audioContext.currentTime);
collisionOscillator1.connect(collisionGain);
collisionOscillator2.connect(collisionGain);
collisionGain.connect(audioContext.destination);
// Explosion Sound (short, noisy burst)
explosionOscillator = audioContext.createOscillator();
explosionOscillator.type = 'sawtooth';
explosionOscillator.frequency.setValueAtTime(60, audioContext.currentTime);
explosionOscillator.start();
explosionGain = audioContext.createGain();
explosionGain.gain.setValueAtTime(0, audioContext.currentTime);
explosionOscillator.connect(explosionGain);
explosionGain.connect(audioContext.destination);
// Sizzling Fuse Sound (white noise through bandpass filter)
// Create a reusable noise buffer
const bufferSize = audioContext.sampleRate * 0.5; // 0.5 seconds of noise
sizzleNoiseBuffer = audioContext.createBuffer(1, bufferSize, audioContext.sampleRate);
const output = sizzleNoiseBuffer.getChannelData(0);
for (let i = 0; i < bufferSize; i++) {
output[i] = Math.random() * 2 - 1; // White noise
}
sizzleFilter = audioContext.createBiquadFilter();
sizzleFilter.type = 'bandpass';
sizzleFilter.frequency.setValueAtTime(8000, audioContext.currentTime);
sizzleFilter.Q.setValueAtTime(1, audioContext.currentTime);
sizzleGain = audioContext.createGain();
sizzleGain.gain.setValueAtTime(0, audioContext.currentTime);
sizzleGain.connect(audioContext.destination);
isAudioInitialized = true;
messageBox.style.display = 'none'; // Hide message box
}
}
/**
* Plays the cannon firing sound.
*/
function playCannonSound() {
if (!isAudioInitialized || isMuted) return;
const now = audioContext.currentTime;
cannonGain.gain.cancelScheduledValues(now);
cannonGain.gain.setValueAtTime(0.5, now);
cannonGain.gain.exponentialRampToValueAtTime(0.001, now + 0.3);
}
/**
* Plays the collision sound.
*/
function playCollisionSound() {
if (!isAudioInitialized || isMuted) return;
const now = audioContext.currentTime;
collisionGain.gain.cancelScheduledValues(now);
collisionGain.gain.setValueAtTime(0.3, now);
collisionGain.gain.exponentialRampToValueAtTime(0.001, now + 0.1);
}
/**
* Plays the explosion sound.
*/
function playExplosionSound() {
if (!isAudioInitialized || isMuted) return;
const now = audioContext.currentTime;
explosionGain.gain.cancelScheduledValues(now);
explosionGain.gain.setValueAtTime(0.8, now); // Louder for explosion
explosionGain.gain.exponentialRampToValueAtTime(0.001, now + 0.5); // Slightly longer decay
}
/**
* Starts the sizzling fuse sound for a bomb.
* @param {number} duration - The duration over which the sizzle should fade out.
*/
function startSizzleSound(duration) {
if (!isAudioInitialized || isMuted) return;
// Stop any existing sizzle sound before starting a new one
if (sizzleBufferSource) {
try {
sizzleBufferSource.stop();
sizzleBufferSource.disconnect();
} catch (e) {
// Already stopped or disconnected
}
}
sizzleBufferSource = audioContext.createBufferSource();
sizzleBufferSource.buffer = sizzleNoiseBuffer; // Use the pre-generated buffer
sizzleBufferSource.loop = true;
sizzleBufferSource.connect(sizzleFilter);
sizzleFilter.connect(sizzleGain); // Connect filter to gain
sizzleBufferSource.start();
const now = audioContext.currentTime;
sizzleGain.gain.cancelScheduledValues(now);
sizzleGain.gain.setValueAtTime(0.4, now); // Start loud
sizzleGain.gain.linearRampToValueAtTime(0.001, now + duration); // Fade out over bomb duration
// Stop the buffer source after the duration + a small buffer
sizzleBufferSource.stop(now + duration + 0.1);
}
// Show message box until user interacts to enable audio
messageBox.style.display = 'flex';
document.body.addEventListener('click', initializeAudio, { once: true });
// --- Utility Functions ---
/**
* Resizes the canvas to fit its parent container and maintain aspect ratio.
*/
function resizeCanvas() {
const parent = canvas.parentElement;
const aspectRatio = 1; // 1:1 aspect ratio (600/600)
let newWidth = parent.clientWidth;
let newHeight = newWidth / aspectRatio;
// Constrain height if it's too large for the window
const maxAllowedHeight = window.innerHeight * 0.7; // Max 70% of window height
if (newHeight > maxAllowedHeight) {
newHeight = maxAllowedHeight;
newWidth = newHeight * aspectRatio;
}
canvas.width = newWidth;
canvas.height = newHeight;
// Scale factor for drawing elements
// We'll scale all coordinates and sizes based on the new canvas size.
// Using a base size of 600 for scaling, as original logic was for 600x600.
const baseSize = 600;
window.scaleFactor = canvas.width / baseSize;
// Redraw everything after resize
drawBackground();
drawBorder();
cannon.draw();
cannonBalls.forEach(ball => ball.draw());
explosionPieces.forEach(piece => piece.draw());
}
/**
* Draws the game background: cyan/black sky and green/dark gray grass.
*/
function drawBackground() {
const grassHeightRatio = 0.2; // 20% of canvas height for grass
const grassHeight = canvas.height * grassHeightRatio;
const skyHeight = canvas.height - grassHeight;
// Always clear the entire canvas area first before drawing background
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (isDarkMode) {
// Draw black sky
ctx.fillStyle = "#000000"; // Black
ctx.fillRect(0, 0, canvas.width, skyHeight);
// Draw black grass (or very dark gray)
ctx.fillStyle = "#1a1a1a"; // Dark gray for ground in dark mode
ctx.fillRect(0, skyHeight, canvas.width, grassHeight);
} else {
// Draw cyan sky
ctx.fillStyle = "#00FFFF"; // Cyan
ctx.fillRect(0, 0, canvas.width, skyHeight);
// Draw green grass
ctx.fillStyle = "#7CFC00"; // Green grass
ctx.fillRect(0, skyHeight, canvas.width, grassHeight);
}
}
/**
* Draws a dark gray border around the playable area.
*/
function drawBorder() {
const borderWidth = 20 * window.scaleFactor; // Scaled border width
const playableAreaX = borderWidth;
const playableAreaY = borderWidth;
const playableAreaWidth = canvas.width - (2 * borderWidth);
const playableAreaHeight = canvas.height - (2 * borderWidth);
// Draw outer border (this will overlap the background drawn by drawBackground)
ctx.fillStyle = "#666666";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Now, draw the actual playable area on top of the border,
// using the same background logic as drawBackground().
// This ensures the border is always visible and the background colors are correct.
const grassHeightRatio = 0.2;
const grassHeight = canvas.height * grassHeightRatio;
const skyHeight = canvas.height - grassHeight;
if (isDarkMode) {
ctx.fillStyle = "#000000"; // Black sky for playable area
ctx.fillRect(playableAreaX, playableAreaY, playableAreaWidth, skyHeight - playableAreaY);
ctx.fillStyle = "#1a1a1a"; // Dark gray grass for playable area
ctx.fillRect(playableAreaX, skyHeight, playableAreaWidth, grassHeight - (canvas.height - playableAreaHeight - playableAreaY - skyHeight));
} else {
ctx.fillStyle = "#00FFFF"; // Cyan sky for playable area
ctx.fillRect(playableAreaX, playableAreaY, playableAreaWidth, skyHeight - playableAreaY);
ctx.fillStyle = "#7CFC00"; // Green grass for playable area
ctx.fillRect(playableAreaX, skyHeight, playableAreaWidth, grassHeight - (canvas.height - playableAreaHeight - playableAreaY - skyHeight));
}
}
/**
* Calculates the new position of a point after rotation around a pivot.
* Used to find the cannonball's starting position correctly.
* @param {number} x - Original X coordinate of the point (unscaled).
* @param {number} y - Original Y coordinate of the point (unscaled).
* @returns {{x: number, y: number}} The new rotated and scaled coordinates.
*/
function sortBallPos(x, y) {
let rotatedAngle = angle;
// Cannon pivot is (cannon.x, cannon.y) in unscaled coordinates (center of barrel)
const pivotX_unscaled = cannon.x;
const pivotY_unscaled = cannon.y;
// Scale the original point to be rotated and the pivot
const scaledX = x * window.scaleFactor;
const scaledY = y * window.scaleFactor;
const pivotX_scaled = pivotX_unscaled * window.scaleFactor;
const pivotY_scaled = pivotY_unscaled * window.scaleFactor;
let dx = scaledX - pivotX_scaled;
let dy = scaledY - pivotY_scaled;
let distance = Math.sqrt(dx * dx + dy * dy);
let originalAngle = Math.atan2(dy, dx);
// Work out new positions
let newX = pivotX_scaled + distance * Math.cos(originalAngle + rotatedAngle);
let newY = pivotY_scaled + distance * Math.sin(originalAngle + rotatedAngle);
return {
x: newX,
y: newY
};
}
// --- Cannon Class ---
class Cannon {
constructor(x, y) {
this.x = x; // Center X of the cannon barrel (unscaled)
this.y = y; // Center Y of the cannon barrel (unscaled)
this.width = 100; // Unscaled width
this.height = 50; // Unscaled height
}
/**
* Rotates the canvas context to align with the mouse position for the cannon.
*/
rotateTop() {
if (mousePos) {
const pivotX_scaled = this.x * window.scaleFactor;
const pivotY_scaled = this.y * window.scaleFactor; // Pivot is now center Y
angle = Math.atan2(mousePos.y - pivotY_scaled, mousePos.x - pivotX_scaled);
// No clamping for visual aiming, allow full rotation
ctx.translate(pivotX_scaled, pivotY_scaled);
ctx.rotate(angle);
ctx.translate(-pivotX_scaled, -pivotY_scaled);
}
}
/**
* Draws the cannon barrel with a dithered pattern and a light tan firing end.
*/
draw() {
ctx.save(); // Save the current canvas state before rotation
this.rotateTop();
const scaledWidth = this.width * window.scaleFactor;
const scaledHeight = this.height * window.scaleFactor;
// Draw the main dithered brown barrel
const patternCanvas = document.createElement('canvas');
patternCanvas.width = 10;
patternCanvas.height = 10;
const pCtx = patternCanvas.getContext('2d');
pCtx.fillStyle = "#A0522D"; // SaddleBrown
pCtx.fillRect(0, 0, patternCanvas.width, patternCanvas.height);
pCtx.fillStyle = "#8B4513"; // Darker brown (Sienna) for dither dots
for (let i = 0; i < patternCanvas.width; i += 2) {
for (let j = 0; j < patternCanvas.height; j += 2) {
pCtx.fillRect(i, j, 1, 1);
pCtx.fillRect(i + 1, j + 1, 1, 1);
}
}
const pattern = ctx.createPattern(patternCanvas, 'repeat');
ctx.fillStyle = pattern;
// Draw barrel from its top-left corner, relative to the current transformed origin (which is the pivot)
// The pivot is at (this.x, this.y)
ctx.fillRect(this.x * window.scaleFactor - scaledWidth / 2, this.y * window.scaleFactor - scaledHeight / 2, scaledWidth, scaledHeight);
ctx.strokeStyle = "#6B3E1F";
ctx.lineWidth = 2 * window.scaleFactor;
ctx.strokeRect(this.x * window.scaleFactor - scaledWidth / 2, this.y * window.scaleFactor - scaledHeight / 2, scaledWidth, scaledHeight);
// Draw the light tan firing end
const tanLength = 15 * window.scaleFactor; // Length of the tan tip
ctx.fillStyle = "#F5DEB3"; // Light tan
// Position the tan end at the right side of the barrel
ctx.fillRect(this.x * window.scaleFactor + scaledWidth / 2 - tanLength, this.y * window.scaleFactor - scaledHeight / 2, tanLength, scaledHeight);
ctx.strokeStyle = "#D2B48C"; // Darker tan border
ctx.lineWidth = 2 * window.scaleFactor;
ctx.strokeRect(this.x * window.scaleFactor + scaledWidth / 2 - tanLength, this.y * window.scaleFactor - scaledHeight / 2, tanLength, scaledHeight);
ctx.restore();
}
/**
* Updates the cannon's position based on keyboard input.
*/
update() {
// Cannon's X position is the center of the barrel
const minCannonX = 20 + this.width / 2; // Left border + half width
const maxCannonX = 600 - 20 - this.width / 2; // Right border - half width
if (keysPressed['arrowleft'] || keysPressed['a']) {
this.x -= cannonMoveSpeed / window.scaleFactor; // Unscale speed for internal logic
}
if (keysPressed['arrowright'] || keysPressed['d']) {
this.x += cannonMoveSpeed / window.scaleFactor; // Unscale speed for internal logic
}
// Clamp cannon position to stay within bounds
this.x = Math.max(minCannonX, Math.min(maxCannonX, this.x));
}
}
// Initialize cannon:
// Cannon width = 100, height = 50 (unscaled)
// Canvas height = 600, border = 20 (unscaled)
// Bottom of playable area = 600 - 20 = 580 (unscaled)
// User wants cannon's center to be half its height (25) above the bottom frame.
// So, cannon's bottom edge should be at (580 - 25) = 555 (unscaled)
// Cannon's center Y (this.y) = 555 - (cannon.height / 2) = 555 - 25 = 530 (unscaled)
// Initial X remains 130 (center of barrel)
let cannon = new Cannon(130, 530);
// --- CannonBall Class ---
class CannonBall {
constructor(angle, x, y, type = 'normal') { // type can be 'normal', 'mortar', 'bomb'
this.radius = 15; // Unscaled radius
this.mass = this.radius;
this.angle = angle;
this.x = x; // Already scaled X
this.y = y; // Already scaled Y
this.dx = Math.cos(angle) * shotPower * window.scaleFactor; // Scaled velocity based on shotPower
this.dy = Math.sin(angle) * shotPower * window.scaleFactor; // Scaled velocity based on shotPower
this.gravity = gravityValue * window.scaleFactor; // Scaled gravity based on gravityValue
this.elasticity = 0.5;
this.friction = 0.008;
this.shouldAudio = true;
this.timeDiff1 = null;
this.timeDiff2 = null;
this.type = type;
this.explosionDelay = (type === 'bomb') ? 3 : 2; // 3 seconds for bomb, 2 for mortar
this.bombStartTime = (type === 'mortar' || type === 'bomb') ? audioContext.currentTime : null;
this.exploded = false;
this.fuseParticles = []; // For fuse visual effect
}
/**
* Moves the cannonball based on its velocity and gravity.
*/
move() {
// Sort out gravity
const groundLevel = (580 - 20) * window.scaleFactor; // Scaled ground level adjusted for border
if (this.y + (this.radius * window.scaleFactor) < groundLevel) {
this.dy += this.gravity;
}
// Apply friction to X axis
this.dx = this.dx - (this.dx * this.friction);
this.x += this.dx;
this.y += this.dy;
// Update fuse particles if it's a bomb or mortar
if ((this.type === 'mortar' || this.type === 'bomb') && !this.exploded) {
this.updateFuse();
}
}
/**
* Draws the cannonball.
*/
draw() {
const scaledRadius = this.radius * window.scaleFactor;
// Draw ball body
if (this.type === 'bomb') {
// Black, shiny bomb
ctx.fillStyle = "#000000"; // Black
ctx.beginPath();
ctx.arc(this.x, this.y, scaledRadius, 0, Math.PI * 2);
ctx.fill();
// Add a shiny highlight
ctx.fillStyle = "rgba(255, 255, 255, 0.3)";
ctx.beginPath();
ctx.arc(this.x - scaledRadius * 0.4, this.y - scaledRadius * 0.4, scaledRadius * 0.6, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = "#222222"; // Darker border
ctx.lineWidth = 1 * window.scaleFactor;
ctx.stroke();
} else {
// Dithered gray for normal/mortar balls
const patternCanvas = document.createElement('canvas');
patternCanvas.width = 10;
patternCanvas.height = 10;
const pCtx = patternCanvas.getContext('2d');
pCtx.fillStyle = "#AAAAAA";
pCtx.fillRect(0, 0, patternCanvas.width, patternCanvas.height);
pCtx.fillStyle = "#666666";
for (let i = 0; i < patternCanvas.width; i += 2) {
for (let j = 0; j < patternCanvas.height; j += 2) {
pCtx.fillRect(i, j, 1, 1);
pCtx.fillRect(i + 1, j + 1, 1, 1);
}
}
const pattern = ctx.createPattern(patternCanvas, 'repeat');
ctx.fillStyle = pattern;
ctx.beginPath();
ctx.arc(this.x, this.y, scaledRadius, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = "#333333";
ctx.lineWidth = 1 * window.scaleFactor;
ctx.stroke();
}
// Draw fuse if it's a bomb or mortar and not exploded
if ((this.type === 'mortar' || this.type === 'bomb') && !this.exploded) {
this.drawFuse();
}
}
/**
* Updates the fuse particles for a bomb/mortar.
*/
updateFuse() {
const scaledRadius = this.radius * window.scaleFactor;
// Calculate fuse tip position (behind the ball, relative to its movement angle)
let currentFuseLength = (this.type === 'bomb' ? 3 : 2) * window.scaleFactor;
if (this.type === 'bomb' && audioContext && this.bombStartTime) {
const elapsed = audioContext.currentTime - this.bombStartTime;
currentFuseLength = currentFuseLength * (1 - (elapsed / this.explosionDelay));
currentFuseLength = Math.max(0, currentFuseLength);
}
// Fuse starts at the back edge of the ball
// We need to calculate the point on the circumference directly opposite to the firing direction
const fuseStartAngle = this.angle + Math.PI; // Opposite direction of travel
const fuseStartX = this.x + Math.cos(fuseStartAngle) * scaledRadius;
const fuseStartY = this.y + Math.sin(fuseStartAngle) * scaledRadius;
// Fuse tip is at the end of the current fuse length, extending straight from the back of the ball
const fuseTipX = fuseStartX + Math.cos(fuseStartAngle) * currentFuseLength;
const fuseTipY = fuseStartY + Math.sin(fuseStartAngle) * currentFuseLength;
// Add new particles from the fuse tip
if (Math.random() < 0.7) { // Chance to spawn a new particle
const angleOffset = (Math.random() - 0.5) * Math.PI / 4; // Small random angle around the back
const particleAngle = fuseStartAngle + angleOffset; // Sparks emit backward from fuse tip
const particleSpeed = (Math.random() * 2 + 1) * window.scaleFactor;
let particleColor;
if (this.type === 'bomb') {
// Red, yellow, orange for bomb sparks
particleColor = `hsl(${Math.random() * 30 + 30}, 100%, 50%)`; // Hues from 30 (orange) to 60 (yellow)
} else { // Mortar sparks
// Randomized random colors for mortar sparks
// Use full hue range (0-360), full saturation (100%), and mid-lightness (50%) for bright colors
particleColor = `hsl(${Math.random() * 360}, 100%, 50%)`;
}
this.fuseParticles.push({
x: fuseTipX, // Particles start exactly at the fuse tip
y: fuseTipY,
dx: Math.cos(particleAngle) * particleSpeed,
dy: Math.sin(particleAngle) * particleSpeed,
size: (Math.random() * 3 + 1) * window.scaleFactor,
opacity: 1,
color: particleColor
});
}
// Update existing particles
for (let i = this.fuseParticles.length - 1; i >= 0; i--) {
const p = this.fuseParticles[i];
p.x += p.dx;
p.y += p.dy;
p.opacity -= 0.05; // Fade out
p.size *= 0.95; // Shrink
if (p.opacity <= 0.1 || p.size <= 0.5) {
this.fuseParticles.splice(i, 1); // Remove faded particles
}
}
}
/**
* Draws the fuse and its particles.
*/
drawFuse() {
const scaledRadius = this.radius * window.scaleFactor;
const fuseWidth = 3 * window.scaleFactor;
// Calculate fuse start and end points
const fuseStartAngle = this.angle + Math.PI; // Opposite direction of travel
const fuseStartX = this.x + Math.cos(fuseStartAngle) * scaledRadius;
const fuseStartY = this.y + Math.sin(fuseStartAngle) * scaledRadius;
let currentFuseLength = (this.type === 'bomb' ? 3 : 2) * window.scaleFactor;
if (this.type === 'bomb' && audioContext && this.bombStartTime) {
const elapsed = audioContext.currentTime - this.bombStartTime;
currentFuseLength = ((this.type === 'bomb' ? 3 : 2) * window.scaleFactor) * (1 - (elapsed / this.explosionDelay));
currentFuseLength = Math.max(0, currentFuseLength);
}
const fuseEndX = fuseStartX + Math.cos(fuseStartAngle) * currentFuseLength;
const fuseEndY = fuseStartY + Math.sin(fuseStartAngle) * currentFuseLength;
// Draw the fuse line
ctx.strokeStyle = "#D2B48C"; // Tan color for fuse
ctx.lineWidth = fuseWidth;
ctx.beginPath();
ctx.moveTo(fuseStartX, fuseStartY);
ctx.lineTo(fuseEndX, fuseEndY);
ctx.stroke();
// Draw fuse particles (sparks)
this.fuseParticles.forEach(p => {
// Ensure color is parsed correctly from HSL string
const colorMatch = p.color.match(/hsl\((\d+),\s*(\d+)%,\s*(\d+)%\)/);
if (colorMatch) {
const h = parseInt(colorMatch[1]);
const s = parseInt(colorMatch[2]);
const l = parseInt(colorMatch[3]);
ctx.fillStyle = `hsla(${h}, ${s}%, ${l}%, ${p.opacity})`;
} else {
ctx.fillStyle = `rgba(255, 0, 0, ${p.opacity})`; // Fallback to red
}
ctx.beginPath();
ctx.arc(p.x, p.y, p.size / 2, 0, Math.PI * 2);
ctx.fill();
});
}
}
// --- Explosion Piece Class ---
class ExplosionPiece {
constructor(x, y, dx, dy, size, color, isChunk = false) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.size = size; // Scaled size
this.color = color;
this.opacity = 1;
this.rotation = Math.random() * Math.PI * 2;
this.rotationSpeed = (Math.random() - 0.5) * 0.2; // Random spin direction and speed
this.gravity = gravityValue * window.scaleFactor; // Inherit current gravity
this.isChunk = isChunk; // True if it's a black chunk
this.elasticity = isChunk ? 0.4 : 0.5; // Chunks might bounce a bit less
}
move() {
this.dy += this.gravity;
this.x += this.dx;
this.y += this.dy;
this.rotation += this.rotationSpeed;
// Chunks do not fade, other pieces fade
if (!this.isChunk) {
this.opacity -= 0.02;
}
}
draw() {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.rotation);
ctx.globalAlpha = Math.max(0, this.opacity); // Ensure opacity doesn't go below 0
ctx.fillStyle = this.color;
ctx.fillRect(-this.size / 2, -this.size / 2, this.size, this.size); // Draw a square piece
ctx.restore();
ctx.globalAlpha = 1; // Reset global alpha
}
}
/**
* Triggers an explosion effect at a given ball's position.
* @param {CannonBall} ball - The ball that is exploding.
*/
function triggerExplosion(ball) {
playExplosionSound();
const numFirePieces = 10 + Math.floor(Math.random() * 5); // 10-14 pieces
for (let j = 0; j < numFirePieces; j++) {
const speed = (Math.random() * 5 + 2) * window.scaleFactor;
const pieceAngle = Math.random() * Math.PI * 2;
let pieceColor;
if (ball.type === 'mortar') {
// Random bright colors for mortar explosions
pieceColor = `hsl(${Math.random() * 360}, 100%, 50%)`;
} else {
// Red to yellow colors for bombs (default fire)
pieceColor = `hsl(${Math.random() * 60}, 100%, 50%)`;
}
explosionPieces.push(new ExplosionPiece(
ball.x,
ball.y,
Math.cos(pieceAngle) * speed,
Math.sin(pieceAngle) * speed,
(Math.random() * 5 + 3) * window.scaleFactor,
pieceColor,
false // Not a chunk
));
}
if (ball.type === 'bomb') {
const numChunks = 5 + Math.floor(Math.random() * 3); // 5-7 black chunks
for (let j = 0; j < numChunks; j++) {
const chunkSpeed = (Math.random() * 8 + 4) * window.scaleFactor; // Higher force
const chunkAngle = Math.random() * Math.PI * 2;
explosionPieces.push(new ExplosionPiece(
ball.x,
ball.y,
Math.cos(chunkAngle) * chunkSpeed,
Math.sin(chunkAngle) * chunkSpeed,
(Math.random() * 8 + 5) * window.scaleFactor, // Larger chunk size
"#000000", // Black color
true // Mark as a chunk
));
}
}
}
/**
* Checks if a cannonball has hit any of the canvas borders and handles collision.
* @param {CannonBall} ball - The cannonball to check.
* @returns {boolean} True if the ball should be removed (e.g., mortar explosion), false otherwise.
*/
function ballHitWall(ball) {
const scaledRadius = ball.radius * window.scaleFactor;
const border = 20 * window.scaleFactor; // Scaled border size
const rightWall = canvas.width - border;
const leftWall = border;
const bottomWall = canvas.height - border;
const topWall = border;