How to Create a Ping Pong Game with HTML, CSS and JavaScript (Source code)

Faraz

By Faraz -

Learn how to create your own Ping Pong game using HTML, CSS, and JavaScript. This tutorial will guide you step-by-step on how to build a game board, ball, paddles, and add movement and collision detection to create a fully functional game.


how to create a ping pong game with html, css and javascript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

Ping Pong is a classic game that has been enjoyed for generations. It is a fast-paced, competitive game that requires skill, strategy, and quick reflexes. In this tutorial, we will guide you step-by-step on how to create your own Ping Pong game using HTML, CSS, and JavaScript.

Creating a Ping Pong game is a great way to learn game development, web game development, game programming, and game design. By following this tutorial, you will gain a better understanding of how HTML, CSS, and JavaScript can be used together to create interactive web applications.

Throughout the tutorial, we will cover the basics of HTML, CSS, and JavaScript, as well as more advanced concepts such as movement, collision detection, and game logic. By the end of this tutorial, you will have a fully functional Ping Pong game that you can play with friends and family.

So, let's get started and create our own Ping Pong game!

Join My Telegram Channel to Download the Source Code: Click Here

Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our ping pong game.

After creating the files just paste the following below codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

The code starts with a document type declaration that specifies the version of HTML being used.

The <html> tag encloses the entire document and serves as the root element. The <head> tag contains information about the document such as the title of the page, links to CSS files, and scripts. The <title> tag sets the title of the page which appears in the browser's title bar.

The <link> tag is used to link to external files, in this case, the Bootstrap CSS file which provides styling for the page. The <style> tag contains CSS code that sets a black border around the <canvas> element.

The <body> tag contains the content of the page, which includes a <div> container that holds a <canvas> element where the game is played. There are also three buttons, a message modal, and a paragraph that provides instructions on how to control the game.

The buttons have unique IDs and the <script> tag at the bottom of the file links to a JavaScript file that handles the functionality of the buttons. The <div> container that holds the buttons has a class called "button" that can be used for styling purposes.

The message modal is hidden by default but can be triggered by JavaScript code when certain events occur in the game. It has an ID of "message-modal" and contains a header and a footer with a close button.

Finally, the HTML file includes two external JavaScript files, jQuery and Bootstrap, and a custom JavaScript file called "script.js" that contains the game logic.

This is the basic structure of our ping pong game using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the ping pong game is in place, the next step is to add styling to the game using CSS. CSS allows us to control the visual appearance of the website, including things like layout, color, and typography.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our game.

The first section of the code targets the .container class and sets it to a flex container with a column layout. The align-items and justify-content properties center the content both horizontally and vertically.

The .button class is used to style the container that holds the game control buttons. It's also set to a flex container with justify-content property to center its child elements horizontally. The margin-top property adds some space between the container and the content above it.

The .btn class targets all the buttons and styles them with a green background color, white text, and no border. The padding property sets the amount of space inside the button, and the margin property sets the space around the button. The cursor property changes the cursor style when hovering over the button. The border-radius property adds rounded corners to the button.

The :hover pseudo-class is used to change the background color of the button when the mouse cursor hovers over it.

The .control class styles the paragraph that contains the game instructions with centered text.

The canvas element is styled with a black background color.

This will give our ping pong game an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.button{
  display: flex;
  justify-content: center;
  margin-top: 15px;
}

.btn {
  background-color: #4caf50;
  border: none;
  color: white;
  padding: 10px 20px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 10px;
  cursor: pointer;
  border-radius: 5px;
}

.btn:hover {
  background-color: #3e8e41;
}

.control {
	text-align: center;
}

canvas {
  background: #000;
} 

Step 3 (JavaScript Code):

Finally, we need to create a function of the ping pong game in JavaScript.

The code uses HTML5 canvas to draw the game elements such as the ball, paddles, and scores. Here is a brief explanation of the code:

The first part of the code initializes the canvas and defines the buttons and their corresponding event listeners. The start button starts the game, the pause button pauses the game, and the restart button restarts the game.

The next part of the code defines the properties of the ball, paddles, and score. It also listens for keyboard events for controlling the paddles.

The update() function updates the game state by moving the paddles, the ball, and checking for collisions. It also updates the scores and checks for a winning condition.

The playerWin() function displays a message modal when a player wins and resets the game.

The reset() function resets the ball to the center of the screen and changes its speed and direction.

The draw() function draws the game elements such as the ball, paddles, and scores on the canvas. It also clears the canvas before drawing the new frame.

Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

// Initialize canvas
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var startBtn = document.getElementById("start-btn");
var pauseBtn = document.getElementById("pause-btn");
var restartBtn = document.getElementById("restart-btn");
var animationId;
var gameRunning = false;

startBtn.addEventListener("click", function() {
  if (!gameRunning) { // only start the game if gameRunning is false
    gameRunning = true; // set gameRunning to true when the game starts
    loop();
  }
});

pauseBtn.addEventListener("click", function() {
  gameRunning = false;
  cancelAnimationFrame(animationId);
});

restartBtn.addEventListener("click", function() {
  document.location.reload();
});

addEventListener("load", (event) => {
  draw();
});


// Define ball properties
var ballRadius = 10;
var ballX = canvas.width / 2;
var ballY = canvas.height / 2;
var ballSpeedX = 5;
var ballSpeedY = 5;

// Define paddle properties
var paddleHeight = 80;
var paddleWidth = 10;
var leftPaddleY = canvas.height / 2 - paddleHeight / 2;
var rightPaddleY = canvas.height / 2 - paddleHeight / 2;
var paddleSpeed = 10;

// Define score properties
var leftPlayerScore = 0;
var rightPlayerScore = 0;
var maxScore = 10;

// Listen for keyboard events
document.addEventListener("keydown", keyDownHandler);
document.addEventListener("keyup", keyUpHandler);

// Handle key press
var upPressed = false;
var downPressed = false;
let wPressed = false;
let sPressed = false;

function keyDownHandler(e) {
  if (e.key === "ArrowUp") {
    upPressed = true;
  } else if (e.key === "ArrowDown") {
    downPressed = true;
  } else if (e.key === "w") {
    wPressed = true;
  } else if (e.key === "s") {
    sPressed = true;
  }
}

// Handle key release
function keyUpHandler(e) {
  if (e.key === "ArrowUp") {
    upPressed = false;
  } else if (e.key === "ArrowDown") {
    downPressed = false;
  } else if (e.key === "w") {
    wPressed = false;
  } else if (e.key === "s") {
    sPressed = false;
  }
}

// Update game state
function update() {
  // Move paddles
  if (upPressed && rightPaddleY > 0) {
    rightPaddleY -= paddleSpeed;
  } else if (downPressed && rightPaddleY + paddleHeight < canvas.height) {
    rightPaddleY += paddleSpeed;
  }

  // Move right paddle based on "w" and "s" keys
  if (wPressed && leftPaddleY > 0) {
    leftPaddleY -= paddleSpeed;
  } else if (sPressed && leftPaddleY + paddleHeight < canvas.height) {
    leftPaddleY += paddleSpeed;
  }

  // Move right paddle automatically based on ball position
  // if (ballY > rightPaddleY + paddleHeight / 2) {
  //   rightPaddleY += paddleSpeed;
  // } else if (ballY < rightPaddleY + paddleHeight / 2) {
  //   rightPaddleY -= paddleSpeed;
  // }

  // Move ball
  ballX += ballSpeedX;
  ballY += ballSpeedY;

  // Check if ball collides with top or bottom of canvas
  if (ballY - ballRadius < 0 || ballY + ballRadius > canvas.height) {
    ballSpeedY = -ballSpeedY;
  }

  // Check if ball collides with left paddle
  if (
    ballX - ballRadius < paddleWidth &&
    ballY > leftPaddleY &&
    ballY < leftPaddleY + paddleHeight
  ) {
    ballSpeedX = -ballSpeedX;
  }

  // Check if ball collides with right paddle
  if (
    ballX + ballRadius > canvas.width - paddleWidth &&
    ballY > rightPaddleY &&
    ballY < rightPaddleY + paddleHeight
  ) {
    ballSpeedX = -ballSpeedX;
  }

  // Check if ball goes out of bounds on left or right side of canvas
  if (ballX < 0) {
    rightPlayerScore++;
    reset();
  } else if (ballX > canvas.width) {
    leftPlayerScore++;
    reset();
  }

  // Check if a player has won
  if (leftPlayerScore === maxScore) {
    playerWin("Left player");
  } else if (rightPlayerScore === maxScore) {
    playerWin("Right player");
  }
}

function playerWin(player) {
  var message = "Congratulations! " + player + " win!";
  $('#message').text(message); // Set the message text
  $('#message-modal').modal('show'); // Display the message modal
  reset();
}

// Reset ball to center of screen
function reset() {
  ballX = canvas.width / 2;
  ballY = canvas.height / 2;
  ballSpeedX = -ballSpeedX;
  ballSpeedY = Math.random() * 10 - 5;
}

// Draw objects on canvas
function draw() {
  // Clear canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  ctx.fillStyle = "#FFF";
  ctx.font = "15px Arial";

  ctx.beginPath();
  ctx.moveTo(canvas.width / 2, 0);
  ctx.lineTo(canvas.width / 2, canvas.height);
  ctx.strokeStyle = "#FFF"; // Set line color to white
  ctx.stroke();
  ctx.closePath();

  // Draw ball
  ctx.beginPath();
  ctx.arc(ballX, ballY, ballRadius, 0, Math.PI * 2);
  ctx.fill();
  ctx.closePath();

  // Draw left paddle
  ctx.fillRect(0, leftPaddleY, paddleWidth, paddleHeight);

  // Draw right paddle
  ctx.fillRect(canvas.width - paddleWidth, rightPaddleY, paddleWidth, paddleHeight);

  // Draw scores
  ctx.fillText("Score: " + leftPlayerScore, 10, 20);
  ctx.fillText("Score: " + rightPlayerScore, canvas.width - 70, 20);
}

// Game loop
function loop() {
  update();
  draw();
  animationId = requestAnimationFrame(loop);
}

$('#message-modal-close').on('click', function() {
  document.location.reload();
});

Final Output:

how to create a ping pong game with html, css and javascript.gif

See the Pen Untitled by Faraz (@codewithfaraz) on CodePen.

Conclusion:

Congratulations! You have successfully created your own Ping Pong game using HTML, CSS, and JavaScript. By following this tutorial, you have gained a better understanding of game development, web game development, game programming, and game design.

We started by creating the game board, ball, and paddles using HTML and CSS. Then, we added movement and collision detection using JavaScript to create a fully functional game.

Creating a Ping Pong game is just the beginning. You can continue to build upon your game by adding more features such as sound effects, multiple levels, and multiplayer options.

Remember to keep practicing and experimenting with different ideas to continue to develop your skills. With the knowledge gained from this tutorial, you can create even more complex and interactive games in the future.

We hope you had fun creating your Ping Pong game and that you continue to explore the exciting world of game development.

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺