Template:Pong
Jump to navigation
Jump to search
This is the "Pong" template. To use it, call it like this:
<canvas id="pongCanvas-1" width="800" height="400" style="border: 1px solid black; display: block; margin: 0 auto;"></canvas>
Left: 0 | Right: 0
<script> (function() {
const gameId = '1';
const canvas = document.getElementById('pongCanvas-' + gameId);
const ctx = canvas.getContext('2d');
const scoreBoard = document.getElementById('scoreBoard-' + gameId);
const ball = {
x: canvas.width / 2,
y: canvas.height / 2,
radius: 10,
dx: 4,
dy: 4
};
const paddle = {
width: 10,
height: 100,
speed: 5
};
const leftPaddle = Object.assign({}, paddle, { x: 0, y: canvas.height / 2 - 50 });
const rightPaddle = Object.assign({}, paddle, { x: canvas.width - 10, y: canvas.height / 2 - 50 });
let leftScore = 0; let rightScore = 0;
const keys = {
w: false,
s: false,
ArrowUp: false,
ArrowDown: false
};
document.addEventListener('keydown', (e) => {
if (e.key in keys) {
keys[e.key] = true;
}
});
document.addEventListener('keyup', (e) => {
if (e.key in keys) {
keys[e.key] = false;
}
});
function movePaddles() {
if (keys.w) {
leftPaddle.y = Math.max(0, leftPaddle.y - leftPaddle.speed);
}
if (keys.s) {
leftPaddle.y = Math.min(canvas.height - paddle.height, leftPaddle.y + leftPaddle.speed);
}
if (keys.ArrowUp) {
rightPaddle.y = Math.max(0, rightPaddle.y - rightPaddle.speed);
}
if (keys.ArrowDown) {
rightPaddle.y = Math.min(canvas.height - paddle.height, rightPaddle.y + rightPaddle.speed);
}
}
function moveBall() {
ball.x += ball.dx;
ball.y += ball.dy;
if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0) {
ball.dy *= -1;
}
if (
(ball.x - ball.radius < leftPaddle.x + paddle.width && ball.y > leftPaddle.y && ball.y < leftPaddle.y + paddle.height) ||
(ball.x + ball.radius > rightPaddle.x && ball.y > rightPaddle.y && ball.y < rightPaddle.y + paddle.height)
) {
ball.dx *= -1;
}
if (ball.x < 0) {
rightScore++;
resetBall();
} else if (ball.x > canvas.width) {
leftScore++;
resetBall();
}
updateScoreBoard(); }
function resetBall() {
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
ball.dx = -ball.dx;
}
function updateScoreBoard() {
scoreBoard.textContent = `Left: ${leftScore} | Right: ${rightScore}`;
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
ctx.fillStyle = 'black';
ctx.fill();
ctx.closePath();
ctx.fillStyle = 'black';
ctx.fillRect(leftPaddle.x, leftPaddle.y, paddle.width, paddle.height);
ctx.fillRect(rightPaddle.x, rightPaddle.y, paddle.width, paddle.height);
}
function gameLoop() {
movePaddles();
moveBall();
draw();
requestAnimationFrame(gameLoop);
}
gameLoop();
})(); </script>
Parameters:
- width - Width of the game canvas (default: 800)
- height - Height of the game canvas (default: 400)