O'Reilly logo

Java® Programming 24-Hour Trainer by Yakov Fain

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 12

Developing a Ping-Pong Game

The tic-tac-toe game developed in Lesson 11 was a simple one. My goal was to show you the basic layout of UI components and event processing. Now you’ll learn how to draw and move such objects as ovals, rectangles, and lines in a window. You’ll also learn how to process keyboard events. To add a little fun to these subjects, you’ll be learning all these things while creating a ping-pong game. This game will have two players: the user and the computer.

The Strategy

Let’s come up with the rules for our version of the ping-pong game:

1. The game lasts until one of the players (the user or the computer) reaches a score of 21. The computer’s racket is on the left.

2. The user’s racket movements will be controlled by the mouse.

3. The game score will be displayed at the bottom of the window.

4. A new game starts when a player presses the N key on the keyboard; the Q key ends the game; S serves the ball.

5. Only the user can serve the ball; the computer can’t.

6. For one of the players to win a point the ball must go beyond the opponent’s racket’s vertical line when the racket is not blocking the ball.

7. When the computer bounces the ball, the ball can move only horizontally to the right.

8. If the ball contacts the user’s racket in the upper half of the table, the ball should be moving up and left. If the ball was located in the bottom part of the table, it should move down and left.

It sounds like a very complicated task, but let’s split ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required