-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJavaScript File
85 lines (70 loc) · 1.76 KB
/
JavaScript File
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
const canvas = document.getElementById("pong");
const ctx = canvas.getContext("2d");
const paddleWidth = 10;
const paddleHeight = 100;
const ballSize = 10;
const player = {
x: 20,
y: canvas.height / 2 - paddleHeight / 2,
width: paddleWidth,
height: paddleHeight,
dy: 4,
};
const computer = {
x: canvas.width - 20 - paddleWidth,
y: canvas.height / 2 - paddleHeight / 2,
width: paddleWidth,
height: paddleHeight,
};
const ball = {
x: canvas.width / 2,
y: canvas.height / 2,
size: ballSize,
dx: 4,
dy: 4,
};
function drawPaddle(x, y, width, height, color = "white") {
ctx.fillStyle = color;
ctx.fillRect(x, y, width, height);
}
function drawBall(x, y, size, color = "white") {
ctx.fillStyle = color;
ctx.fillRect(x, y, size, size);
}
function movePaddle() {
player.y += player.dy;
if (player.y < 0) player.y = 0;
if (player.y + paddleHeight > canvas.height) player.y = canvas.height - paddleHeight;
}
function moveComputer() {
let paddleCenter = computer.y + paddleHeight / 2;
if (paddleCenter < ball.y - 35) {
computer.y += computer.dy;
} else if (paddleCenter > ball.y + 35) {
computer.y -= computer.dy;
}
}
function moveBall() {
ball.x += ball.dx;
ball.y += ball.dy;
if (ball.y < 0 || ball.y + ball.size > canvas.height) {
ball.dy *= -1;
}
if (ball.x < 0) {
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
}
if (ball.x + ball.size > canvas.width) {
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
}
let playerPaddle = ball.x < canvas.width / 2;
let paddle = playerPaddle ? player : computer;
if (collision(ball, paddle)) {
ball.dx *= -1;
}
}
function collision(ball, paddle) {
return (
ball.x + ball.size > paddle.x &&
ball.x < paddle.x + paddle.width}