Simple Game Programming In JavaScript Ping Pong | WebReference

Simple Game Programming In JavaScript Ping Pong

By Lisha Sterling


Digg This Add to

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:

  • A ball that can be hit from one side to the other inside the playing court
  • A playing court drawn by the browser using CSS
    • The ball will always stay inside this court
    • If the ball hits the right or left edges of the court, the opposite side has won that round.
  • Flat paddles for hitting the ball, Pong style
    • Each paddle will be movable using keyboard entry
    • The paddles will have "hit" the ball if any part of the ball hits any part of the paddles
  • Two different ways to start play or "serve" the ball
    • One button to "Start Play!"
    • One keystroke to serve the ball.

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

  • A scoreboard
  • A way to change the difficulty (speed or paddle size) of the game
  • A way for two players on different computers to play the game
  • A way for both players to move their paddles at the same time

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: