Previously, I had written a very basic entry about creating a Ping Pong game with Windows Forms in C # and Visual Basic, this time, I write a fully functional version in Windows Forms.

Creating and configuring the project

The first thing we will do is create the project, this will be created in the section Visual C # -> Windows Classic Desktop -> Windows Forms App (.NET Framework), as follows:

Creando un proyecto Windows Forms
Creando un proyecto Windows Forms

Configuring the form

We will place the main elements in our form.

We put a black background on the form through the BackColor property.

We put 4 PictureBox and assign them the following:


Name Size
pbPlayer1 65, 160
pbPlayer2 65, 160
pbTitleScreen N/A
pbBall 35, 35

We put 2 Label elements, and we make the following adjustments:

Name Text
lblScore1 0
lblScore2 0

In the end, we should have something like this:

Interfaz Gráfica del Ping Pong
Interfaz Gráfica del Ping Pong

Do not worry much at the moment by the positions, that we will do it under the code.

Defining the size of the container

We will define 2 constants as part of the class, one called ScreenWidth, and another called ScreenHeight, as follows:

Inside the constructor, we will define the new size of our window, through the property ClientSize, to which we will pass the previously defined parameters.

With this, if we run the application, we will have a window defined based on the vouchers assigned to the variables ScreenWidth and ScreenHeight.

Cargando los Sprites

We are interested now, to show the images in the corresponding PictureBox. To do this, we will create a new class called “GameItem”, which will be in charge of managing the speed, position and image of a “playable” element on the screen, and codify it as follows:

Similarly, we created another class called BallItem, which will inherit from our base class “GameItem”, and which will have a specific method to update the position of our ball.

Returning to the form class, we created 3 variables, 2 of type GameItem, and 1 of type BallItem.

Inside the constructor, we subscribe to the Load event of the form and also call a method that will be called “Initialize”. As part of the Load event, we will call a method called “LoadGraphicsContent”, which we define as follows:

Before running the project, we must download the sprites. These sprites need to be unzipped, and they should be left in the Debug folder.

Colocando los sprites
Colocando los sprites

With this, we will already have our sprites loaded in the form.

Sprites cargados
Sprites cargados

Detect Mouse and Draw Player 1

Before continuing, we will create 5 regions:

  • GamePlay Methods
  • Events
  • Engine Methods
  • Mechanics
  • Collisions

We will place the form load event code in the event region, Initalize and LoadGraphicsContent within Engine Methods.

We add 2 timers as part of the main interface, and assign them the following:

Name Enabled Interval
UpdateTimer True 16
DrawTimer True 16

We have to create their respective event handler for the Tick event, which we will take to the event region to have the code sorted. Within the event handler of the click event of the UpdateTimer control, it is necessary to call an undefined method still called UpdateScene, which will contain the logic to carry out the update of the graphical interface. UpdateScene must go in the EngineMethods region.

We will define the UpdateScene method within the Engine Methods region, and from there we will call a new undefined method called UpdatePlayer.

Within the Mechanics region, we will define the new UpdatePlayer method, where we will define the code, first to control player 1. We begin by defining the constant X position that our sprite will have on stage, that is, because a paddle can only move from top to bottom, therefore, the position in X will always be the same. On the other hand, we will take the value in Y, according to the position of the mouse pointer. Subsequently, we will create a new position according to the values obtained. Finally, we make checks so that our paddle does not leave the limits of the stage.

Finally, we must redraw the control in its new position, so we have to code within the DrawTimer_Tick event handler, a new method called DrawScene.

DrawScene will be defined within Engine Methods, and will contain a call to the Draw method of the corresponding sprite.

If we execute, we will have the paddle of player 1 in action.

Detect keyboard and draw Player 2

Performing the detection of the keys in Windows Forms, is easier these days. To do this, you have to use 2 libraries that are not added by default: “PresentationCore” and “WindowsBase”. With this, we can implement the logic in the UpdatePlayer method, to detect if a key of our preference has been typed, in our case, we will use the keys ‘S’ and ‘W’, later, we validate if the paddle of player 2 is found on the stage. We must also define a class-level variable called “_currentY”, of type int.

The code to perform the check is as follows:

Finally, we must not forget to update the drawing of the paddle, in the DrawScene method.

Moving the ball

To move the ball, we must define 3 new methods within the “Mechanics” region, which will be: “ResetBall”, “GenerateBallX” and “GenerateBallY”.

So that it does not mark errors with the variables, we will add the missing ones as part of the class.

Finally, it is necessary to update the position of the ball, and to draw it through the corresponding methods.

Validating the clash of the ball against the paddles and walls

Validating the clash against the paddles

To perform these validations, add 4 points to the sprites, in order to verify if the ball has hit a paddle. For this, we will modify the GameItem class, as follows.

And we’ll add the CheckPaddleCollisions method to the form class.

Finally, we called to call the new method through UpdateScene:

Validating the shock against the upper and lower walls

For this validation, we will create a new method called “CheckWallCollision”, which should be as follows:

Again, add the variable “BaseBallSpeed” as part of the class variables.

And again, we call the check from the UpdateScene method.

Validating if the ball has left the scene

For this, you have to validate where the position of the ball is through the following code.

You have to add the variables that will store the players’ scores.

Finally, we call the method from UpdateScene.

Code in Github

With this we reached the end of the entry, the code is still quite improving, I just wanted to update this entry, because I saw that there were many people interested in the subject. I leave the code in Github with a piece of code that I have not shown here.


¡Califica la publicación!
[Total: 0 Promedio: 0]


Please enter your comment!
Please enter your name here