-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
837 lines (700 loc) · 24.2 KB
/
script.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
const CANVAS_WIDTH = 400;
const CANVAS_HEIGHT = 500;
const NUM_BRICKS_PER_ROW = 14;
const BRICK_GAP = 2;
const WALL_WIDTH = 10; // Wall width
const BRICK_WIDTH = (CANVAS_WIDTH - (WALL_WIDTH * 2) - (BRICK_GAP * (NUM_BRICKS_PER_ROW - 1))) / NUM_BRICKS_PER_ROW;
const BRICK_HEIGHT = 16;
const PADDLE_WIDTH = BRICK_WIDTH * 2;
const PADDLE_HEIGHT = BRICK_HEIGHT / 2;
const ORIGINAL_BALL_SIZE = 5;
const bricks = [];
const canvas = document.getElementById('game');
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
const context = canvas.getContext('2d');
const LVL1 = [
[],
[],
[],
[],
[],
[],
['C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C'],
['R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R', 'R'],
['O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'],
['Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y'],
['G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G'],
['L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L'],
['B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B'],
['F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'F']
];
const LVL2 = [
[],
[],
['C', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'],
['X', 'R', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'],
['X', 'X', 'O', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'],
['X', 'X', 'X', 'Y', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'],
['X', 'X', 'X', 'X', 'G', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'],
['X', 'X', 'X', 'X', 'X', 'L', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'],
['X', 'X', 'X', 'X', 'X', 'X', 'B', 'X', 'X', 'X', 'X', 'X', 'X', 'X'],
['X', 'X', 'X', 'X', 'X', 'X', 'X', 'F', 'X', 'X', 'X', 'X', 'X', 'X']
];
const LVL3 = [
[],
['X', 'F', 'X', 'X', 'X', 'X', 'X', 'F', 'X', 'X', 'X', 'X', 'X', 'X'],
['F', 'X', 'F', 'X', 'X', 'X', 'F', 'X', 'F', 'X', 'X', 'X', 'X', 'X'],
['X', 'F', 'X', 'C', 'X', 'C', 'X', 'F', 'X', 'F', 'X', 'X', 'X', 'X'],
['F', 'X', 'F', 'P', 'C', 'P', 'F', 'X', 'F', 'X', 'F', 'X', 'X', 'X'],
['X', 'F', 'X', 'C', 'X', 'C', 'X', 'F', 'X', 'F', 'X', 'F', 'X', 'X'],
['F', 'X', 'F', 'X', 'C', 'X', 'F', 'X', 'F', 'X', 'F', 'X', 'X', 'X'],
['X', 'F', 'X', 'C', 'X', 'C', 'X', 'F', 'X', 'F', 'X', 'X', 'X', 'X'],
['F', 'X', 'F', 'X', 'C', 'X', 'F', 'X', 'F', 'X', 'X', 'X', 'X', 'X'],
['X', 'F', 'X', 'C', 'X', 'C', 'X', 'F', 'X', 'X', 'X', 'X', 'X', 'X'],
['X', 'X', 'F', 'X', 'C', 'X', 'F', 'X', 'X', 'X', 'X', 'X', 'X', 'X'],
['X', 'X', 'X', 'C', 'X', 'C', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'],
['X', 'X', 'X', 'X', 'C', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X']
];
// Map color names to characters for ease-of-change
const colorMap = {
'C': '#800020', //CRIMSON
'R': '#B33D26', //RED
'O': '#DE754C', //ORANGE
'Y': '#DDA46F', //YELLOW
'G': '#789F90', //GREEN
'L': '#387F97', //LIGHTBLUE
'B': '#236192', //DARKBLUE
'F': '#2C3968', //FORDBLUE
'P': 'lightgrey' //PADDLE COLOR
};
const paddle = {
x: canvas.width / 2 - PADDLE_WIDTH / 2,
y: 440,
width: PADDLE_WIDTH,
height: PADDLE_HEIGHT,
dx: 0 // Paddle x velocity
};
const ball = {
x: canvas.width / 2,
y: 260,
width: 5,
height: 5,
speed: 3,
dx: 0, // Ball x velocity
dy: 0 // Ball y velocity
};
/////////////////////////////////
/// MUTATORS AND ACCESSORS
////////////////////////////
const ORIGINAL_BALL_SPEED = ball.speed;
const ORIGINAL_PADDLE_WIDTH = paddle.width;
function setPaddlePosition(horizontalPosition, verticalPosition) {
paddle.x = horizontalPosition;
paddle.y = verticalPosition;
}
function setPaddleWidth(newWidth) { paddle.width = newWidth; }
function getOriginalPaddleWidth() { return ORIGINAL_PADDLE_WIDTH; }
function setBallPosition(horizontalPosition, verticalPosition) {
ball.x = horizontalPosition;
ball.y = verticalPosition;
}
function setBallSpeed(newSpeed) {
let ratioX = ball.dx / ball.speed;
let ratioY = ball.dy / ball.speed;
ball.speed = newSpeed;
// Adjust dx and dy based on the new speed while maintaining direction
ball.dx = ratioX * ball.speed;
ball.dy = ratioY * ball.speed;
}
function setBallSize(newSize) {
ball.height = newSize;
ball.width = newSize;
}
/////////////////////////////////
/// GAME FUNCTIONS
////////////////////////////
let currentLevel = 1;
function createGameGrid(level) {
for (let row = 0; row < level.length; row++) {
for (let col = 0; col < level[row].length; col++) {
const colorCode = level[row][col];
if (colorCode !== 'X') {
bricks.push({
x: WALL_WIDTH + (BRICK_WIDTH + BRICK_GAP) * col,
y: WALL_WIDTH + (BRICK_HEIGHT + BRICK_GAP) * row,
color: colorMap[colorCode],
width: BRICK_WIDTH,
height: BRICK_HEIGHT
});
}
}
}
setLevelNumber(level);
updateLevelText(currentLevel);
}
function setLevelNumber(level) {
switch (level) {
case LVL1:
currentLevel = 1;
break;
case LVL2:
currentLevel = 2;
break;
case LVL3:
currentLevel = 3;
break;
}
}
function updateLevelText(newLevel) {
var levelElement = document.getElementById('level');
levelElement.textContent = 'LEVEL ' + newLevel;
}
function getCurrentLevelGrid() {
switch (currentLevel) {
case 1:
return LVL1;
break;
case 2:
return LVL2;
break;
case 3:
return LVL3;
break;
}
}
// Check for collision between two objects using axis-aligned bounding box (AABB)
function collides(obj1, obj2) {
return obj1.x < obj2.x + obj2.width &&
obj1.x + obj1.width > obj2.x &&
obj1.y < obj2.y + obj2.height &&
obj1.y + obj1.height > obj2.y;
}
function updateScore() {
const scoreElement = document.getElementById('score');
scoreElement.textContent = `Score: ${score}`;
// Increase ball speed every 20 points
if (score % 20 == 0) {
updateBallSpeed();
}
}
function updateBallSpeed() {
const speedIncreaseFactor = 1.3;
ball.speed *= speedIncreaseFactor;
// Update the ball's velocity components based on the new speed
// Preserve the direction of the ball while updating speed
ball.dx = (ball.dx / Math.abs(ball.dx)) * ball.speed;
ball.dy = (ball.dy / Math.abs(ball.dy)) * ball.speed;
}
function showGameOver() {
const gameOverElement = document.getElementById('game-over');
gameOverElement.style.display = 'block'; // Display the Game Over text
}
function hideGameOver() {
const gameOverElement = document.getElementById('game-over');
gameOverElement.style.display = 'none';
}
function showWinScreen() {
const gameOverElement = document.getElementById('winner');
gameOverElement.style.display = 'block'; // Display the Game Over text
}
function hideWinScreen() {
const gameOverElement = document.getElementById('winner');
gameOverElement.style.display = 'none';
}
// When initializing or resetting the ball's position and movement
function resetBall() {
ball.x = canvas.width / 2;
ball.y = paddle.y - ball.height; // Position the ball just above the paddle
ball.speed = 1;
ball.dx = ball.speed * (Math.random() < 0.5 ? -1 : 1); // Randomize left or right direction
ball.dy = -ball.speed; // Always move up
}
function resetPaddle() {
paddle.x = canvas.width / 2 - PADDLE_WIDTH / 2;
paddle.y = 440;
width: PADDLE_WIDTH;
height: PADDLE_HEIGHT;
dx: 0;
}
//////////////////////////////
/// GAME LOOP
/////////////////////////
const POWERUP_CHANCE = 0.6;
const POWERUP_COOLDOWN = 3;
const WIDE_BAR_DURATION = 6;
const SLOW_BALL_DURATION = 3;
const BIG_BALL_DURATION = 6;
// Global flags for each powerup
let slowBallActive = false;
let widePaddleActive = false;
let powerupActive = false;
let bigBallActive = false;
let powerupDuration = 0;
let powerupCooldown = POWERUP_COOLDOWN;
let widePaddleDuration = 0;
let slowBallDuration = 0;
let bigBallDuration = 0;
let previousBallSpeed = 1;
let score = 0;
let isGameOver = false;
let isPaused = false;
createGameGrid(LVL1);
loop();
function loop() {
if (!isGameOver && !isPaused) {
// Ensure next frame is scheduled before current frame logic is processed for smoother animations
requestAnimationFrame(loop);
context.clearRect(0, 0, canvas.width, canvas.height);
// Move Paddle and Paddle
movePaddle();
moveBall()
// Check Ball Collision
checkBallPaddleCollision();
checkBallBrickCollision();
// Draw Walls
drawWalls();
// Draw Ball
drawBall();
// Draw Bricks
drawBricks();
// Draw Paddle
drawPaddle();
// Check Remaining Bricks
if (bricks.length == 0) {
isGameOver = true;
}
}
else if (isPaused) {
// Render the pause menu
showPauseMenu();
}
else {
if (bricks.length == 0) {
showWinScreen();
}
else {
showGameOver();
}
}
}
function showPauseMenu() {
// Create an offscreen canvas
let offscreenCanvas = document.createElement('canvas');
offscreenCanvas.width = canvas.width;
offscreenCanvas.height = canvas.height;
let offscreenContext = offscreenCanvas.getContext('2d');
// Draw the current game state to the offscreen canvas
offscreenContext.drawImage(canvas, 0, 0);
// Draw the blurred image back to the main canvas
context.drawImage(offscreenCanvas, 0, 0);
// Semi-transparent overlay
context.fillStyle = 'rgba(0, 0, 0, 0.7)';
context.fillRect(0, 0, canvas.width, canvas.height);
// Draw the pause menu text
context.fillStyle = '#FFFFFF';
context.font = '18px "Press Start 2P", cursive';
context.textAlign = 'center';
context.fillText('Level Selection', canvas.width / 2, 150);
context.fillText('1. Level 1', canvas.width / 2, 200);
context.fillText('2. Level 2', canvas.width / 2, 250);
context.fillText('3. Level 3', canvas.width / 2, 300);
}
function showStartMessage() {
// Create an offscreen canvas
let offscreenCanvas = document.createElement('canvas');
offscreenCanvas.width = canvas.width;
offscreenCanvas.height = canvas.height;
let offscreenContext = offscreenCanvas.getContext('2d');
// Draw the current game state to the offscreen canvas
offscreenContext.drawImage(canvas, 0, 0);
// Set text properties
context.fillStyle = '#FFFFFF'; // White color for text
context.font = '18px "Press Start 2P", cursive'; // Your desired font
context.textAlign = 'center';
context.textBaseline = 'middle'; // Align text in the middle vertically
// Draw the text at the center of the canvas
context.fillText('-- Press Spacebar To Start --', canvas.width / 2, canvas.height / 2);
}
//////////////////////////////
/// GAME FUNCTIONS
/////////////////////////
// Add: 1. AI OVERRIDE 2. MULTI-BALL
const POWERUP_TYPES = {
WIDER_BAR: 'wider_bar',
SLOW_BALL: 'slow_ball',
BIG_BALL: 'big_ball'
}
function movePaddle() {
paddle.x += paddle.dx;
// Collision with walls
if (paddle.x < WALL_WIDTH) {
paddle.x = WALL_WIDTH;
}
else if (paddle.x + paddle.width > canvas.width - WALL_WIDTH) {
paddle.x = canvas.width - WALL_WIDTH - paddle.width;
}
}
function moveBall() {
ball.x += ball.dx;
ball.y += ball.dy;
// Wall collision logic
// Left & Right walls
if (ball.x < WALL_WIDTH || ball.x + ball.width > canvas.width - WALL_WIDTH) {
ball.dx *= -1;
}
// Top wall
if (ball.y < WALL_WIDTH) {
ball.dy *= -1;
}
// Reset ball if it goes below the screen
if (ball.y > canvas.height) {
isGameOver = true;
}
}
function checkBallPaddleCollision() {
// If ball collides with paddle, change y velocity
if (collides(ball, paddle)) {
ball.dy *= -1;
ball.y = paddle.y - ball.height;
}
}
function checkBallBrickCollision() {
let collisionOccurred = false;
for (let i = 0; i < bricks.length && !collisionOccurred; i++) {
const brick = bricks[i];
if (collides(ball, brick)) {
// Remove brick from the bricks array
bricks.splice(i, 1);
// Increment score
++score;
updateScore();
// Decrement Powerup Cooldown
--powerupCooldown;
// Update Powerup Gauge
updatePowerupGauge();
// Check For Powerup Chance
checkForRandomPowerupChance();
// Calculate where the ball hit the brick
const ballBottom = ball.y + ball.height;
const ballTop = ball.y;
const brickBottom = brick.y + brick.height;
const brickTop = brick.y;
const ballCenterX = ball.x + ball.width / 2;
const ballCenterY = ball.y + ball.height / 2;
const brickCenterX = brick.x + brick.width / 2;
const brickCenterY = brick.y + brick.height / 2;
// Determine the side of the collision
const hitVertical = Math.abs(ballCenterX - brickCenterX) < brick.width / 2;
const hitHorizontal = Math.abs(ballCenterY - brickCenterY) < brick.height / 2;
// Ball hits the brick from the bottom or top
if (hitVertical && !hitHorizontal) {
ball.dy *= -1;
}
// Ball hits the brick from the side
else if (hitHorizontal && !hitVertical) {
ball.dx *= -1;
}
// Corner hit, reflect both axes
else {
ball.dx *= -1;
ball.dy *= -1;
}
collisionOccurred = true;
}
}
}
function getRandomPowerup() {
const keys = Object.keys(POWERUP_TYPES);
const randomIndex = Math.floor(Math.random() * keys.length);
return POWERUP_TYPES[keys[randomIndex]];
}
function displayPowerupText(text) {
const powerupTextElement = document.getElementById('powerupText');
powerupTextElement.textContent = text;
powerupTextElement.style.display = 'block';
setTimeout(() => powerupTextElement.style.display = 'none', 5000); // Hide the text after 5 seconds
}
function checkForRandomPowerupChance() {
if (Math.random() < POWERUP_CHANCE && !powerupActive && powerupCooldown === 0) {
powerupActive = true; // Global flag indicating a powerup is active
let selectedPowerup = getRandomPowerup();
// Activate the selected powerup and set the respective flag
if (selectedPowerup === POWERUP_TYPES.SLOW_BALL && !slowBallActive) {
powerupDuration = SLOW_BALL_DURATION;
previousBallSpeed = ball.speed;
setBallSpeed(ball.speed / 2);
slowBallActive = true; // Set the slow ball flag
displayPowerupText('SLOWWWW');
}
else if (selectedPowerup === POWERUP_TYPES.WIDER_BAR && !widePaddleActive) {
powerupDuration = WIDE_BAR_DURATION;
setPaddleWidth(paddle.width * 2);
widePaddleActive = true; // Set the wide paddle flag
displayPowerupText('WIDE PADDLE');
}
else if (selectedPowerup === POWERUP_TYPES.BIG_BALL && !bigBallActive) {
powerupDuration = BIG_BALL_DURATION;
setBallSize(12);
bigBallActive = true; // Set the wide paddle flag
displayPowerupText('BIG BALL');
}
powerupCooldown = POWERUP_COOLDOWN;
}
}
function updatePowerupGauge() {
if (powerupDuration > 0) {
// Decrease the duration of the wide paddle powerup
if (widePaddleActive) {
--powerupDuration;
}
--powerupDuration;
if (powerupDuration === 0) {
if (widePaddleActive) {
setPaddleWidth(getOriginalPaddleWidth()); // Reset paddle width
widePaddleActive = false;
}
if (slowBallActive) {
setBallSpeed(previousBallSpeed); // Reset ball speed
//ball.speed = previousBallSpeed;
slowBallActive = false;
}
if (bigBallActive) {
setBallSize(ORIGINAL_BALL_SIZE); // Reset ball speed
bigBallActive = false;
}
powerupCooldown = POWERUP_COOLDOWN;
}
}
powerupActive = widePaddleActive || slowBallActive || bigBallActive;
}
function drawWalls() {
context.fillStyle = colorMap['P'];
context.fillRect(0, 0, canvas.width, WALL_WIDTH);
context.fillRect(0, 0, WALL_WIDTH, canvas.height);
context.fillRect(canvas.width - WALL_WIDTH, 0, WALL_WIDTH, canvas.height);
}
function drawBall() {
if (ball.dx || ball.dy) {
context.fillRect(ball.x, ball.y, ball.width, ball.height);
}
}
function drawBricks() {
bricks.forEach(function (brick) {
context.fillStyle = brick.color;
context.fillRect(brick.x, brick.y, brick.width, brick.height);
});
}
function drawPaddle() {
context.fillStyle = colorMap['P'];
context.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
}
function resetGame(levelSelection) {
// Reset Score
score = 0;
updateScore();
// Reset the game state flags
isGameOver = false;
isPaused = false;
slowBallActive = false;
widePaddleActive = false;
bigBallActive = false;
powerupActive = false;
powerupDuration = 0;
powerupCooldown = POWERUP_COOLDOWN;
widePaddleDuration = 0;
slowBallDuration = 0;
bigBallDuration = 0;
// Reset any powerups if active
setBallSpeed(ORIGINAL_BALL_SPEED);
setPaddleWidth(ORIGINAL_PADDLE_WIDTH);
// Hide the Game Over Text
hideGameOver();
hideWinScreen();
// Repopulate the bricks array for a new game
bricks.length = 0; // Clear the existing bricks;
createGameGrid(levelSelection);
// Reset Ball Position/Velocity
resetBall();
resetPaddle();
// Restart the game loop
requestAnimationFrame(loop);
}
//////////////////////////////
/// DIRECTIONAL MOTION
/////////////////////////
let leftArrowPressed = false;
let rightArrowPressed = false;
document.addEventListener('keydown', function (e) {
if (e.key === 'ArrowLeft') {
leftArrowPressed = true;
paddle.dx = -3;
}
if (e.key === 'ArrowRight') {
rightArrowPressed = true;
paddle.dx = 3;
}
if (ball.dx === 0 && ball.dy === 0 && e.key === ' ') {
resetBall();
}
});
// Stop paddle movement when keys are released
document.addEventListener('keyup', function (e) {
if (e.key === 'ArrowLeft') {
leftArrowPressed = false;
}
if (e.key === 'ArrowRight') {
rightArrowPressed = false;
}
if (!leftArrowPressed && !rightArrowPressed) {
paddle.dx = 0;
}
});
document.addEventListener('keydown', function (e) {
if (e.key === " " && isGameOver) { // If spacebar is pressed and the game is over
resetGame(getCurrentLevelGrid());
}
});
document.addEventListener('keydown', function (event) {
if (event.key === 'Enter') {
isPaused = !isPaused;
if (!isPaused) {
// Resume the game
requestAnimationFrame(loop);
}
}
else if (isPaused) {
if (event.key === '1') {
// Load level
isPaused = false; // Unpause the game
resetGame(LVL1);
}
else if (event.key === '2') {
// Load level 2
isPaused = false; // Unpause the game
resetGame(LVL2);
}
else if (event.key === '3') {
// Load level 3
isPaused = false; // Unpause the game
resetGame(LVL3);
}
}
});
//////////////////////////////
/// MOBILE SUPPORT
/////////////////////////
canvas.addEventListener('touchstart', handleTouchStart, false);
canvas.addEventListener('touchmove', handleTouchMove, false);
canvas.addEventListener('touchend', handleTouchEnd, false);
let gameStarted = false;
// Listen for touchstart events on the canvas
canvas.addEventListener('touchstart', function (e) {
// Get the touch coordinates
const touchX = e.touches[0].clientX;
const touchY = e.touches[0].clientY;
// Adjust touch coordinates for canvas position
const canvasRect = canvas.getBoundingClientRect();
const canvasScaleX = canvas.width / canvasRect.width; // scale factor for width
const canvasScaleY = canvas.height / canvasRect.height; // scale factor for height
const canvasTouchX = (touchX - canvasRect.left) * canvasScaleX;
const canvasTouchY = (touchY - canvasRect.top) * canvasScaleY;
// Check if the touch is within the paddle's bounds
if (
canvasTouchX >= paddle.x &&
canvasTouchX <= paddle.x + paddle.width &&
canvasTouchY >= paddle.y &&
canvasTouchY <= paddle.y + paddle.height
) {
// If the game hasn't started, start the game
if (!gameStarted) {
gameStarted = true;
resetBall(); // Start the ball movement
loop(); // Start the game loop
}
}
}, false);
let lastTouchX;
function handleTouchStart(e) {
const touch = e.touches[0];
lastTouchX = touch.clientX;
e.preventDefault(); // Prevent scrolling when touching the canvas
}
function handleTouchMove(e) {
const touch = e.touches[0];
const deltaX = touch.clientX - lastTouchX;
lastTouchX = touch.clientX;
// Move paddle based on the change in touch position
paddle.x += deltaX;
// Prevent the paddle from going out of bounds
if (paddle.x < WALL_WIDTH) {
paddle.x = WALL_WIDTH;
} else if (paddle.x + paddle.width > canvas.width - WALL_WIDTH) {
paddle.x = canvas.width - WALL_WIDTH - paddle.width;
}
e.preventDefault();
}
function handleTouchEnd(e) {
// Stop paddle movement when touch ends
paddle.dx = 0;
e.preventDefault();
}
// Get the level element
const levelElement = document.getElementById('level');
// Attach a touchstart event listener to the level element
levelElement.addEventListener('touchstart', function (e) {
// Prevent default behavior
e.preventDefault();
// Handling level selection logic
// You can toggle between levels or show a level selection menu here
// For simplicity, let's just cycle through levels 1, 2, and 3
if (levelElement.textContent.includes("1")) {
resetGame(LVL2);
levelElement.textContent = "LEVEL 2";
}
else if (levelElement.textContent.includes("2")) {
resetGame(LVL3);
levelElement.textContent = "LEVEL 3";
}
else if (levelElement.textContent.includes("3")) {
resetGame(LVL1);
levelElement.textContent = "LEVEL 1";
}
// Resume the game if paused
if (isPaused) {
isPaused = false;
requestAnimationFrame(loop);
}
}, false);
canvas.addEventListener('touchstart', function (e) {
if (isGameOver) {
const touchX = e.touches[0].clientX;
const touchY = e.touches[0].clientY;
const canvasRect = canvas.getBoundingClientRect();
const canvasScaleX = canvas.width / canvasRect.width;
const canvasScaleY = canvas.height / canvasRect.height;
const canvasTouchX = (touchX - canvasRect.left) * canvasScaleX;
const canvasTouchY = (touchY - canvasRect.top) * canvasScaleY;
// Check if the touch is within the paddle's bounds
if (
canvasTouchX >= paddle.x &&
canvasTouchX <= paddle.x + paddle.width &&
canvasTouchY >= paddle.y &&
canvasTouchY <= paddle.y + paddle.height
) {
// Restart the game
resetGame(getCurrentLevelGrid());
isGameOver = false; // Reset the game over state
}
}
e.preventDefault();
}, false);
window.addEventListener('deviceorientation', handleTilt);
function handleTilt(e) {
// Get the device tilt from the event
const gamma = e.gamma; // Represents the left to right tilt in degrees
// Set the paddle velocity based on the tilt
// You may need to adjust the sensitivity to get the desired responsiveness
const sensitivity = 1.5;
paddle.dx = gamma * sensitivity;
}