generated from jade-city2/BeaconGames
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
115 lines (98 loc) · 2.07 KB
/
script.js
File metadata and controls
115 lines (98 loc) · 2.07 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
const canvas = document.getElementById("pongCanvas");
const ctx = canvas.getContext("2d");
canvas.width = 800;
canvas.height = 500;
// Paddle
const paddle = {
x: 30,
y: canvas.height / 2 - 50,
width: 10,
height: 100,
dy: 5
};
// Ball
const ball = {
x: canvas.width / 2,
y: canvas.height / 2,
radius: 8,
speed: 4,
dx: 4,
dy: 4
};
// Score
let score = 0;
// Draw paddle
function drawPaddle() {
ctx.fillStyle = "white";
ctx.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
}
// Draw ball
function drawBall() {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
ctx.fillStyle = "white";
ctx.fill();
ctx.closePath();
}
// Draw score
function drawScore() {
ctx.fillStyle = "white";
ctx.font = "20px Arial";
ctx.fillText("Score: " + score, 20, 30);
}
// Move paddle
document.addEventListener("keydown", (e) => {
if (e.key === "ArrowUp" && paddle.y > 0) {
paddle.y -= paddle.dy;
} else if (e.key === "ArrowDown" && paddle.y + paddle.height < canvas.height) {
paddle.y += paddle.dy;
}
});
// Move ball
function moveBall() {
ball.x += ball.dx;
ball.y += ball.dy;
// Bounce off top/bottom
if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0) {
ball.dy *= -1;
}
// Bounce off paddle
if (
ball.x - ball.radius < paddle.x + paddle.width &&
ball.y > paddle.y &&
ball.y < paddle.y + paddle.height
) {
ball.dx *= -1;
score++; // <-- Add score when ball hits paddle
}
// Reset if ball goes off screen (missed paddle)
if (ball.x - ball.radius < 0) {
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
ball.dx = 4;
ball.dy = 4;
score = 0; // Reset score when you lose
}
// Bounce off right wall
if (ball.x + ball.radius > canvas.width) {
ball.dx *= -1;
}
}
// Draw everything
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPaddle();
drawBall();
drawScore();
}
// Update game
function update() {
moveBall();
}
// Game loop
function loop() {
update();
draw();
requestAnimationFrame(loop);
}
loop();