Create the Classic Ping-pong Game With Java | by Nicolai B. Andersen | May, 2022

A Java and Processing library tutorial

A GIF showing Ping-pong.
A GIF displaying the Ping-pong sport from this text.

Are you searching for a tutorial explaining how you can recreate the traditional Ping-pong sport? Then, look no additional, this text focuses on recreating the sport utilizing the Processing library and Java. I’ve additionally written one other article on how to recreate the classic snake game if you wish to create one other sport.

To obtain Processing go to processing.org/download and select the model matching the popular platform.

Processing offers a graphical library and an built-in improvement atmosphere (IDE) and it makes use of the programming language Java (Wikipedia, 2022a).

The necessities of the sport are offered in two totally different elements. The primary half describes the visible necessities associated to representing the gamers, ball, and atmosphere. The second half describes the practical necessities of how the totally different objects and the applying ought to behave.

3.1 Visible necessities

  • The participant object must be represented by a rectangle.
  • The ball object must be represented by a circle.
  • The sport ought to include two textual content parts displaying every participant’s rating.

3.1 Purposeful necessities

  • The participant object ought to solely be capable to transfer on the y-axis.
  • The ball object ought to be capable to transfer on the x-, and y-axis.
  • The ball object ought to change its path on the x-axis to the other if it overlaps with a participant object.
  • The ball object ought to change its path on the y axis to the other if it strikes out of the display on the y-axis.
  • The ball object’s place and path must be reset if it strikes out of the display on the x-axis.
  • A participant will get some extent at any time when the ball strikes out of the display on the other facet.
  • The primary participant must be managed by the keyboard and the second participant by the pc.

The sport will include two totally different lessons, one to signify a participant object, and one other to signify the ball object. Determine 1 exhibits a UML class diagram containing the 2 lessons. For these of you by no means heard of a UML class diagram, it’s merely a diagram with a system’s lessons, properties, strategies, and relations (Wikipedia, 2022b).

Figure 1: A UML Class diagram showing the two classes used in the Ping-pong game.
Determine 1: A UML Class diagram displaying the 2 lessons used within the Ping-pong sport.

4.1 The participant object

The participant class will probably be used to create objects for each gamers, it’s, due to this fact, essential the place and y-direction are distinctive for every participant, however it may be argued that width, peak, and boundary might be static variables because the values are the identical on all objects. Determine 2 illustrates the concept behind the positioning of the gamers and the boundaries of their motion.

A GIF showing the properties of each player and the path (the red line) they can move.
Determine 2: A GIF displaying the properties of every participant and the trail (the pink line) they’ll transfer.

4.1.1. Participant Properties

The category requires 5 properties (see determine 1), and every of those properties has the next objective:

  • place — A PVector that defines the participant’s x and y place.
  • yDir — A float that defines the path and velocity of the participant’s motion.
  • w — A float defining the width of the participant’s rectangle.
  • h — A float defining the peak of the participant’s rectangle.
  • b— A float defining the boundaries of the participant’s motion.

The implementation of the properties within the participant class might be seen in determine 3.

Determine 3: Reveals the implementation of properties within the participant class.

4.1.2. Participant Strategies

The category additionally requires 5 strategies (see determine 1), and every of those properties has the next objective:

  • replace() — A void technique that’s used to replace the conduct of the participant associated to motion, boundaries test, and drawing of the visible object.
  • setDirection(yDir) — A setter technique that’s used to replace the participant object’s path on the y-axis.
  • getPosition() — A getter technique that returns the participant object’s place.
  • getHeight() — A getter technique that returns the participant object’s peak.
  • getWidth()— A getter technique that returns the participant object’s width.

The Participant class additionally wants a constructor to set the preliminary values of the place and path on the y-axis. The constructor’s argument is designed with floats to signify the beginning place which throughout the constructor is used to create an occasion of a brand new PVector object for the participant’s place.

This can guarantee participant objects don’t seek advice from the identical PVector object in reminiscence which might have been the case if a number of participant objects got the identical PVector object on instantiation.

The getter technique for the path will permit the path to be set on an object outdoors the category, and the setter strategies for place, peak, and width will permit these properties to be learn on an object outdoors the category (see the implementation in determine 4).

Determine 4: Reveals the implementation of the participant constructor, and getter and setter strategies.

The final technique wanted within the participant class is the replace() technique. Determine 5 exhibits the implementation of the strategy.

Determine 5: Reveals the implementation of the participant’s replace technique.

Its conduct might be described as follows:

  • Line 10 — This line will enhance the participant’s y place if the worth of ydir is optimistic and reduces the participant’s y place if the worth of ydir is unfavorable.
  • Line 14 — The primary line checks if the participant’s y place is lower than the worth of b which was used to outline the boundaries of the participant’s motion. Or in different phrases, if the participant has reached its boundary on the high of the display.
  • Line 16 — Reset the participant’s y place to worth of b to stop it from shifting any additional towards the highest of the display.
  • Line 19 — An analogous test to line 14 however checks if the participant has reached the underside of the display as an alternative. This test contains the participant’s peak and the worth of b to make sure the rectangle stops on the right place (See determine 6 for an evidence).
  • Line 21 — Reset the participant’s y place on the backside of the display to stop it from shifting out of the display on the y-axis.
The player object is moved at the anchor point (the value of the position property) and it should therefore stop at the screen height subtracted by b and h to ensure the rectangle stop when its bottom side reaches the boundary.
Determine 6: The participant object is moved on the anchor level (the worth of the place property) and it ought to due to this fact cease on the display peak subtracted by b and h to make sure the rectangle cease when its backside facet reaches the boundary.

A closing instance of the participant class might be discovered at this link.

4.2 The ball object

The ball class is similar to the participant class, however it’s allowed to maneuver on each the x- and y-axis. Determine 7 illustrates how the values of the ball’s place and path change whereas it strikes.

A GIF showing the properties of the ball object.
Determine 7: A GIF displaying the properties of the ball object.

4.1.1. Ball Properties

Determine 1 exhibits the ball class requires 4 properties which might be described as follows:

  • place — A PVector that defines the ball’s x and y place.
  • path — A PVector that defines the path and velocity of the ball’s motion.
  • d — A float defining the diameter of the ball’s circle.
  • s — A float defining the beginning velocity of the ball.

The implementation of the ball’s properties might be seen in determine 8.

Determine 8: The implementation of properties within the ball class.

4.1.2. Ball Strategies

The ball class must also have 5 strategies because the participant class which might be described as follows:

  • replace() — A void technique updating the motion, boundaries, and visuals of the ball.
  • getPosition() — A getter technique that returns the ball’s place.
  • resetMovement() — A void technique that reset the ball’s place to the middle of the display and resets its path to a random worth.
  • setDirection(x) —A setter technique that units the x-direction of the ball.
  • overlapsWith(participant) — A boolean technique returning true if the ball overlaps with the given participant.

The implementation of the ball’s constructor and the strategies, getPosition(), resetMovement(), setDirection(x), and replace() might be seen in determine 9.

Determine 9: The implementation of the ball’s constructor, and the strategies, getPosition(), resetMovement(), invertDirectionX(), and replace().

4.1.2. Collision Strategies

The final technique that must be applied within the ball class is the overlapsWith(participant) technique. Earlier than I present the implementation I wish to give a brief description of the mathematical concepts behind the answer.

Determine 10 exhibits the ball drawn inside a coordinate system, and the anchor level is positioned at origo. The anchor level is the same as the place property of the ball.

Every vector/arrow within the determine factors in the direction of some extent relative to the anchor level which must be used within the collision test. The factors might be calculated by the formulation for changing levels to radians and the rotation matrix.

The figure shows the ball drawn within a coordinate system. The anchor point is the ball’s position, and each vector/arrow points to a point relative to the ball’s anchor point. Each vector is rotated 45 degrees.
Determine 10: The determine exhibits the ball drawn inside a coordinate system. The anchor level is the ball’s place, and every vector/arrow factors to some extent relative to the ball’s anchor level. Every vector is rotated 45 levels.

The formulation for changing levels to radians might be outlined as (Wikipedia, 2022c):

The formula for converting degrees to radians.

The formulation for rotating a vector v, θ radians might be outlined as (Wikipedia, 2022d):

The formula for rotating a vector v, θ radians

The factors calculated with the formulation above are used to test if one in all them is between the nook factors of a participant which might imply the ball is overlapping with the participant (See determine 11).

Determine 11: The determine exhibits a participant object overlapping with the ball object. It additionally exhibits every nook level of a participant based mostly on its place, width, and peak property.

Line 24, in determine 12 exhibits the implementation of the formulation used to transform levels to radians, and line 28–29, in determine 12 exhibits the implementation of the rotation matrix used to rotate a 2D vector 45 levels.

Line 33–34, in determine 12 exhibits the test that returns true if the factors are throughout the participant’s nook factors.

Determine 12: The determine exhibits the implementation of the ‘overlapsWith(participant)’ technique.

A closing instance of the ball class might be discovered at this link.

The appliance wants three Processing strategies, the setup() technique which is executed as soon as the applying begins (Processing.org, 2022a), the draw() technique which is executed as soon as each body till stopped (Processing.org, 2022b), and the keyPressed() technique which is executed when a secret is pressed (Processing.org, 2022c).

5.1 International properties

The sport requires a few international properties used to reference the participant objects, the ball object, velocity, and participant scores (See determine 13).

Determine 13: Reveals the implementation of the sport’s international properties.

5.2 Setup

The setup() technique is used to initialize participant and ball situations and set the display measurement (see determine 14).

Determine 14: Reveals the implementation of the sport’s setup technique.

5.3 Draw

The draw() technique is used for the sport’s repeating logic. Line 20–33 in determine 15 exhibits an if- and else if-statement checking if the ball is outdoors the display, and if that’s the case, one of many gamers will get one level and the ball’s place and path are reset. Line 36–29 in determine 14 exhibits a test that evaluates to true if one of many gamers overlaps with the ball which inverts the ball’s x-direction. Line 43–58 in determine 14 exhibits a small implementation of how the pc controls its participant object (p2) and line 61–64 exhibits the implementation of the gamers’ rating textual content.

Determine 15: Reveals the implementation of the sport’s draw technique.

5.4 KeyPressed

The final code the sport want is for the performance dealing with the keyboard occasions that transfer the p1 object (See determine 16).

Determine 16: Reveals the implementation of the sport’s keyPressed technique.

The Ping-pong sport within the article is created utilizing the Processing library and Java. It incorporates two lessons, a Participant class used to signify participant objects and a Ball class used to signify the ball object.

The lessons are used collectively inside Processing’s setup() draw(), and keyPressed() strategies to arrange the continual conduct and the construction of the sport. The primary participant object might be managed by the keyboard utilizing s and w, and the second participant is managed by the pc.

An instance of the entire sport might be discovered at this link.

En.wikipedia.org. (2022a). Processing (programming language) — Wikipedia. [online] Out there at: <https://en.wikipedia.org/wiki/Processing_(programming_language)> [Accessed 30 April 2022].

En.wikipedia.org. (2022b). Class diagram — Wikipedia. [online] Out there at: <https://en.wikipedia.org/wiki/Class_diagram> [Accessed 16 May 2022].

En.wikipedia.org. (2022c). Radian — Wikipedia. [online] Out there at: <https://en.wikipedia.org/wiki/Radian> [Accessed 17 May 2022].

En.wikipedia.org. (2022d). Rotation matrix — Wikipedia. [online] Out there at: <https://en.wikipedia.org/wiki/Rotation_matrix> [Accessed 17 May 2022].

Processing.org. (2022a). setup() [online] Out there at: <https://processing.org/reference/setup_.html> [Accessed 30 April 2022].

Processing.org. (2022b). draw() [online] Out there at: <https://processing.org/reference/draw_.html> [Accessed 30 April 2022].

Processing.org. (2022c). keyPressed() [online] Out there at: <https://processing.org/reference/keyPressed_.html> [Accessed 30 April 2022].

More Posts