RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


An Introduction to Game Programming with JavaScript-2 : Page 2

Create the Game Elements
Open your favorite text editor and enter the following HTML to create the screen objects for the game:
  <body >
  <div id="playingArea">
    <div id="paddle">
        <img src="paddle.gif">
    <div id="ball">
        <img src="ball.gif">
    <div id="score">
        Score: 0
Note that the playingArea <div> is a container for all the other screen objects. As you'll see, I'll position the playingArea absolutely and then do the same for the paddle, ball, and score. The result is that the paddle, ball, and score are positioned relatively to the location of the playingArea.

Next, create the CSS that formats and positions the HTML objects by adding the following <style> element to the <head> of the file:
      position: absolute;
      top: 100;
      left: 100;
      border: 1px solid black;
      width: 500;
      height: 500;
      background-color: rgb(192,192,192);
      position: absolute;
      top: 470;
      left: 228;
      width: 64;
      height: 16;
      position: absolute;
      top: 4;
      left: 200;
      width: 16;
      height: 16;
      position: absolute;
      top: 486;
      left: 0;
      width: 500;
      height: 14;
      font-size: 10pt;
      color: white;
      background-color: rgb(32,128,64);
Scripting the Game
Add a <script> tag just beneath the <style> element and create the instance variables for the program. Instance variables are variables whose scope is the entire script.
<script language="JavaScript">
   //instance vars
   var ball;
   var paddle;
   var score;

   //initial speeds
   var dx = 6;
   var dy = 6;
   var currentScore = 0;
   var timer;

   //set initial conditions for ball and paddle
   var paddleLeft = 228;
   var ballLeft = 200;
   var ballTop = 4;
Next, you'll need to provide initial positions for the ball, paddle, and score variables visible on the screen. This init() function initializes the objects. Add the following to your script:
function init(){
//instantiate HTML object instance vars
   ball = document.getElementById('ball');
   paddle = document.getElementById('paddle');
   score = document.getElementById('score');
Then, call the init() function from the <body> tag's onLoad event:
<body onLoad="init()"> 

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date