Make Ping Pong Game using HTML, CSS & Javascript


TABLE OF CONTENT
Ping Pong primary points
Ping Pong Game Rules
LOCAL STORAGE
Solution - How to make Ping Pong Game using HTML, CSS

Ping Pong game is one of the first computer games ever made; it's a simple "tennis-like" game with two paddles and a ball, with the goal of defeating your opponent.

So, we're going to make a smaller, easier version of this game.

The following are the game's primary points:

  1. The screen will have two rods at the top and bottom.
  2. Same keys will be used to operate both rods. To put it another way, they will move in sync.
  3. When the game begins, an alert about the greatest score and the player who achieved it should be displayed. If no such record exists, state that - this is your first time.
  4. Save the name and max-score in local storage if the score becomes the highest.
  5. When a player wins a round, an alert will appear on the screen, displaying the victorious player's name and score.

There are screenshots and a little gameplay video available, but first, let's go over the game's rules -

Ping Pong Game Rules -

  1. When the 'Enter' key is pushed, the round should begin. ( You can also use another key )
  2. The 'arrow-right' and 'arrow-left' keys will only move the rods horizontally. ( You can also use other keys )
  3. The ball will be given to the losing rod for the next match, and the rods and ball will be moved to the centre.
  4. Starting from the first match, the score will be kept track of.

When the game first starts, it should appear like this -

How to Make Ping Pong Game using HTML, CSS & Javascript - Start

At the end of each round, the game should look like this -

How to Make Ping Pong Game using HTML, CSS & Javascript - Bar 1 win

At the start of each round, the game should look like this -

How to Make Ping Pong Game using HTML, CSS & Javascript - Bar 2 win

A little clip for this gameplay may be found below -

To Make Ping Pong Game using HTML, CSS & Javascript, we also need to have proper knowledge of the topic - Local Storage.

We will discuss briefly how the Local storage works.

LOCAL STORAGE

Local Storage is a kind of online storage that allows you to store and access data in your browser.

The data in local storage does not have an expiration date.

Data is saved in local storage as a 'key-value' pair, often known as a data item.

The 'keys' and 'values' that are stored are always strings.

Even integers and other primitive values will be transformed to strings.

Storing data in Local Storage

You can store data items in local storage by passing two parameters to the 'setItem()' method: a 'key' and a 'value.'

The syntax for storing data items is as follows:

localStorage.setItem("key", "value");

Getting Data from the Local Storage

By giving 'key' as a parameter to the 'getItem()' method, you can retrieve data items saved in the browser. As an output, the method returns the 'value' corresponding to the 'key.' If no such item is discovered, the value 'undefined' is returned.

The syntax for gaining access to a data item is as follows:

localStorage.getItem("key");

Removing Data from the Local Storage

You can delete a data item from the web storage by giving the parameter 'key' to the 'removeItem()' method. If no such object is connected with the specified 'key', it will do nothing.

The syntax for removing a data item is as follows:

localStorage.removeItem("key");

Replacing Data in Local Storage

The value saved with a 'key' can be replaced directly by calling the'setItem()' method. This will either overwrite the existing data item or create a new one if there is no such key in the storage.

Solution - How to make Ping Pong Game using HTML, CSS & Javascript:

HTML Code - pingpong.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ping-Pong!!</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div id="container">
        <div id="bar-1">Bar 1</div>
        <div id="ball"></div>
        <div id="bar-2">Bar 2</div>
    </div>
    <script type="text/javascript" src="script.js"></script>
</body>
</html>

CSS Code - style.css

*{
    padding: 0px;
    margin: 0px;
}
#container{
    /* border: 1px solid black; */
    position: relative;
}
#ball{
    height: 20px;
    width: 20px;
    /* border:1px solid black; */
    position: fixed;
    border-radius: 50%;
    background-color:brown;
    left:60%;
    top:20px;
}
#bar-1{
    height: 20px;
    display: flex;
    justify-content: center;
    width:150px;
    background-color: seagreen;
    border-radius: 10px;
    /* border:1px solid black; */
    position: fixed;
    font-weight: bold;
    top:0%;
    left:50%;
}
#bar-2{
    height: 20px;
    width:150px;
    background-color: cadetblue;
    border-radius: 10px;
    /* border:1px solid black; */
    position: fixed;
    display: flex;
    justify-content: center;
    font-weight: bold;
    bottom: 0%;
    left:50%;
}

Javascript Code - script.js

var bar1=document.getElementById("bar-1");
var bar2=document.getElementById("bar-2");
var ball=document.getElementById("ball");
var movement=20;

const thisBar1="Bar-1";
const thisBar2="Bar-2";
const storeName="abc";
const storeScore=123;

let whichBar;
let moveX=2;
let moveY=2;
let ballMoving;
let border=12;
let score;
let highScore;
let gameStart=false;

localStorage.setItem(storeScore,"null");
localStorage.setItem(storeScore,"null");
(function(){
    highScore=localStorage.getItem(storeScore);
    whichBar=localStorage.getItem(storeName);
    if(whichBar==="null" || highScore==="null"){
        alert("Hello.. This is your first game");
        highScore=0;
        whichBar=thisBar1;
    }
    else{
        alert(whichBar + " has maximum score of " + highScore*100);
    }
    gameReset(whichBar);
})();




function gameReset(barName){

    bar1.style.left=((window.innerWidth-bar1.offsetWidth)/2)+"px";
    bar2.style.left=((window.innerWidth-bar2.offsetWidth)/2)+"px";
    ball.style.left=((window.innerWidth-ball.offsetWidth)/2)+"px";

    if(barName === thisBar1){
        ball.style.top=bar2.getBoundingClientRect().y-bar2.getBoundingClientRect().height+"px";
        moveY=-2;
    }

    else if(barName === thisBar2){
        ball.style.top=bar1.getBoundingClientRect().height+"px";
        moveY=2;       
    }

    score=0;
    gameStart=false;

}




document.addEventListener('keydown',function(event){

    if(event.keyCode==68 || event.keyCode==39){
        if(parseInt(bar1.style.left)<(window.innerWidth-bar1.offsetWidth-border)){
            bar1.style.left=parseInt(bar1.style.left)+movement+'px';
            bar2.style.left=bar1.style.left;
        };

    };

    if(event.keyCode==65 || event.keyCode==37){
        
        if(parseInt(bar1.style.left)>border){
            bar1.style.left=parseInt(bar1.style.left)-movement+'px';
            bar2.style.left=bar1.style.left;
        };

    };

    if(event.keyCode==13){
        
        if(!gameStart){
            gameStart=true;
            let ballRect = ball.getBoundingClientRect();
            let ballX = ballRect.x;
            let ballY=ballRect.y;
            let ballDia=ballRect.width;

            let bar1Height=bar1.offsetHeight;
            let bar2Height=bar2.offsetHeight;
            let bar1Width=bar2.offsetWidth;
            let bar2Width=bar2.offsetWidth;

            ballMoving = setInterval(function(){
            
                let bar1X=bar1.getBoundingClientRect().x;
                let bar2X=bar2.getBoundingClientRect().x;

                let ballCentre=ballX+ballDia/2;

                ballX+=moveX;
                ballY+=moveY;

                ball.style.left=ballX+"px";
                ball.style.top=ballY+"px";

                if(((ballX+ballDia)>window.innerWidth) || (ballX<0)){
                    moveX=-moveX;
                }

                if(ballY<=bar1Height){
                    moveY=-moveY;
                    score++;

                    if((ballCentre<bar1X) || (ballCentre>(bar1X+bar1Width))){
                        dataStoring(score,thisBar2);
                    }
                }
                if((ballY+ballDia)>=(window.innerHeight-bar2Height)){
                    moveY=-moveY;
                    score++;

                    if((ballCentre<bar2X) || (ballCentre>(bar2X+bar2Width))){
                        dataStoring(score,thisBar1);
                    }
                }  
            }, 10);
        }
    }
});

function dataStoring(scoreObtained,winningBar){
    if(score>highScore){
        highScore=score;
        localStorage.setItem(storeName,winningBar);
        localStorage.setItem(storeScore,highScore);
    }
    clearInterval(ballMoving);
    gameReset(winningBar);

    alert(winningBar+" wins with score of "+(scoreObtained*100)+". Max Score is: "+(highScore*100));
}

Hope you enjoyed a lot making and playing this lovely game - Ping Pong Game using HTML, CSS & Javascript.

You may like to Explore -

3 Super Mini Projects using jQuery

Cheers.

Happy Coding.

About the Author

This article was authored by Rawnak.

Comments are closed.