JavaScript Pong
Written by Mike James   
Friday, 24 December 2010
Article Index
JavaScript Pong
Ball and bats
Timer for animation
Enhancements

The animation loop

The entire court is now setup and we can begin to move the ball, allow the user to move the bats and start testing for hits. As browsers only support a single thread of execution we can’t really implement a polling-based animation loop – it would freeze the rest of the user interface. Instead we can make use of a timer.

 

Banner

 

While the window object has a timer it’s so much better to build and use a timer object:

 CTimer = function(tick, code) {
this.timer = window.setInterval(
code, tick);
this.clearTimer = function() {
window.clearInterval(this.timer)
};
}

This will run the specified code every tick milliseconds.

To animate the game all we need to add to run is:

Timer = new CTimer(20, update);

and supply the update function:

update = function() {
var state = Ball.move();
if (state != 0) {
Timer.clearTimer();
BatL.hit(Ball);
BatR.hit(Ball);
}

This simply moves the ball, checks to see if the ball is still in play, and checks to see if either bat has hit the ball – in which case the hit routine bounces the ball.

If the ball goes out of play the game stops, but this is easy to change to give a fixed number of rounds.

Moving bats

The only thing essential thing missing at this point is the ability to move the bats. Ideally this would be done by a method belonging to the bats but this would mean wiring up a keypress to call the correct bat's up-date method. A simpler but not entirely satisfactory solution is to write a keypress handler that calls the appropriate bat move method:

batupdate = function(e) {
 var e = window.event ? event : e;
 if (e.keyCode) { key = e.keyCode; }
 else if (typeof (e.which)
!= 'undefined') { key = e.which; }
 switch (key) {
 case (122):
BatL.move(1);
break;
case (97):
BatL.move(-1);
break;
case (107):
BatR.move(-1);
break;
case (109):
BatR.move(1);
break;
}
}

The strange goings on at the start of the method simply take account of the different way that IE and Firefox return event information. Having a uniform way of handling events would be one of the big advantages of using almost any JavaScript class library.

The keys selected are A and Z for the left bat and K and M for the right bat but you can remap the handlers to any keys that seem reasonable.

Connecting this to the keypress event is just a matter of adding:

document.onkeypress = batupdate;

Now you should have a game that you can play in the sense that the ball moves, bounces off the walls and bat and you can move the bat and hit the ball.

 

Banner

<ASIN:0735624496>

<ASIN:1590595335>



Last Updated ( Friday, 24 December 2010 )
 
 

   
RSS feed of all content
I Programmer - full contents
Copyright © 2014 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.