-
Notifications
You must be signed in to change notification settings - Fork 0
/
breakout.js
455 lines (404 loc) · 12.7 KB
/
breakout.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
//play sound if giraffe is clicked
(function() {
let yahoo = new Audio('../sounds/yahoo.mp3');
let giraffe = document.getElementById('giraffe');
giraffe.addEventListener('click', function(){
giraffe.classList.remove('pulsate');
setTimeout(function(){
giraffe.classList.add('pulsate');
}, 0);
yahoo.play();
})
})();
/*****************************************************************
declare global variables
*****************************************************************/
//sounds
let ballCollide = new Audio('../sounds/click.mp3');
let brickCollide = new Audio('../sounds/collide.mp3');
let victory = new Audio('../sounds/victory.mp3');
let won = new Audio('../sounds/WON.mp3');
let loose = new Audio('../sounds/loose.mp3');
let died = new Audio('../sounds/died.mp3');
//dom elements
const canvas = document.getElementById('canvas');
const start = document.getElementById('start');
const restart = document.getElementById('restart');
const next = document.getElementById('next-level');
const context = canvas.getContext('2d');
/***************************
Canvas elements
**************************/
//ball position on canvas
let y = canvas.height - 30;
let x = canvas.width / 2;
//ball pixel movement/animation frame
let dx = 2;
let dy = -2;
//ball and paddle dimensions
let ballRad = 10;
let paddleH = 10;
let paddleW = 200;
let paddleX = (canvas.width - paddleW) / 2;
//brick size and layout parameters
let brickRow = 3;
let brickColumn = 5;
let brickW = 75;
let brickH = 20;
let brickPadding = 10;
let brickOffsetTop = 30;
let brickOffsetLeft = 30;
/***************************
States
**************************/
//key press state
let leftPressed = false;
let rightPressed = false;
//game start state
let gameStart = false;
//animation frame control
let startStopAnimation = false;
/***************************
Counters
**************************/
//score count
let score = 0;
//level count
let level = 1;
//lives count
let lives = 2;
/*****************************************************************
general purpose functions
*****************************************************************/
//show hide buttons
function toggleButtons(button) {
button === 'start' ? start.style.display = 'block' : start.style.display = 'none';
button === 'restart' ? restart.style.display = 'block' : restart.style.display = 'none';
button === 'next' ? next.style.display = 'block' : next.style.display = 'none';
}
//generate random colors
let colors = ['purple', 'green', 'red', 'orange', 'blue'];
let colorsInUse = colors[0];
function changeColor() {
colorsInUse = colors[Math.floor(Math.random() * colors.length)];
}
//add / remove event listeners depending on state
function handleEventListeners(state = true) {
//store event and event handler
let eventHandlers = [
['keydown', keyDownHandler],
['keyup', keyUpHandler],
['mousemove', mouseHandler],
['touchstart', touch2Mouse],
['touchmove', touch2Mouse],
['touchend', touch2Mouse]
];
//assign event handlers to events
eventHandlers.forEach(e => { //loop through eventHandlers
state === true ? document.addEventListener(e[0], e[1], false) //if true add
:
document.removeEventListener(e[0], e[1], false); // else remove
});
}
function reset() {
//cancel all event handlers
//handleEventListeners(false);
//reset ball position
x = canvas.width / 2;
y = canvas.height - 30;
//reset score
score = 0;
//reset animation state
startStopAnimation = false;
//reset brick state to allow rendering
for (let c = 0; c < brickColumn; c++) {
for (let r = 0; r < brickRow; r++) {
bricks[c][r].state = true;
}
}
}
/*****************************************************************
Bricks
*****************************************************************/
//generate bricks
let bricks = [];
for (let c = 0; c < brickColumn; c++) {
bricks[c] = [];
for (let r = 0; r < brickRow; r++) {
bricks[c][r] = {
x: 0,
y: 0,
state: true
};
}
}
//collision detection for bricks
function brickCollisionAction() {
for (let c = 0; c < brickColumn; c++) {
for (let r = 0; r < brickRow; r++) {
let b = bricks[c][r];
if (b.state == true) {
if (x > b.x && x < b.x + brickW && y > b.y && y < b.y + brickH) {
brickCollide.play();
dy = -dy;
b.state = false;
score++;
if (score >= brickColumn * brickRow) {
victory.play();
drawVictory();
}
}
}
}
}
}
/*****************************************************************
draw sprites
*****************************************************************/
//draw the ball
function ball() {
context.beginPath();
context.arc(x, y, ballRad, 0, Math.PI * 2, false);
context.fillStyle = colorsInUse;
context.fill();
context.closePath();
}
//draw the paddle
function paddle() {
context.beginPath();
context.rect(paddleX, canvas.height - paddleH, paddleW, paddleH);
context.fillStyle = 'green';
context.fill();
context.closePath();
}
//draw bricks
function drawBricks() {
for (let c = 0; c < brickColumn; c++) {
for (let r = 0; r < brickRow; r++) {
if (bricks[c][r].state == true) {
bricks[c][r].x = (c * (brickW + brickPadding)) + brickOffsetLeft;
bricks[c][r].y = (r * (brickH + brickPadding)) + brickOffsetTop;
context.beginPath();
context.rect(bricks[c][r].x, bricks[c][r].y, brickW, brickH);
context.fillStyle = 'red';
context.fill();
context.closePath();
}
}
}
}
/*****************************************************************
draw statistics and messages
*****************************************************************/
//draw the score
function drawScore() {
let text = 'Score: ' + score;
let left = canvas.width / 5;
context.font = '16px Arial';
context.fillStyle = 'green';
context.fillText(text, left, 20);
}
//draw number of lives
function drawLives() {
let right = canvas.width - (canvas.width / 4);
context.font = '16px Arial';
context.fillStyle = 'green';
context.fillText('Extra Lives: ' + lives, right, 20);
}
//draw level
function drawLevel() {
let center = canvas.width - (canvas.width / 2);
context.font = '16px Arial';
context.fillStyle = 'green';
context.fillText('Level: ' + level, center, 20);
}
//draw victory
function drawVictory() {
if (level < 7) {
let txt = 'Winner! You finished Level ' + level;
message(txt);
nextLevel();
} else if (level === 7) {
let txt = 'You are the new Jedi Grand Master';
message(txt);
restartGame();
//createButton(txtButton);
won.play();
}
}
function nextLevel() {
//remove all active event listeners
handleEventListeners(false);
toggleButtons('next');
next.addEventListener('click', function listen() {
reset(); //reset parameters
level += 1; //increase level
lives += 1; //add extra life
motion(); //start the game
//control level difficulty
level === 3 ? dx += 1 : null;
//increase speed
dx > 0 ? dx += 1 : dx -= 1;
dy < 0 ? dx -= 1 : dy += 1;
//decrease paddle width
paddleW -= 10;
next.removeEventListener('click', listen, false); //remove This event listener
handleEventListeners(); //activate event listeners for game control
})
}
function restartGame() {
handleEventListeners(false);
toggleButtons('restart');
restart.addEventListener('click', function() {
location.reload();
})
}
function startGame() {
handleEventListeners(false);
toggleButtons('start');
start.addEventListener('click', function() {
gameStart = true; //allow game to start
handleEventListeners(true);
motion(); //start the game
})
}
//draw game over
function drawGameOver() {
let txt = 'You lost at Level ' + level;
message(txt);
restartGame();
}
/*****************************************************************
message and button constructors
*****************************************************************/
//message constructor
function message(txt) {
//clear canvas
context.clearRect(0, 0, canvas.width, canvas.height);
//set style and text
context.font = '25px Arial';
context.fillStyle = 'red';
let center = (canvas.width - context.measureText(txt).width) / 2;
context.fillText(txt, center, canvas.height / 2);
//stop animation
startStopAnimation = true;
}
/*****************************************************************
Collision control
*****************************************************************/
//control collision with external walls and other elements
function collisionControl() {
//control collision with external walls
if (x + dx < ballRad || x + dx > canvas.width - ballRad) {
dx = -dx;
changeColor();
ballCollide.play();
}
if (y + dy < ballRad) {
dy = -dy;
changeColor();
ballCollide.play();
}
//collision control with the paddle
if (y + dy > canvas.height - ballRad) { //if ball is within the canvas
if (x > paddleX && x < paddleX + paddleW) { //if ball hits the paddle
dy = -dy;
ballCollide.play();
} else { //else if ball does not hit the paddle
if (lives > 0) { //if there are lives remaining
died.play();
lives--;
x = canvas.width / 2;
y = canvas.height - 30;
paddleX = (canvas.width - paddleW) / 2;
} else if (lives === 0) { //if there are no lives remaining
drawGameOver();
loose.play();
}
}
}
}
function movePaddle() { //set paddle in motion
leftPressed && paddleX > 0 ? paddleX -= 7 : null;
rightPressed && paddleX < (canvas.width - paddleW) ? paddleX += 7 : null;
}
/*****************************************************************
Event handlers
*****************************************************************/
function keyDownHandler(e) { //on key down
e.keyCode == 37 ? leftPressed = true : null;
e.keyCode == 39 ? rightPressed = true : null;
}
function keyUpHandler(e) { //on key up
e.keyCode == 37 ? leftPressed = false : null;
e.keyCode == 39 ? rightPressed = false : null;
}
function mouseHandler(e) { //mouse movement handler
let relativeX = e.clientX - canvas.offsetLeft;
if (relativeX > (paddleW / 2) && relativeX < canvas.width - (paddleW / 2)) {
paddleX = (relativeX - paddleW / 2);
}
}
function touch2Mouse(e) { //touch handle
let theTouch = e.changedTouches[0];
let mouseEv;
switch (e.type) //assign touch events to corresponding mouse events
{
case "touchstart":
mouseEv = "mousedown";
break;
case "touchend":
mouseEv = "mouseup";
break;
case "touchmove":
mouseEv = "mousemove";
break;
default:
return;
}
let mouseEvent = document.createEvent("MouseEvent");
mouseEvent.initMouseEvent(mouseEv, true, true, window, 1, theTouch.screenX, theTouch.screenY, theTouch.clientX, theTouch.clientY, false, false, false, false, 0, null);
theTouch.target.dispatchEvent(mouseEvent);
e.preventDefault();
}
/*****************************************************************
Animate canvas
*****************************************************************/
function motion() {
function animate() { //define animation function
if (startStopAnimation) return;
requestAnimationFrame(motion);
}
//clear canvas before drawing
context.clearRect(0, 0, canvas.width, canvas.height);
//draw sprites on canvas
drawBricks();
ball();
paddle();
//call collision detection functions
brickCollisionAction();
collisionControl();
//UI control
movePaddle();
//draw statistics
drawScore();
drawLives();
drawLevel();
//set ball in motion
x += dx;
y += dy;
//execute animation
animate();
};
/*****************************************************************
Initiate Game
*****************************************************************/
function initiate() {
startGame();
if (gameStart === true) {
handleEventListeners();
motion();
won.play();
}
}
initiate();