Creating Pong Game Using HTML CSS Javascript

pong gaming using html css javascript

Introduction:

Welcome to the world of game development! Have you ever wanted to create your own video game? Well, you’re in luck because today we’re going to learn how to build a classic game called Pong using three essential web technologies: HTML, CSS, and JavaScript.

Pong is a simple but fun game where two players control paddles on opposite sides of the screen. The goal is to hit a ball back and forth, trying to make the other player miss it. It’s like virtual ping-pong!

In this tutorial, we’ll guide you through the process of creating your own Pong game from scratch. Don’t worry if you’re new to programming or game development – we’ll explain everything step by step in a simple and easy-to-understand way.

By the end of this tutorial, you’ll have your very own playable Pong game that you can share with your friends or even customize to make it your own. So let’s get started and have some fun building our own Pong game together!

Code Explanation:

Let’s break down the provided code:

HTML Structure:

  • The HTML file starts with the usual <!DOCTYPE html> declaration and <html>, <head>, and <body> tags.
  • Within the <head>, there’s a <style> block defining the CSS styles for the canvas element.

Canvas Setup:

  • A canvas element is created with the id “pongCanvas” and dimensions 800×400 pixels.

JavaScript:

  • The JavaScript begins with obtaining a reference to the canvas and its context.
  • It defines constants and variables for paddle dimensions, paddle positions, ball dimensions, ball positions, and ball speeds.

Drawing Functions:

  • Two drawing functions are defined:
    • drawRect: To draw rectangles (used for paddles and clearing the canvas).
    • drawCircle: To draw circles (used for the ball).
  • These functions set the fill style and draw shapes based on given parameters.

Drawing Function:

  • The draw() function is responsible for drawing the game elements on the canvas:
    • Clears the canvas.
    • Draws the paddles and ball.

Update Function:

  • The update() function is responsible for updating the game state:
    • Moves the ball.
    • Handles collisions with walls and paddles.
    • Resets the ball if it goes out of bounds.

Reset Ball Function:

  • The resetBall() function resets the ball position to the center of the canvas and changes its direction.

Mouse Move Handler:

  • An event listener is added to the canvas for the ‘mousemove’ event.
  • It updates the position of the player’s paddle based on the mouse movement.

Calculate Mouse Position:

  • The calculateMousePos() function calculates the position of the mouse relative to the canvas.

Game Loop:

  • The gameLoop() function runs continuously using requestAnimationFrame():
    • Draws the game.
    • Updates the game state.
    • Requests the next animation frame.

Start Game:

  • The game loop is started by calling gameLoop().
 

How to Run Below Code:

To run the provided code, follow these steps:

  1. Copy the entire code provided in the previous response.

  2. Open any text editor (like Notepad, Visual Studio Code, Sublime Text, etc.) and paste the copied code into a new file.

  3. Save the file with an appropriate name, for example, “pong.html“.

  4. Open the saved HTML file using a web browser (such as Chrome, Firefox, Edge, etc.).

  5. Once opened in the browser, you should see the Pong game canvas. You can control one paddle using your mouse, and the game will automatically start.

  6. Move your mouse up and down to control the paddle and try to hit the ball with it.

  7. Enjoy playing the simple Pong game!

 

Source Code:

				
					<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Pong Game</title>
  <style>
    canvas {
      background-color: black;
      display: block;
      margin: 0 auto;
    }
  </style>
</head>
<body>
  <canvas id="pongCanvas" width="800" height="400"></canvas>
  <script>
    const canvas = document.getElementById('pongCanvas');
    const ctx = canvas.getContext('2d');
    
    // Paddle Variables
    const paddleWidth = 10;
    const paddleHeight = 100;
    let paddle1Y = canvas.height / 2 - paddleHeight / 2;
    let paddle2Y = canvas.height / 2 - paddleHeight / 2;
    
    // Ball Variables
    const ballSize = 10;
    let ballX = canvas.width / 2;
    let ballY = canvas.height / 2;
    let ballSpeedX = 5;
    let ballSpeedY = 5;
    
    // Draw Functions
    function drawRect(x, y, width, height, color) {
      ctx.fillStyle = color;
      ctx.fillRect(x, y, width, height);
    }
    
    function drawCircle(x, y, radius, color) {
      ctx.fillStyle = color;
      ctx.beginPath();
      ctx.arc(x, y, radius, 0, Math.PI * 2, false);
      ctx.fill();
    }
    
    function draw() {
      // Clear Canvas
      drawRect(0, 0, canvas.width, canvas.height, 'black');
      
      // Draw Paddles
      drawRect(0, paddle1Y, paddleWidth, paddleHeight, 'white');
      drawRect(canvas.width - paddleWidth, paddle2Y, paddleWidth, paddleHeight, 'white');
      
      // Draw Ball
      drawCircle(ballX, ballY, ballSize, 'white');
    }
    
    // Update Function
    function update() {
      // Move Ball
      ballX += ballSpeedX;
      ballY += ballSpeedY;
      
      // Ball Collision with Top and Bottom Walls
      if (ballY - ballSize < 0 || ballY + ballSize > canvas.height) {
        ballSpeedY = -ballSpeedY;
      }
      
      // Ball Collision with Paddles
      if (ballX - ballSize < paddleWidth && ballY > paddle1Y && ballY < paddle1Y + paddleHeight ||
          ballX + ballSize > canvas.width - paddleWidth && ballY > paddle2Y && ballY < paddle2Y + paddleHeight) {
        ballSpeedX = -ballSpeedX;
      }
      
      // Ball Out of Bounds
      if (ballX - ballSize < 0 || ballX + ballSize > canvas.width) {
        resetBall();
      }
    }
    
    // Reset Ball Position
    function resetBall() {
      ballX = canvas.width / 2;
      ballY = canvas.height / 2;
      ballSpeedX = -ballSpeedX;
    }
    
    // Mouse Move Handler
    canvas.addEventListener('mousemove', function(event) {
      const mousePos = calculateMousePos(event);
      paddle1Y = mousePos.y - paddleHeight / 2;
    });
    
    // Calculate Mouse Position
    function calculateMousePos(event) {
      const rect = canvas.getBoundingClientRect();
      const root = document.documentElement;
      const mouseX = event.clientX - rect.left - root.scrollLeft;
      const mouseY = event.clientY - rect.top - root.scrollTop;
      return { x: mouseX, y: mouseY };
    }
    
    // Game Loop
    function gameLoop() {
      draw();
      update();
      requestAnimationFrame(gameLoop);
    }
    
    // Start Game
    gameLoop();
  </script>
</body>
</html>

				
			

Output:

More HTML CSS JS Projects
Get Huge Discounts

Find More Projects

Jungle Dash Game Using Python with source code with pygame module Introduction: Dive into the excitement of jungle adventures with our new …

Building a Tetris Game with Python with source code Introduction: Welcome to the world of Tetris, where falling blocks meet strategic maneuvers …

Super Mario Game Using Python with source code Introduction: Remember playing Super Mario as a kid? It’s that classic game where you …

library management system using python with source code using Python GUI Tkinter (Graphical User Interface) How to Run the code: Introduction:  Imagine …

Space Shooter Game Using Python with source code Overview: A space shooter game typically involves controlling a spaceship to navigate through space …

Hotel Management System Using Python with source code Introduction: Welcome to our blog post introducing a helpful tool for hotels: the Tkinter-based …

All Coding Handwritten Notes

Browse Handwritten Notes