WEB APP GENERATOR
Feed
Active: none
Key ready
Login
Guest
Ping Pong Game
ddd • Jan 28, 2026 7:31 PM
A simple interactive ping pong game where you control a paddle to keep the ball in play.
Prompt
create a pingpong game
HTML
<div class="game-container">
    <canvas id="gameCanvas" width="800" height="400"></canvas>
</div>
CSS
body {
    margin: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background-color: #222;
}

.game-container {
    position: relative;
}

canvas {
    background-color: #000;
    border: 2px solid #fff;
}
JS
(() => {
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');
    const paddleHeight = 10;
    const paddleWidth = 75;
    let paddleX = (canvas.width - paddleWidth) / 2;
    let rightPressed = false;
    let leftPressed = false;
    const ballRadius = 10;
    let x = canvas.width / 2;
    let y = canvas.height - 30;
    let dx = 2;
    let dy = -2;

    document.addEventListener('keydown', keyDownHandler, false);
    document.addEventListener('keyup', keyUpHandler, false);

    function keyDownHandler(event) {
        if (event.key === 'Right' || event.key === 'ArrowRight') {
            rightPressed = true;
        } else if (event.key === 'Left' || event.key === 'ArrowLeft') {
            leftPressed = true;
        }
    }

    function keyUpHandler(event) {
        if (event.key === 'Right' || event.key === 'ArrowRight') {
            rightPressed = false;
        } else if (event.key === 'Left' || event.key === 'ArrowLeft') {
            leftPressed = false;
        }
    }

    function drawBall() {
        ctx.beginPath();
        ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
        ctx.fillStyle = '#fff';
        ctx.fill();
        ctx.closePath();
    }

    function drawPaddle() {
        ctx.beginPath();
        ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight);
        ctx.fillStyle = '#fff';
        ctx.fill();
        ctx.closePath();
    }

    function draw() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        drawBall();
        drawPaddle();

        if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
            dx = -dx;
        }
        if (y + dy < ballRadius) {
            dy = -dy;
        } else if (y + dy > canvas.height - ballRadius) {
            if (x > paddleX && x < paddleX + paddleWidth) {
                dy = -dy;
            } else {
                document.location.reload();
            }
        }

        if (rightPressed && paddleX < canvas.width - paddleWidth) {
            paddleX += 7;
        } else if (leftPressed && paddleX > 0) {
            paddleX -= 7;
        }

        x += dx;
        y += dy;
        requestAnimationFrame(draw);
    }

    draw();
})();

Comments (0)

Log in to comment.
Working...