canvas.width = 800;
canvas.height = 600;
let paddleWidth = 10, paddleHeight = 100, ballSize = 10;
let playerY = (canvas.height - paddleHeight) / 2;
let aiY = (canvas.height - paddleHeight) / 2;
let ballX = canvas.width / 2 - ballSize / 2;
let ballY = canvas.height / 2 - ballSize / 2;
let ballSpeedX = 5, ballSpeedY = 5;
let playerScore = 0, aiScore = 0;
let level = 1;
function drawRect(x, y, w, h, color) {
context.fillStyle = color;
context.fillRect(x, y, w, h);
}
function drawCircle(x, y, r, color) {
context.fillStyle = color;
context.beginPath();
context.arc(x, y, r, 0, Math.PI * 2, false);
context.closePath();
context.fill();
}
function drawText(text, x, y, color) {
context.fillStyle = color;
context.font = "32px Arial";
context.fillText(text, x, y);
}
function resetBall() {
ballX = canvas.width / 2 - ballSize / 2;
ballY = canvas.height / 2 - ballSize / 2;
ballSpeedX = 5 * (Math.random() > 0.5 ? 1 : -1);
ballSpeedY = 5 * (Math.random() > 0.5 ? 1 : -1);
level += 1;
ballSpeedX += level;
ballSpeedY += level;
}
function game() {
update();
render();
}
function update() {
// Move the ball
ballX += ballSpeedX;
ballY += ballSpeedY;
// AI Paddle movement
if (aiY + paddleHeight / 2 < ballY) {
aiY += 6;
} else {
aiY -= 6;
}
// Ball collision with top and bottom walls
if (ballY <= 0 || ballY + ballSize >= canvas.height) {
ballSpeedY = -ballSpeedY;
}
// Ball collision with paddles
if (ballX <= paddleWidth) {
if (ballY > playerY && ballY < playerY + paddleHeight) {
ballSpeedX = -ballSpeedX;
} else {
aiScore++;
resetBall();
}
}
if (ballX + ballSize >= canvas.width - paddleWidth) {
if (ballY > aiY && ballY < aiY + paddleHeight) {
ballSpeedX = -ballSpeedX;
} else {
playerScore++;
resetBall();
}
}
// Player Paddle movement
document.addEventListener('mousemove', function(evt) {
let rect = canvas.getBoundingClientRect();
playerY = evt.clientY - rect.top - paddleHeight / 2;
});
}
function render() {
// Clear the canvas
drawRect(0, 0, canvas.width, canvas.height, '#00008b'); // Azul celeste oscuro
// Draw paddles and ball
drawRect(0, playerY, paddleWidth, paddleHeight, 'white');
drawRect(canvas.width - paddleWidth, aiY, paddleWidth, paddleHeight, 'white');
drawCircle(ballX, ballY, ballSize / 2, 'white');
// Draw the net
for (let i = 0; i < canvas.height; i += 30) {
drawRect(canvas.width / 2 - 1, i, 2, 20, 'white');
}
// Draw the scores
drawText(playerScore, canvas.width / 4, canvas.height / 5, 'white');
drawText(aiScore, 3 * canvas.width / 4, canvas.height / 5, 'white');
}
// Start the game loop
setInterval(game, 1000 / 60);
// Fullscreen functionality
canvas.addEventListener('click', function() {
if (!document.fullscreenElement) {
canvas.requestFullscreen().catch(err => {
alert(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`);
});
} else {
document.exitFullscreen();
}
});