Pong
Pong
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pong Game for Two Players</title>
<style>
body,
html {
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: black;
}
canvas {
border: 1px solid white;
}
</style>
</head>
<body>
<canvas id="pongCanvas"></canvas>
<script>
const canvas = document.getElementById('pongCanvas');
const ctx = canvas.getContext('2d');
canvas.width = 600;
canvas.height = 400;
const player1 = {
x: 10,
y: canvas.height / 2 - 40,
width: 10,
height: 80,
dy: 0,
score: 0
};
const player2 = {
x: canvas.width - 20,
y: canvas.height / 2 - 40,
width: 10,
height: 80,
dy: 0,
score: 0
};
const ball = {
x: canvas.width / 2,
y: canvas.height / 2,
radius: 7,
speed: 5,
dx: 5,
dy: 5
};
function drawNet() {
for (let i = 0; i <= canvas.height; i += 20) {
drawRect(canvas.width / 2 - 1, i, 2, 10, 'WHITE');
}
}
function draw() {
drawRect(0, 0, canvas.width, canvas.height, 'BLACK'); // background
drawNet();
drawRect(player1.x, player1.y, player1.width, player1.height, 'WHITE'); //
player1
drawRect(player2.x, player2.y, player2.width, player2.height, 'WHITE'); //
player2
drawCircle(ball.x, ball.y, ball.radius, 'WHITE'); // ball
}
return player.left < ball.right && player.top < ball.bottom && player.right >
ball.left && player.bottom > ball.top;
}
function resetBall() {
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
ball.dx = -ball.dx;
ball.speed = 5;
}
function update() {
if (gameStarted) {
ball.x += ball.dx;
ball.y += ball.dy;
player1.y += player1.dy;
if (player1.y < 0) player1.y = 0;
else if (player1.y + player1.height > canvas.height) player1.y =
canvas.height - player1.height;
player2.y += player2.dy;
if (player2.y < 0) player2.y = 0;
else if (player2.y + player2.height > canvas.height) player2.y =
canvas.height - player2.height;
}
}
function drawScore() {
context.font = '35px Arial';
context.fillStyle = 'white';
context.fillText(player1.score, canvas.width / 4, 50);
context.fillText(player2.score, 3 * canvas.width / 4, 50);
}
function restartGame() {
// Resetar as pontuações
player1.score = 0;
player2.score = 0;
// Atualizar a exibição das pontuações, se aplicável
// Esta é uma função hipotética para atualizar as pontuações na tela
function gameLoop() {
draw();
update();
if (player1.score === 10) {
alert("Player 1 wins!");
document.location.reload();
restartGame();
} else if (player2.score === 10) {
alert("Player 2 wins!");
document.location.reload();
restartGame();
}
requestAnimationFrame(gameLoop);
}
</html>