Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

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


advertisement
Create the Game Elements
Open your favorite text editor and enter the following HTML to create the screen objects for the game:

<html> <head> <title>Rebound</title> </head> <body > <h1>Rebound</h1> <div id="playingArea"> <div id="paddle"> <img src="paddle.gif"> </div> <div id="ball"> <img src="ball.gif"> </div> <div id="score"> Score: 0 </div> </div> </body> </html>

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:

<style> #playingArea{ position: absolute; top: 100; left: 100; border: 1px solid black; width: 500; height: 500; background-color: rgb(192,192,192); } #paddle{ position: absolute; top: 470; left: 228; width: 64; height: 16; } #ball{ position: absolute; top: 4; left: 200; width: 16; height: 16; } #score{ position: absolute; top: 486; left: 0; width: 500; height: 14; font-size: 10pt; color: white; background-color: rgb(32,128,64); } </style>

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

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()">




Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap