Search This Blog

Pong

The Classic Game



So I built Pong! I wanted to make something in Java and settled on this classic game because it seemed just challenging enough. I've never made anything that uses Javafx like this so it was an interesting challenge. 

The hardest part was getting the ball to move. I had to teach myself how to use the animation features of javafx and even then it was a headache. 

Basically, I generate a black screen, 2 rectangular paddles, and a ball. 
Each paddle is stuck to it's side of the screen, and the paddle on the left (paddle 1), follows the y position of the mouse pointer. The other paddle line's its centre up with the y position of the ball using an animation. The general instruction is: "Paddle 2, you have x-amount of time to move your centre to line up with the y coordinate of the ball." I found using animation controls for the paddle to make it move much more smoothly than just translating it. I also implemented limits of motion so the paddles can't go off the edges of the screen. 

The ball starts off in the centre and moves away from the side that last scored a point. Movement in the x-direction is done using another animation command that essentially says: "Ball, you have x-amount of time to translate in X to the rightmost (or leftmost) side of the screen." The x-amount of time controls the speed of the ball, and the direction is controlled using a switch statement that checks for a positive, zero, or negative integer.

Once the ball starts moving, a "motion-in-x" listener keeps track of where it is and if it's reached one side or the other. If it does, it runs another command to either reset the ball(if a point was scored) or bounce it back (if it hits a paddle). 

When I tried to implement the same logic for the top and bottom of the screen (making the ball bounce off those sides), I got nothing but glitches. What I believe was happening was I was trying to give the ball another "animate" command while one was already in progress. The result was a conniption. In the end, I opted for a much simpler "adjust y position" command that directs the ball up or down depending on what it hit. 

Finally, I implemented a way of keeping score, and topped it all off with system beep noises every time the ball hits a paddle. 

The files are available for download here:

No comments:

Post a Comment