Part 4

Opening the Racquet file


Now that our ball is able to bounce around the screen, let’s start coding the Racquet we use to hit the ball.

Open up the “Racquet” file, it should look like what is shown here.


Creating Racquet class variables


Next, add the code as shown here to create the class variables that the “Racquet” class will need.

Here, we use the word final on all of the racquet’s dimensions. This is because the racquet will never change in size, so these should be constant. We also have its y position set as final. This is because the y position also shouldn’t change.

Then we need a variable to save the current x position (x) as well as the current x speed (xa).

Lastly, we again need a reference to the game itself in order to communicate with it (game).

Creating Racquet constructor and paint method


Next, add the code as shown here to create the constructor and paint method for the “Racquet” class.

Just like with the “Ball” constructor, we have one parameter here, a reference to the game so that we can save it.

Then inside the “paint” function, we use our class variable to draw a rectangle with the correct dimensions at the correct position.

Painting the Racquet


Next, go back to the “Main” file and add the next two code segments as shown.

First we need to create a new racquet to use in our game, as shown in line 12 here.

Then we need to go inside the “paint” function to get the racquet to paint. This is shown on lines 30-31 here.


Testing the Racquet


Once you’ve completed all of the previous code, go ahead and run the program.

If everything is done correctly, you should see the racquet appear in the game!