JSFiddle - React, Tailwind, and code Playground
by accreditly
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pong Game</title>
<style>
/* Add CSS code here */
</style>
</head>
<body>
<canvas id="pong" width="600" height="400"></canvas>
<script>
// Add JavaScript code here
</script>
</body>
</html>
CSS
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #000;
}
canvas {
border: 1px solid #fff;
}
JavaScript
const canvas = document.getElementById('pong');
const ctx = canvas.getContext('2d');
canvas.addEventListener('mousemove', (e) => {
player.y = e.clientY - player.height / 2;
});
const player = {
x: 10,
y: canvas.height / 2 - 50,
width: 10,
height: 100,
color: '#fff',
};
const ai = {
x: canvas.width - 20,
y: canvas.height / 2 - 50,
width: 10,
height: 100,
color: '#fff',
};
const ball = {
x: canvas.width / 2,
y: canvas.height / 2,
radius: 8,
color: '#fff',
speed: 5,
velocityX: 5,
velocityY: 5,
};
function drawRect(x, y, width, height, color) {
ctx.fillStyle = color;
ctx.fillRect(x, y, width, height);
}
function drawBall(x, y, radius, color) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
}
function game() {
update();
render();
requestAnimationFrame(game);
}
function update() {
ball.x += ball.velocityX;
ball.y += ball.velocityY;
if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0) {
ball.velocityY = -ball.velocityY;
}
let paddle = ball.x < canvas.width / 2 ? player : ai;
if (collision(ball, paddle)) {
let angle = (Math.random() - 0.5) * Math.PI / 4;
ball.velocityX = -ball.velocityX * 1.1;
ball.velocityY = ball.speed * Math.sin(angle);
}
if (ball.x - ball.radius < 0) {
resetBall();
} else if (ball.x + ball.radius > canvas.width) {
resetBall();
}
ai.y += (ball.y - (ai.y + ai.height / 2)) * 0.1;
}
function collision(b, p) {
return (
b.x + b.radius > p.x &&
b.x - b.radius < p.x + p.width &&
b.y + b.radius > p.y &&
b.y - b.radius < p.y + p.height
);
}
function resetBall() {
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
ball.speed = 5;
ball.velocityX = -ball.velocityX;
ball.velocityY = (Math.random() - 0.5)...