Tuesday, September 15, 2009

A Simple Pong Game using JavaScript

Pong Game in JavaScript Screenshot

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:


  1. hello,
    Nice post dude..Are you interested in back linking? If yes then contact me at

  2. Wow! fantastic! it's really a nice and interesting blog..

  3. wow .. This site was champ for web programming knowledge.
    great place to learn web programming

  4. anjali10:45 AM

    i have one error in this program that is clientY is null or not an object why this error will be came pls tell me

  5. anjali10:45 AM

    i have one error in this program that is clientY is null or not an object why this error will be came pls tell me

  6. Hi anjali,

    As the program is well tested by me, (I've also confirmed right now). Please post the code and the browser you're using.

  7. JavaScript is a good program and very easy to use. I don´t like a complex program. I prefer javascript because i consider it like a device very eficient and it have a good quality.
    I always looking for the quality that is why i prefer to buy viagra because i always have a great result in my sexual life.

  8. I am really new into this. I know that basic stuff in C++ but I haven't tried Java. But Thanks to you and people that really add this kind of stuff that I learned about C++.


You are free to comment anything, although you can comment as 'Anonymous' it is strongly recommended that you supply your name. Thank You.

Please don't use abusive language.