Skip to main content

A Simple Pong Game using JavaScript

Pong Game in JavaScript Screenshot

Please see our new and updated version of the Pong Game in HTML & JavaScript. It uses newer technologies like HTML Canvas which are made for animations and games.

Having the knowledge of moving images using JavaScript, we’ll be creating a small Ping Pong game as an example for this post.

Today we’ll learn to do a few new things in JavaScript:

1. Executing some code every specified time interval (for game loop).
2. Tracking and using mouse movements.
3. Attaching code (function) to events.

Game Theory

As you should be knowing, in this game there is one ball and two paddles at two ends. One is user-controlled the other, for this example, is CPU controlled. User has to move the paddle in order not to let the ball pass through, CPU also has to do the same thing. Whoever’s side the ball passes through looses the game.

There are a few objects which can interact with each other, these are ball, paddles, walls. Let’s see the various interactions that can take place between these:

  1. Ball Hitting Upper/Lower Wall – Ball will bounce off.

  2. Ball Passing Through Either Side – Player or CPU, depending on whose side ball passed through, will loose the game.

  3. Ball Hitting Paddle – It’ll bounce off

We’ll need to take care of these events:

  1. Page Load – Game objects will be initialized

  2. Game Start – Mouse click on the player paddle will start the game.

  3. Mouse Movements – Inside the game area (a div), the paddle will follow the y-position of the mouse. Paddle however should not get past the boundaries.

  4. CPU Paddle – The paddle will follow the ball by moving up/down depending the relative position of the ball. We’ve added a little intelligence by only moving the paddle while ball is coming towards it. This will make the movement as well as the game look more real.


NOTE: Put two files ball_small.png, paddle.png (Right-Click "Save As") in the same directory the script is in.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Pong Game In JavaScript</title>

   width: 500px;
   height: 300px;
   margin: auto;
   border: 5px solid #ccc;
   position: relative;
   overflow: hidden;

   position: absolute;
   border: 0px;
<script type="application/javascript">

var Speed = 5; // Speed of ball (pixels/step)
var CPUSpeed = 5; // Speed of CPU Paddle (pixels/step)

// Short references to objects
var paddle1;
var paddle2;
var ball;
var box;
var msg;

// For internal use
var dx, dy; // Speed in x and y directions
var ballX, ballY; // x and y positions of ball
var playerY; // y position of player paddle (x fixed)

var cpuY; // y position of CPU paddle (x fixed)
var iID; // To store ID of set interval used to clear it when required

// Attach a function to onLoad event
window.onload = Init;

function Init()
   // Make short refrences to objects

   paddle1 = document.getElementById('paddle1');
   paddle2 = document.getElementById('paddle2');
   ball = document.getElementById('ball');
   box = document.getElementById('box');
   msg = document.getElementById('msg');

   // Initial values
   ballX = (box.offsetWidth / 2) - (ball.offsetWidth / 2);
   ballY = (box.offsetHeight / 2) - (ball.offsetHeight / 2);
   cpuY = (box.offsetHeight / 2) - (paddle2.offsetHeight / 2);
   playerY = (box.offsetHeight / 2) - (paddle1.offsetHeight / 2);
   dx = dy = Speed; = 20 + 'px'; = playerY + 'px'; = box.offsetWidth - (20 + paddle2.offsetWidth) + 'px'; = cpuY + 'px'; = ballX + 'px'; = ballY + 'px';

   // Show message

   msg.innerHTML = '<h2>Click on Paddle to Start Game.</h2>';

function Start()
   // Attach a function to onmousemove event of the box
   box.onmousemove = MovePaddle;
   // Call 'GameLoop()' function every 10 milliseconds

   iID = setInterval('GameLoop()', 10);

   msg.innerHTML = '';

function GameLoop()
   ballX += dx;
   ballY += dy;

   // See if ball is past player paddle

   if(ballX < 0)

      box.onmousemove = '';

      msg.innerHTML = '<h2>You Loose!<br/>Click on Paddle to Re-Start Game.</h2>';

   // See if ball is past CPU paddle

   if((ballX + ball.offsetWidth) > box.offsetWidth)

      box.onmousemove = '';

      msg.innerHTML = '<h2>You Win!<br/>Click on Paddle to Re-Start Game.</h2>';


   // If ball hits upper or lower wall
   if(ballY < 0 || ((ballY + ball.offsetHeight) > box.offsetHeight))
      dy = -dy; // Make x direction opposite

   // If ball hits player paddle

   if(ballX < (paddle1.offsetLeft + paddle1.offsetWidth))
      if(((ballY + ball.offsetHeight) > playerY) && ballY < (playerY + paddle1.offsetHeight))
         dx = -dx;

   // If ball hits CPU paddle
   if((ballX + ball.offsetWidth) > paddle2.offsetLeft)
      if(((ballY + ball.offsetHeight) > cpuY) && ballY < (cpuY + paddle2.offsetHeight))
         dx = -dx;

   // Place ball at calculated positions = ballX + 'px'; = ballY + 'px';

   // Move paddle only if ball is coming towards the CPU paddle
   if(dx > 0)
      if((cpuY + (paddle2.offsetHeight / 2)) > (ballY + ball.offsetHeight)) cpuY -= CPUSpeed;
      else cpuY += CPUSpeed; = cpuY + 'px';

function MovePaddle(e)
   // Fetch y coordinate of mouse
   var y = (e.clientY - (box.offsetTop - document.documentElement.scrollTop));
   // Here, (box.offsetTop - document.documentElement.scrollTop) will get the relative
   // position of "box" w.r.t to current scroll postion

   // If y below lower boundary (cannot go above upper boundary - 
   // mousemove event only generated when mouse is inside box
   if(y > (box.offsetHeight - paddle1.offsetHeight))
      y = (box.offsetHeight - paddle1.offsetHeight);

   // Copy position
   playerY = y;
   // Set position = y + 'px';

<body bgcolor="#fff">
<h1 align="center">Pong Game Example in JavaScript</h1>

<div id="box">
<img class="ob" id="paddle1" src="paddle.PNG" onclick="javascript: Start()"/>

<img class="ob" id="paddle2" src="paddle.PNG" />
<img class="ob" id="ball" src="ball_small.PNG" />

<div id="msg" align="center"></div>

Related Posts:

Popular posts from this blog

Fix For Toshiba Satellite "RTC Battery is Low" Error (with Pictures)

RTC Battery is Low Error on a Toshiba Satellite laptop "RTC Battery is Low..." An error message flashing while you try to boot your laptop is enough to panic many people. But worry not! "RTC Battery" stands for Real-Time Clock battery which almost all laptops and PCs have on their motherboard to power the clock and sometimes to also keep the CMOS settings from getting erased while the system is switched off.  It is not uncommon for these batteries to last for years before requiring a replacement as the clock consumes very less power. And contrary to what some people tell you - they are not rechargeable or getting charged while your computer or laptop is running. In this article, we'll learn everything about RTC batteries and how to fix the error on your Toshiba Satellite laptop. What is an RTC Battery? RTC or CMOS batteries are small coin-shaped lithium batteries with a 3-volts output. Most laptops use

The Best Way(s) to Comment out PHP/HTML Code

PHP supports various styles of comments. Please check the following example: <?php // Single line comment code (); # Single line Comment code2 (); /* Multi Line comment code(); The code inside doesn't run */ // /* This doesn NOT start a multi-line comment block /* Multi line comment block The following line still ends the multi-line comment block //*/ The " # " comment style, though, is rarely used. Do note, in the example, that anything (even a multi-block comment /* ) after a " // " or " # " is a comment, and /* */ around any single-line comment overrides it. This information will come in handy when we learn about some neat tricks next. Comment out PHP Code Blocks Check the following code <?php //* Toggle line if ( 1 ) {      // } else {      // } //*/ //* Toggle line if ( 2 ) {      // } else {      // } //*/ Now see how easy it is to toggle a part of PHP code by just removing or adding a single " / " from th

Designing a Simple Order Form Application in PHP

Ok guys, for this post we’re going to create a simple yet complete order form page. Order forms are used on many sites to take customers order online. Order forms should have the capability to take orders from visitors regarding what items they want to purchase and store the information for further processing. For this post’s example, we are going to create an order form for a Book Seller. The form will be designed to take order of five different items (books). Our order form application should be able to take order of five different items in any separate quantities tht user wants, it should also ask for shipping address and name of the customer. It should then store the information provided in a file along with the date and time order was placed. The application should also be able to take any number of orders and store them all linearly for further human processing. For this, we need a front end of a HTML form to which the user would interact a