Skip to main content

How to Create a Dynamic Pong Game in HTML, CSS, and JavaScript

Pong is a classic arcade game that has entertained players for decades. In this tutorial, we will guide you through creating a dynamic version of Pong using HTML, CSS, and JavaScript. This modern take on Pong will include real-time scoring, player controls, and a winning alert. Let’s get started!

Step 1: Setting Up the HTML

First, we need to set up the basic HTML structure. Create an HTML file with a <canvas> element where our game will be rendered. Here’s the basic HTML setup:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Pong Game</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <canvas id="pongCanvas"></canvas>
    <script src="script.js"></script>
</body>
</html>

Step 2: Styling with CSS

Next, style the canvas to center it on the page. Here’s the CSS you need:

body {
    margin: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background: #000;
}

canvas {
    background: #000;
}

Step 3: Adding Game Logic with JavaScript

Now, let’s add the JavaScript to bring the game to life. This script will handle player controls, scoring, and game mechanics:


// script.js
const canvas = document.getElementById("pongCanvas");
const ctx = canvas.getContext("2d");

canvas.width = 800;
canvas.height = 600;

// Paddle settings
const paddleWidth = 10;
const paddleHeight = 100;
const paddleSpeed = 10;

// Ball settings
const ballSize = 10;
const ballSpeed = 5;
const winningScore = 5; // Score to win the game

let leftPaddle = {
  x: 0,
  y: canvas.height / 2 - paddleHeight / 2,
  width: paddleWidth,
  height: paddleHeight,
  dy: 0,
};
let rightPaddle = {
  x: canvas.width - paddleWidth,
  y: canvas.height / 2 - paddleHeight / 2,
  width: paddleWidth,
  height: paddleHeight,
  dy: 0,
};
let ball = {
  x: canvas.width / 2,
  y: canvas.height / 2,
  size: ballSize,
  dx: ballSpeed,
  dy: ballSpeed,
};

// Player Names
const player1Name = "Player 1";
const player2Name = "Player 2";

// Control Key Names
const player1Controls = "W (Up) / S (Down)";
const player2Controls = "Arrow Up (Up) / Arrow Down (Down)";

// Scores
let player1Score = 0;
let player2Score = 0;

// Draw Paddle
function drawPaddle(paddle) {
  ctx.fillStyle = "#fff";
  ctx.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
}

// Draw Ball
function drawBall() {
  ctx.beginPath();
  ctx.arc(ball.x, ball.y, ball.size, 0, Math.PI * 2);
  ctx.fillStyle = "#f00"; // Red color for the ball
  ctx.fill();
  ctx.closePath();
}

// Draw Scores
function drawScores() {
  ctx.fillStyle = "#fff";
  ctx.font = "30px Arial";
  ctx.textAlign = "left";
  ctx.fillText(`${player1Name}: ${player1Score}`, 20, 40);
  ctx.textAlign = "right";
  ctx.fillText(`${player2Name}: ${player2Score}`, canvas.width - 20, 40);
}

// Draw Player Names and Controls
function drawInfo() {
  ctx.fillStyle = "#fff";
  ctx.font = "20px Arial";
  ctx.textAlign = "left";
  ctx.fillText(`${player1Name}: ${player1Controls}`, 20, 70);
  ctx.textAlign = "right";
  ctx.fillText(`${player2Name}: ${player2Controls}`, canvas.width - 20, 70);
}

// Update Paddle Position
function updatePaddle(paddle) {
  if (
    paddle.y + paddle.dy >= 0 &&
    paddle.y + paddle.dy + paddle.height <= canvas.height
  ) {
    paddle.y += paddle.dy;
  }
}

// Update Ball Position
function updateBall() {
  ball.x += ball.dx;
  ball.y += ball.dy;

  // Ball collision with top/bottom
  if (
    ball.y + ball.dy < ball.size ||
    ball.y + ball.dy > canvas.height - ball.size
  ) {
    ball.dy = -ball.dy;
  }

  // Ball collision with paddles
  if (
    (ball.x - ball.size < leftPaddle.x + leftPaddle.width &&
      ball.y > leftPaddle.y &&
      ball.y < leftPaddle.y + leftPaddle.height) ||
    (ball.x + ball.size > rightPaddle.x &&
      ball.y > rightPaddle.y &&
      ball.y < rightPaddle.y + rightPaddle.height)
  ) {
    ball.dx = -ball.dx;
  }

  // Ball out of bounds
  if (ball.x + ball.dx < 0) {
    player2Score++;
    resetBall();
  }
  if (ball.x + ball.dx > canvas.width) {
    player1Score++;
    resetBall();
  }

  // Check for game over
  if (player1Score >= winningScore || player2Score >= winningScore) {
    const winner = player1Score >= winningScore ? player1Name : player2Name;
    alert(`${winner} wins!`);
    // Reset scores and restart the game
    player1Score = 0;
    player2Score = 0;
  }
}

// Reset Ball Position
function resetBall() {
  ball.x = canvas.width / 2;
  ball.y = canvas.height / 2;
  ball.dx = -ball.dx;
}

// Control Paddle Movement
document.addEventListener("keydown", (e) => {
  if (e.key === "w") leftPaddle.dy = -paddleSpeed;
  if (e.key === "s") leftPaddle.dy = paddleSpeed;
  if (e.key === "ArrowUp") rightPaddle.dy = -paddleSpeed;
  if (e.key === "ArrowDown") rightPaddle.dy = paddleSpeed;
});

document.addEventListener("keyup", (e) => {
  if (e.key === "w" || e.key === "s") leftPaddle.dy = 0;
  if (e.key === "ArrowUp" || e.key === "ArrowDown") rightPaddle.dy = 0;
});

// Game Loop
function gameLoop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawPaddle(leftPaddle);
  drawPaddle(rightPaddle);
  drawBall();
  drawScores();
  drawInfo();
  updatePaddle(leftPaddle);
  updatePaddle(rightPaddle);
  updateBall();
  requestAnimationFrame(gameLoop);
}

gameLoop();

    

In this code, we handle the ball and paddle movements, scoring, and determine the game’s winner. You can adjust the controls and game settings as needed.

Conclusion

With these steps, you’ve created a dynamic Pong game that features real-time scoring and player controls. Enjoy your game and feel free to modify it to add more features or improve its design!

For the complete JavaScript code, check out our [GitHub repository](#). Happy coding!

Comments

Popular posts from this blog

Creating an Interactive Tic Tac Toe Game

In this tutorial, we'll walk through the steps to create a dynamic Tic Tac Toe game using HTML, CSS, and JavaScript. This classic game is a great way to practice your web development skills and learn more about interactive web applications. HTML Structure We'll start with the HTML structure, which includes the game board, a reset button, and a status display: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Tic Tac Toe</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="container"> <h1>Tic Tac Toe</h1> <div id="board" class="board"></div> <button id="reset">Reset Game</button> <div id=...

Creating a Simple Car Racing Game with HTML, CSS, Javascript

In this post, we will create a simple car racing game using HTML, CSS, and JavaScript. This game will feature a player car, an opponent car, and a score counter. The player can move their car left and right to avoid collisions with the opponent car. Let's dive into the code! HTML Structure The HTML structure consists of a game area that contains the road, player car, opponent car, and score display: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Car Racing Game</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="gameArea"> <div class="road"></div> <div class="playerCar"></div> <div class="opponentCar"></div...

Create Your Own Chrome Dino Game with HTML, CSS, and JavaScript

Have you ever wanted to create your own version of the Chrome Dino game? With just a few lines of HTML, CSS, and JavaScript, you can bring this iconic game to life. Here's a step-by-step guide to building a simple yet fun version of the Dino game. HTML Start by creating an HTML file to define the game structure. You'll need a container for the game, a <div> for the dinosaur, another <div> for the cactus, and a score display. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Chrome Dino Game</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="game-container"> <div id="dino" class="dino"></div> <div id="cactus" class="cactus...