-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
364 lines (323 loc) · 11.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
// Get DOM elements
const gameBoard = document.getElementById('game-board');
const paddle = document.getElementById('paddle');
const ball = document.getElementById('ball');
let scoreDisplay = document.getElementById('score');
let livesDisplay = document.getElementById('lives');
let timerDisplay = document.getElementById('timer');
let gameOver = true;
let isPaused = true;
let start = true;
let lives ;
let score;
//timer display
let startTime;
let intervalId;
let timerPaused = false;
let pausedTime = 0;
class Brick {
color;
constructor(xAxis, yAxis) {
this.x = xAxis;
this.y = yAxis;
}
}
const brickWidth = 119;
const brickHeight = 30;
let bricks = [];
const ballStart = [360, 399]
let ballCurrentPosition = ballStart
let ballDirectionX = 1;
let ballDirectionY = -1;
let ballSpeed = 2;
const paddleStart = [313, 410]
let paddleCurrentPosition = paddleStart
let previousTime = performance.now();
let pauseTime = null;
let animationFrameId;
document.addEventListener('keydown', (event) => {
if (event.key === 'ArrowLeft') {
movePaddleLeft();
} else if (event.key === 'ArrowRight') {
movePaddleRight();
} else if (event.key === 'Enter') {
resetGame();
initializeGame();
} else if (event.key === ' ' || event.key === 'Space') {
if (!document.getElementById('win-menu').classList.contains('hidden')) {
document.getElementById('win-menu').classList.add('hidden');
document.getElementById('pause-menu').classList.add('hidden');
resetGame();
}
if (gameOver === true) {
document.getElementById('game-over-menu').classList.add('hidden');
initializeGame()
gameOver = false;
} else {
if (start === true) {
start = false
isPaused = false
}else {
toggleMenu('pause-menu'); //pauseTimer() called in toggleMenu()
}
}
}// else if (event.key === 'k') {
// gameOver = true;
// toggleMenu('win-menu');
// }
});
function startTimer() {
if (!startTime) {
startTime = new Date().getTime();
timerPaused = false;
intervalId = setInterval(updateTimer, 10); // Update every 10 milliseconds
}
}
function pauseTimer() {
if (!timerPaused) {
pausedTime = new Date().getTime() - startTime;
clearInterval(intervalId);
} else {
startTime = new Date().getTime() - pausedTime;
intervalId = setInterval(updateTimer, 10);
}
timerPaused = !timerPaused;
}
function resetTimer() {
startTime = null;
timerPaused = false;
pausedTime = 0;
clearInterval(intervalId);
timerDisplay.textContent = 'Time: 00:00.000';
}
function updateTimer() {
if (!timerPaused) {
const currentTime = new Date().getTime();
const elapsedTime = currentTime - startTime;
const milliseconds = elapsedTime % 1000;
const seconds = Math.floor(elapsedTime / 1000) % 60;
const minutes = Math.floor(elapsedTime / 60000);
timerDisplay.textContent = `Time: ${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${milliseconds.toString().padStart(3, '0')}`;
}
}
function movePaddleLeft() {
paddleCurrentPosition[0] -= 15;
if (paddleCurrentPosition[0] < 0) {
paddleCurrentPosition[0] = 0;
}
}
function movePaddleRight() {
paddleCurrentPosition[0] += 15;
const maxPosition = gameBoard.clientWidth - paddle.clientWidth;
if (paddleCurrentPosition[0] > maxPosition) {
paddleCurrentPosition[0] = maxPosition;
}
}
// Update game state
// Game loop
function gameLoop() {
if (isPaused) {
if (pauseTime === null) {
pauseTime = performance.now();
cancelAnimationFrame(animationFrameId);
}
} else {
startTimer();
// Calculate time since last frame
if (pauseTime !== null) {
previousTime += performance.now() - pauseTime;
pauseTime = null;
}
const deltaTime = performance.now() - previousTime;
previousTime = performance.now();
if (gameOver === true) {
cancelAnimationFrame(animationFrameId);
return;
}
// Update game state
update(deltaTime);
// Render game elements
render();
}
animationFrameId = requestAnimationFrame(gameLoop);
}
function update(deltaTime) {
ballSpeed *= 1.0003;
// Update ball position
ballCurrentPosition[0] += ballDirectionX * ballSpeed * deltaTime / 16;
ballCurrentPosition[1] += ballDirectionY * ballSpeed * deltaTime / 16;
// Handle collisions with walls
if (ballCurrentPosition[0] <= 0 || ballCurrentPosition[0] >= gameBoard.clientWidth - ball.clientWidth) {
ballDirectionX *= -1; // Reverse ball's X direction
}
if (ballCurrentPosition[1] <= 0) {
ballDirectionY *= -1; // Reverse ball's Y direction
}
// Handle collisions with paddle
if (
ballCurrentPosition[1] + ball.clientHeight >= gameBoard.clientHeight - 40 &&
ballCurrentPosition[0] + ball.clientWidth >= paddleCurrentPosition[0] &&
ballCurrentPosition[0] <= paddleCurrentPosition[0] + paddle.clientWidth
) {
ballDirectionY *= -1; // Reverse ball's Y direction
} else if (ballCurrentPosition[0] + ball.clientWidth >= paddleCurrentPosition[0] &&
ballCurrentPosition[0] <= paddleCurrentPosition[0] + paddle.clientWidth &&
ballCurrentPosition[1] + ball.clientHeight >= gameBoard.clientHeight - paddle.clientHeight) {
ballDirectionX *= -1; // Reverse ball's X direction
}
for (let i = 0; i < bricks.length; i++){
const brick = bricks[i];
const ballCenterX = ballCurrentPosition[0] + ball.clientWidth / 2;
const ballCenterY = ballCurrentPosition[1] + ball.clientHeight / 2;
const brickCenterX = brick.x + brickWidth / 2;
const brickCenterY = brick.y + brickHeight / 2;
const deltaX = ballCenterX - brickCenterX;
const deltaY = ballCenterY - brickCenterY;
if
(
// Collision with top or bottom of the brick
(Math.abs(deltaY) < brickHeight / 2 + ball.clientHeight / 2) &&
(Math.abs(deltaX) < brickWidth / 2)
||
// Collision with left or right side of the brick
(Math.abs(deltaX) < brickWidth / 2 + ball.clientWidth / 2) &&
(Math.abs(deltaY) < brickHeight / 2))
{
const allBlocks = Array.from(document.querySelectorAll('.brick'))
if (brick.color === "orange"){
brick.color = "green"
const brickElement = document.getElementsByClassName('brick')[i];
brickElement.style.backgroundColor = brick.color;
} else if (brick.color === "green"){
brick.color = "blue"
const brickElement = document.getElementsByClassName('brick')[i];
brickElement.style.backgroundColor = brick.color;
} else {
//allBlocks[i].classList.remove('brick');
allBlocks[i].remove();
bricks.splice(i,1);
}
if ((Math.abs(deltaY) < brickHeight / 2 + ball.clientHeight / 2) &&
(Math.abs(deltaX) < brickWidth / 2)) {
ballDirectionY *= -1; // Reverse ball's Y direction
} else {
ballDirectionX *= -1; // Reverse ball's X direction
}
score += 200;
scoreDisplay.innerHTML = "Score: " + score.toString();
if (bricks.length === 0) {
scoreDisplay.innerHTML = 'You Win!'
toggleMenu('win-menu');
//document.removeEventListener('keydown', gameLoop)
}
}
}
// Check game over condition
if (ballCurrentPosition[1] >= gameBoard.clientHeight - ball.clientHeight){
// Player loses a life
start = true;
ballSpeed = 2;
lives--;
document.getElementById('lives').innerHTML = "Lives: " + lives.toString();
if (lives <= 0) {
// Game over logic (to be implemented)
console.log("Game over!");
toggleMenu('game-over-menu');
gameOver = true;
} else {
// Reset ball position and direction
paddleCurrentPosition = [313, 410]
ballCurrentPosition = [360, 399]
ballDirectionX = 1;
ballDirectionY = -1;
render();
isPaused = true;
}
}
}
function resetGame() {
//timerDisplay.textContent = '<%RESET%>';
paddleCurrentPosition = [313, 410]
ballCurrentPosition = [360, 399]
ballDirectionX = 1;
ballDirectionY = -1;
score = 0;
lives = 5;
scoreDisplay.innerHTML = "Score: " + score.toString()
document.getElementById('lives').innerHTML = "Lives: " + lives.toString();
const brickElements = document.querySelectorAll('.brick');
brickElements.forEach(brickElement => {
brickElement.remove();
});
bricks = [];
renderBricks(generateBricks());
render();
resetTimer();
isPaused = true;
}
// Render game elements
function render() {
// Update paddle's CSS position
paddle.style.left = `${paddleCurrentPosition[0]}px`;
paddle.style.top = `${paddleCurrentPosition[1]}px`;
// Update ball's CSS position
ball.style.left = `${ballCurrentPosition[0]}px`;
ball.style.top = `${ballCurrentPosition[1]}px`;
}
function toggleMenu(type) {
const pauseMenu = document.getElementById(type);
const isHidden = pauseMenu.classList.contains('hidden');
pauseTimer();
if (isHidden) {
pauseMenu.classList.remove('hidden');
isPaused = true; // Pause the game loop
} else {
pauseMenu.classList.add('hidden');
isPaused = false; // Resume the game loop
}
}
function generateBricks() {
// // Generate bricks
const brickRows = 4;
const brickColumns = 6;
const brickGap = 10;
for (let i = 0; i < brickRows; i++) {
for (let j = 0; j < brickColumns; j++) {
let brick = new Brick(j * (brickWidth) + brickGap, i * (brickHeight) + brickGap);
if (i === 3){
brick.color = "orange";
} else if (i === 2){
brick.color = "green";
} else if (i <= 1){
brick.color = "blue";
}
bricks.push(brick);
}
}
return bricks;
}
function renderBricks(bricks) {
bricks.forEach(brick => {
const brickElement = document.createElement('div');
brickElement.classList.add('brick');
brickElement.style.left = `${brick.x}px`;
brickElement.style.top = `${brick.y}px`;
brickElement.style.backgroundColor = brick.color;
gameBoard.appendChild(brickElement);
});
paddle.style.left = `${paddleCurrentPosition[0]}px`;
paddle.style.top = `${paddleCurrentPosition[1]}px`;
ball.style.left = `${ballCurrentPosition[0]}px`;
ball.style.top = `${ballCurrentPosition[1]}px`;
}
function initializeGame() {
const winMenu = document.getElementById("win-menu");
winMenu.classList.add('hidden');
resetGame();
gameLoop();
}
//initializeGame();
while (gameOver === true) {
gameOver = false;
initializeGame();
}