Plan du site  
pixel
pixel

Articles - Étudiants SUPINFO

Development of a PONG game in VB

Par Vincent SYLVESTRE Publié le 21/04/2017 à 11:19:10 Noter cet article:
(0 votes)
En attente de relecture par le comité de lecture

When designing applications with Visual Studio, two languages are used : C # as well as Visual Basic (VB). The second one was created in 1991 but it was not, until 2002 and 6 different versions, integrated into the .NET framework to give the VB.NET. At the same time, C # appeared as the .NET framework.

The use of the VB, according to O'Reilly's books sales, was more important than C # until 2006, the year in which the C # definitely took the step on its predecessor.

In this article, we will discover the syntax of Visual Basic by recreating the PONG game using Visual Studio.

Prerequisites

As mentioned above, you will need to download and install Visual Studio.

For my part, I will use Microsoft Visual Basic 2008 Express, a free version, but nothing prevents you from choosing a more complete and / or up-to-date one.

Creating the user interface

In order to get this interface, we will drag-and-drop several elements of the toolbox (on the left) on the main window.

Start by dropping off two labels that will be used to display the scores of the players, then two Buttons, resize them, a RadioButton which will act as a ball and finally in the category "Components", slide a timer on the edit window. It will be used for the sequential shifting of the ball.

Now, configure the properties of these controls.

Click on the main window, you will be able to modify its Text with for example "Ping Pong". And, with the same method, delete the Text of the Buttons.

Next, configure the names of all the controls in the same way. Click the item to rename and change its "(Name)" property.

We will name them as follows :

  • LblScore1

  • LblScore2

  • Raq1

  • Raq2

  • Balle

  • FrmPingPong (the main window)

Now we will set up a trigger interval for the timer. Change its "Interval" property to 100. This value is expressed in milliseconds.

Event Creation

Once the interface created, it looks very well but, if you launch the application, nothing will happen :). Now, we have to deal with the programming part.

First, you have to double-click on the main window. This will open a new tab in your IDE (Development environment) with the automatic creation of a function Private Sub Form_Load…

This function will be triggered automatically when the application is launched.

Do the same with the Timer. The Timer1_Tick function will be triggered at the timer rhythm every 100 milliseconds.

Then, to detect keyboard presses, create this function :

    Private Sub FrmPingPong_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    
    End Sub
    

The e object in parameter will contain the value of the key pressed.

Code writing

Variable declaration

At the very top of your code page, just below Public Class FrmPingPong, declare all the variables you will use in the rest of the code.

    Dim DepVertic As Integer    ' Distance traveled vertically by the ball at each movement 
    Dim DepHoriz As Integer     ' Distance traveled horizontally by the ball at each movement 
    Dim DepRaq As Integer       ' Distance traveled vertically by the racket at each movement 
    Dim LimiteHaut As Integer  ' Upper boundary coordinate of the game frame 
    Dim LimiteBas As Integer   ' Lower boundary coordinate of the game frame 
    Dim LimiteGauche As Integer ' Left boundary coordinate of the game frame 
    Dim LimiteDroite As Integer    ' Right boundary coordinate of the game frame 
      

Preliminary functions

In order to simplify the comprehension and reduce the code, you must create two functions that will be reused later. They are called "deplacerRaqVersHaut" and "deplacerRaqVersBas". And their name, I think, is quite explicit :).

In addition, they take as parameters :

  • Raquette, the name of the racket defined above to move.

  • Deplacement, the distance that the racket must travel upward or downward.

  • Limite, which defines the maximum limit at the top or bottom of the racket.

    Sub deplacerRaqVersHaut(ByRef raquette As Button, ByVal deplacement As Integer, ByVal limite As Integer)
        raquette.Top = raquette.Top - deplacement
        If raquette.Top <= limite Then
            raquette.Top = limite
        End If
    End Sub

    Sub deplacerRaqVersBas(ByRef raquette As Button, ByVal deplacement As Integer, ByVal limite As Integer)
        If raquette.Bottom < limite Then
            raquette.Top = raquette.Top + deplacement
        End If
    End Sub
      

Finalization

Once all these preliminary steps have been completed, you will code the Form_Load function that triggers when the application is opened. It will have to initialize all its parameters.

    Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.KeyPreview = True    'Allows to run the keyboard events on the form 
        'Initialization of global variables 
        DepVertic = 3
        DepHoriz = 3
        DepRaq = 10
        LimiteHaut = 0
        LimiteGauche = 0
        LimiteBas = Me.Height - 38 'A few pixels adjustment 
        LimiteDroite = Me.Width - 5 'A few pixels adjustment 
        LblScore1.Text = 0
        LblScore2.Text = 0
        Timer1.Interval = 30    'Time interval in milli-seconds between each timer trigger 
        Timer1.Start()          'Start the Timer 
    End Sub
      

After that, we go to the function FrmPingPong_KeyDown which is triggered when a key is pressed. The goal is to call the correct function in relation to the key pressed.

    Private Sub FrmPingPong_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        Select Case e.KeyCode
            Case 65         'Key A ascii 65 : Raq1 to Top
                deplacerRaqVersHaut(Raq1, DepRaq, LimiteHaut)
            Case 81         'Key Q ascii 81 : Raq1 to Bottom
                deplacerRaqVersBas(Raq1, DepRaq, LimiteBas)
            Case 80         'Key P ascii 80 : Raq2 to Top 
                deplacerRaqVersHaut(Raq2, DepRaq, LimiteHaut)
            Case 77         'Key M ascii 77 : Raq2 to Bottom 
                deplacerRaqVersBas(Raq2, DepRaq, LimiteBas)
        End Select
    End Sub
      

Then we turn to the Timer1_Tick function that is triggered at each interval of the counter. It is responsible of the moves and the behavior of the ball in different kinds of situation.

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Balle.Top = Balle.Top + DepVertic   ' Ball movement 
        Balle.Left = Balle.Left + DepHoriz

        ' Treatment of the rebound at the top by inversion of the sign of the displacement
        ' Treatment of the rebound at the bottom by inversion of the sign of the displacement
        If Balle.Top <= LimiteHaut Or Balle.Bottom >= LimiteBas Then
            DepVertic = -DepVertic
        End If

        ' Treatment of the rebound at the left by inversion of the sign of the displacement
        If Balle.Left <= LimiteGauche Then
            LblScore2.Text += 1
            DepHoriz = -DepHoriz
        End If

        ' Treatment of the rebound at the right by inversion of the sign of the displacement
        If Balle.Right >= LimiteDroite Then
            LblScore1.Text += 1
            DepHoriz = -DepHoriz
        End If

        'Treatment of the ball contact with racket1 and rebound by inversion of the sign of the displacement
        If DepHoriz < 0 And Balle.Left <= Raq1.Right And Balle.Left >= Raq1.Left Then
            If Balle.Top >= Raq1.Top And Balle.Top <= Raq1.Top + Raq1.Height Then
                DepHoriz = -DepHoriz
            End If
        End If

        'Treatment of the ball contact with racket2 and rebound by inversion of the sign of the displacement
        If DepHoriz > 0 And Balle.Right >= Raq2.Left And Balle.Right <= Raq2.Right Then
            If Balle.Top >= Raq2.Top And Balle.Top <= Raq2.Top + Raq2.Height Then
                DepHoriz = -DepHoriz
            End If
        End If

    End Sub
      

Conclusion

Congratulations! You just created a rudimentary but functional Pong game, but above all, you have been able to understand the basics of the VB.NET language.

If you are interested in this language and if you like PONG, many improvements of this game are possible like the management of new games when a certain score is reached for example.

To help you, I advise you to follow one of the courses on openclassrooms : https://openclassrooms.com/courses/apprenez-a-programmer-en-vb-net .

A propos de SUPINFO | Contacts & adresses | Enseigner à SUPINFO | Presse | Conditions d'utilisation & Copyright | Respect de la vie privée | Investir
Logo de la société Cisco, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société IBM, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société Sun-Oracle, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société Apple, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société Sybase, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société Novell, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société Intel, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société Accenture, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société SAP, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société Prometric, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo de la société Toeic, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management Logo du IT Academy Program par Microsoft, partenaire pédagogique de SUPINFO, la Grande École de l'informatique, du numérique et du management

SUPINFO International University
Ecole d'Informatique - IT School
École Supérieure d'Informatique de Paris, leader en France
La Grande Ecole de l'informatique, du numérique et du management
Fondée en 1965, reconnue par l'État. Titre Bac+5 certifié au niveau I.
SUPINFO International University is globally operated by EDUCINVEST Belgium - Avenue Louise, 534 - 1050 Brussels