The Wayback Machine - https://web.archive.org/web/20111012004435/http://www.webreference.com/programming/javascript/java_anim2/index.html

WebReference.com logo
tip archive  •   about  •   sitemap  •   contact  •   jobs  •   write for us  •   subscribe

Newletters


[next]

Simple Game Programming In JavaScript

By Lisha Sterling

Digg This Add to del.icio.us

C/C++ Developer (NYC)
Next Step Systems
US-NY-New York

Justtechjobs.com Post A Job | Post A Resume

In the previous article you learned how to create an animation with JavaScript using a timer mechanism, an image of a ball and CSS styles. This time we'll make some adjustments to the CSS and the document object model (DOM) to create a simple ping-pong game. We'll also be using keyboard input and events. With these tools you'll be able to create different games in JavaScript, such as Breakout, Tetris, Frogger or your dream game.

First, let's look at what our game will contain when we're done with this article:

Now, let's look at some basic things that won't be in our game (yet):

The first two of these are fairly simple to add, but would make this article too long. The third requires an AJAX version of this game which is also beyond the scope of this article. The fourth shortcoming concerns advanced event handling in JavaScript. We'll take a deeper look at the problems and the solution for multiple event handling in another article.

Let's start out by creating the HTML and drawing the playing court. Last time we used the entire window for our animation, and the ball bounced around against the inside boundaries of the browsers. This time we're going to use a div inside our browser window as our court. We'll draw a blue court of 400 x 750 pixels, with a dashed centerline. The outside boundaries of the court will be 4 pixels wide. The center line will be only 1 pixel wide.

HTML page:

Now, let's add in the ball and the paddles. The ball will start on the left side of the court, near the top, ready to be "served" by the left paddle. The two paddles will start out on their respective sides of the court, 15 pixels away from the edge of the div. You'll notice that the left position for the right paddle is 725 pixels, 25 pixels away from the edge of the court. The paddle is 10 pixels wide, though, so the right side of the paddle is 15 pixels away from the right edge of the court.

HTML changes:


[next]

Recent Articles

WebReference.com site name
Flashmaps' DynamicLocator: Interactive Maps for Small Areas
Flashmaps' AreaSelector: Interactive Maps for Wide Areas
The DB Mapper: Interactive Street-level Maps of U.S. and Canada
internet.com site name
Vocalocity launches telephony/app integrations for Desktop
How to Reanimate Dead Spots in Wi-Fi Networks
PC Buyer's Guide for Gaming Enthusiasts


Internet.com
The Network for Technology Professionals

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers