autonomous-pong / index.html
akhaliq's picture
akhaliq HF staff
Update index.html
f5d2385 verified
<!DOCTYPE html>
<html>
<head>
<title>Autonomous Pong</title>
<style>
canvas {
border: 1px solid black;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="800" height="400"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Game objects
const ball = {
x: canvas.width/2,
y: canvas.height/2,
radius: 10,
speedX: 5,
speedY: 5
};
const paddleWidth = 10;
const paddleHeight = 60;
const leftPaddle = {
x: 50,
y: canvas.height/2 - paddleHeight/2,
speed: 4
};
const rightPaddle = {
x: canvas.width - 50 - paddleWidth,
y: canvas.height/2 - paddleHeight/2,
speed: 4
};
// Game loop
function gameLoop() {
update();
draw();
requestAnimationFrame(gameLoop);
}
// Update game state
function update() {
// Move ball
ball.x += ball.speedX;
ball.y += ball.speedY;
// Ball collision with top and bottom
if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0) {
ball.speedY = -ball.speedY;
}
// Autonomous paddle movement
// Left paddle follows ball
if (ball.y > leftPaddle.y + paddleHeight/2) {
leftPaddle.y += leftPaddle.speed;
} else {
leftPaddle.y -= leftPaddle.speed;
}
// Right paddle follows ball
if (ball.y > rightPaddle.y + paddleHeight/2) {
rightPaddle.y += rightPaddle.speed;
} else {
rightPaddle.y -= rightPaddle.speed;
}
// Keep paddles within canvas
leftPaddle.y = Math.max(0, Math.min(canvas.height - paddleHeight, leftPaddle.y));
rightPaddle.y = Math.max(0, Math.min(canvas.height - paddleHeight, rightPaddle.y));
// Ball collision with paddles
if (
(ball.x - ball.radius < leftPaddle.x + paddleWidth &&
ball.y > leftPaddle.y &&
ball.y < leftPaddle.y + paddleHeight) ||
(ball.x + ball.radius > rightPaddle.x &&
ball.y > rightPaddle.y &&
ball.y < rightPaddle.y + paddleHeight)
) {
ball.speedX = -ball.speedX;
}
// Reset ball if it goes past paddles
if (ball.x < 0 || ball.x > canvas.width) {
ball.x = canvas.width/2;
ball.y = canvas.height/2;
ball.speedX = -ball.speedX;
}
}
// Draw game elements
function draw() {
// Clear canvas
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw ball
ctx.fillStyle = 'white';
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI*2);
ctx.fill();
// Draw paddles
ctx.fillRect(leftPaddle.x, leftPaddle.y, paddleWidth, paddleHeight);
ctx.fillRect(rightPaddle.x, rightPaddle.y, paddleWidth, paddleHeight);
// Draw center line
ctx.setLineDash([5, 15]);
ctx.beginPath();
ctx.moveTo(canvas.width/2, 0);
ctx.lineTo(canvas.width/2, canvas.height);
ctx.strokeStyle = 'white';
ctx.stroke();
ctx.setLineDash([]);
}
// Start the game
gameLoop();
</script>
</body>
</html>