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.

Code

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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Pong Game In JavaScript</title>

<style>
#box
{
   width: 500px;
   height: 300px;
   margin: auto;
   border: 5px solid #ccc;
   position: relative;
   overflow: hidden;
}

.ob
{
   position: absolute;
   border: 0px;
}
</style>
<script type="application/javascript">

// CHANGE THESE, IF REQUIRED
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;

// INITIALIZE GAME OBJECTS
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;

   paddle1.style.left = 20 + 'px';
   paddle1.style.top = playerY + 'px';
   paddle2.style.left = box.offsetWidth - (20 + paddle2.offsetWidth) + 'px';
   paddle2.style.top = cpuY + 'px';
   ball.style.left = ballX + 'px';
   ball.style.top = ballY + 'px';

   // Show message

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

// START GAME
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 = '';
}

// MAIN GAME LOOP, CALLED REPEATEDLY
function GameLoop()
{
   // MOVE BALL
   ballX += dx;
   ballY += dy;

   // See if ball is past player paddle

   if(ballX < 0)
   {
      clearInterval(iID);
      Init();

      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)
   {
      clearInterval(iID);
      Init();

      box.onmousemove = '';

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

   // COLLISION DETECTION

   // 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

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

   // MOVE CPU PADDLE
   // 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;

      paddle2.style.top = cpuY + 'px';
   }
}


// TO MOVE PLAYER PADDLE ON MOUSE MOVE EVENT
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

   paddle1.style.top = y + 'px';
}
</script>
</head>

<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>
<div id="msg" align="center"></div>
</body>
</html>

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

How to Create an HTML Form Linked with MySQL Database in PHP

If you're looking for example code and detailed discussion on how to create an HTML form that stores data in a MySQL database using PHP then this post might be what you're looking for. I assume that you're familiar with basic HTML, CSS, PHP coding, and  MySQL. I am going to divide this small project into two parts: The HTML form itself that takes input from the user and the PHP script that saves it into the database A table that displays the user-added data that has been saved in the database. We'll be dealing with the first part in this tutorial. Again I'd like to break this problem into a few parts so that it's easier for you to understand and probably gives you an insight into how breaking up a problem into smaller chunks can help make things clearer in your mind. Let's think about it, there is an HTML form (that is HTML code), then there is the PHP code that deals with the user-input data, and the MySQL database itself. For this tutorial, we'll b