• (3 Pages)
• 1
• 2
• 3

## Creating a fully-functional pong game. A step-by-step guide to creating a pong game in VB.NET Rate Topic: 2 Votes //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=39686&amp;s=b2239bc808a43a42727254531a6df3cc&md5check=' + ipb.vars['secure_hash'], cur_rating: 5, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #31 Bongi m

Reputation: 0
• Posts: 1
• Joined: 25-February 11

Posted 04 March 2011 - 05:04 AM

daneroo, on 25 September 2008 - 07:54 AM, said:

Great tutorial, well commented and explained thoroughly, Thank-you />

Dan

Hey thats great hey man your good keep it up.can you also post the battleship game tutorial please

This post has been edited by macosxnerd101: 07 June 2013 - 09:07 AM
Reason for edit:: Removed email link per site policies

### #32 ohkelvin

Reputation: 0
• Posts: 1
• Joined: 26-March 11

Posted 26 March 2011 - 03:43 PM

RodgerB, on 17 December 2007 - 12:34 AM, said:

5) Making the ball bounce.

Making the ball bounce is easier than you may initially think. We need to put code in the gameTimer timer again, because we need it constantly checking if the ball needs to bounce or not.

To make the ball bounce, it is just a matter of setting the ball's position to contact the surface of the wall, and set the velocity opposite to it's current velocity. How would we set it opposite you ask? By making it negative. So hypothetically, we will be testing to see if the ball hits the wall, and if it does make it bounce off the wall. Here is how we would do this using the top wall. Note that you will need to add this to the Main Timer region, inside the timer subroutine.

```' Check for top wall.
If gameBall.Location.Y < 0 Then
gameBall.Location = New Point(gameBall.Location.X, 0)
yVel = -yVel
End If

```

Note that we only want to invert the Y Axis as we aren't dealing with any advanced spinning physics. The ball should now bounce off the wall and continue in it's path; which is obviously what we want.

Now we will need to make the code for the bottom wall. When checking for the collision, we need to to check if the ball is higher than the form's height minus the height of the ball, and we will take off 45 to line it up.

```' Check for bottom wall.
If gameBall.Location.Y > Me.Height - gameBall.Size.Height - 45 Then
gameBall.Location = New Point(gameBall.Location.X, Me.Height - gameBall.Size.Height - 45)
yVel = -yVel
End If

```

Now we have the ability to make the ball bounce up and down. Now that we can do this... I think it would be a good time to demonstrate how we can make the ball bounce off the paddles. It is actually relatively simpler than the form's walls, so don't worry, the head scratching is done for this section.. kinda. We will start with the player paddle. We will need to add the following to the main timer, as the main timer is for collisions and other miscellaneous tasks.

```' Check for player paddle.
gameBall.Location = New Point(paddlePlayer.Location.X - gameBall.Size.Width, _
gameBall.Location.Y)
xVel = -xVel
End If

```

This will check if the ball has intersected with the paddle object and bounce it off if it did. It is the same with the computer paddle too; the process involved is the same pretty much.

```' Check for computer paddle.
gameBall.Location.Y)
xVel = -xVel
End If

```

Now that we have the ball bouncing, we need to add Game Flow.

6) Game Flow.

Game Flow in pong is basically, you lose if the ball goes past the paddle. When it goes past the paddle we want the ball to go back to the middle of the form, and give the winner a point, which will be displayed in the label.

In order to give the players a score, we will need two global variables indicating them. In the Globals region, add the following code so we can start using these score variables.

```' The player's scores.
Dim compScore As Integer = 0
Dim plrScore As Integer = 0

```

Now we want to do something with these variables, otherwise we would just be wasting precious memory. Add the following to the main timer, as we are checking for a collision with the left wall.

```' Check for left wall.
If gameBall.Location.X < 0 Then
plrScore += 1
gameBall.Location = New Point(Me.Size.Width / 2, Me.Size.Height / 2)
plrScoreDraw.Text = Convert.ToString(plrScore)
End If

```

We will add one to the player's score, as he/she has scored, set the ball's position to the middle of the form and we will set the plrScoreDraw.Text property to display the player's score.

We will do the same thing if the computer wins, except we will be checking to see if the right wall has been hit.

```' Check for right wall.
If gameBall.Location.X > Me.Width - gameBall.Size.Width - paddlePlayer.Width Then
compScore += 1
gameBall.Location = New Point(Me.Size.Width / 2, Me.Size.Height / 2)
compScoreDraw.Text = Convert.ToString(compScore)
End If

```

Now that we have this functionality, the game is in a playable state. Now to a couple of 'nice to have' features.

My ball won't bounce... here is my code

```Public Class Game

Dim speed As Single = 10 'speed of ball'
Dim random As New Random() 'Random instance
Dim xVel As Single = Math.Cos(random.Next(5, 10)) * speed
Dim yVel As Single = Math.Cos(random.Next(5, 10)) * speed

Private Sub PictureBox2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox2.Click
Help.Visible = True
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
'Set the computer player to move according to the ball's position."

If ball.Location.Y > 5 And ball.Location.Y < Me.Height - 40 _
- Player.Height Then

PC.Location = New Point(PC.Location.X, ball.Location.Y)
End If
'Move the ball'
ball.Location = New Point(ball.Location.X + xVel, ball.Location.Y + yVel)

'Watch out for top wall.'
If ball.Location.Y < 0 Then
ball.Location = New Point(ball.Location.X, 0)
yVel = -yVel
End If

'Watch out for bottom wall.'
If ball.Location.Y < Me.Height - ball.Size.Height - 45 Then
ball.Location = New Point(ball.Location.X, Me.Height - ball.Size.Height - 45)
yVel = -yVel
End If

'Check 4 player
If ball.Bounds.IntersectsWith(Player.Bounds) Then
ball.Location = New Point(Player.Location.X - ball.Size.Width, _
ball.Location.Y)
xVel = -xVel
End If

'Check 4 computer
If ball.Bounds.IntersectsWith(PC.Bounds) Then
ball.Location = New Point(PC.Location.X + PC.Size.Width + 1, _
ball.Location.Y)
xVel = -xVel
End If
End Sub

' Move the paddle according to the mouse position.
Private Sub Player_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Player.MouseMove

If e.Y > 5 And e.Y < Me.Height - 40 - Player.Height Then _
Player.Location = New Point(Player.Location.X, e.Y)

End Sub

Private Sub Game_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Set up the game. (hid cursor)
Windows.Forms.Cursor.Hide()
End Sub
End Class

```

### #33 Jordan.M

Reputation: 0
• Posts: 16
• Joined: 26-April 11

Posted 26 April 2011 - 01:58 PM

ozzyosborne68, on 29 November 2008 - 10:06 AM, said:

great
even i understood it and im only 15
dude im 12 and i made a similar tut

### #34 Jordan.M

Reputation: 0
• Posts: 16
• Joined: 26-April 11

Posted 26 April 2011 - 02:07 PM

Jacques Malan, on 18 August 2010 - 11:23 AM, said:

I tried to add some code to close game once comp. player reaches 5 points, but my message box flies around and the game continues in the background.
```If compScoreDraw.Text = 5 Then
MessageBox.Show("You lose, better luck next time")
Me.Close()
End If

```

Any Help?

the code is

if compScoreDraw.Text = 5 Then
MsgBox("You lose, better luck next time")
End If

the reason you need to do this is if you say it your way it will show the message box, you need to just right the text after. plus you wrought the short form for message box wrong its "msgbox"

This post has been edited by Jordan.M: 26 April 2011 - 02:08 PM

### #35 manowar689

Reputation: 0
• Posts: 55
• Joined: 26-September 10

Posted 27 May 2011 - 09:24 AM

Ok I have successfully adapted this code to work in a game of mini golf which in in the screenshot that I have posted below I'm having issues with first of all making the ball move to the direction of the cursor until it reaches a wall and two the wall shooting the ball off in the opposite direction aka using the angle of the line shape which one point is attached to the ball and the other end attached to the cursor with the mousemove form event so what I need to do is have it travel that line till a wall intersection and the come off at the opposite angle of the wall any ideas

Reputation: 3
• Posts: 139
• Joined: 23-May 11

Posted 22 July 2011 - 11:22 AM

How do I move the ball so that sometimes it will go faster than others?

### #37 lbecker34

Reputation: 0
• Posts: 10
• Joined: 23-November 11

Posted 23 November 2011 - 05:59 PM

Cookiesliyr, on 09 June 2009 - 04:54 AM, said:

will nice work Rodger, about the difficult it won't be funny to make the computer slower as easier , to make the computer easier and beatable make it play as a human ! will how is that ? will not exactly like human but what does human do ? will they r not perfect so they won't follow the ball all the time , so u can make a random number which the computer will decide what to do, for example

random number between 1 to 100

if the number is between 1 to 50 => follow the ball
if the number is between 51 to 80 => stand still (do nothing)
if the number is between 80 to 100 => move in opposite direction

so in different difficult the range will change , so easy computer will stand still or move in the wrong way most of the time unlike the hard one.

i hope u get the idea how to make a beatable computer, btw i won't write the code i am sure u can do it

I generated the random number and it did make the computer beatable, but it made the computers movements very jumpy and of course random. Is there a way to make it smoother? Or do you think I may have entered the code wrong?

### #38 lbecker34

Reputation: 0
• Posts: 10
• Joined: 23-November 11

Posted 23 November 2011 - 07:04 PM

CodesALot, on 03 June 2010 - 12:06 PM, said:

If you use the following code to move the computer paddle, the game is winnable. I used the suggestion of one of the others to incorporate random numbers. You can play with the range of the random numbers to affect the skill of the computer. I also added an invisible label control to slow the game down a bit (if the random number generated is an even number) which increases the likelyhood that the computer paddle will not always move to the correct location. I also created a constant for the X axis of the computer paddle since it will always be the same.

' Move computer depending upon random number generated
Dim objRandom As Random
Dim intRandom As Integer
objRandom = New Random()
intRandom = objRandom.Next(0, 100)
If (intRandom Mod 2) = 0 Then
lblRandom.Text = intRandom.ToString
End If
If (intRandom < 5) Or (intRandom > 95) Then
End If

Where did you get "lblRandom" from?

### #39 Othinolis

Reputation: 0
• Posts: 1
• Joined: 28-January 12

Posted 28 January 2012 - 09:28 AM

When I build the program, both paddles end up on the right side. Here's my code:
```Public Class pongMain
#Region "Globals"
Dim speed As Single = 10 ' Ball Speed
Dim rndInst As New Random() ' Random instance
Dim xVel As Single = Math.Cos(rndInst.Next(5, 10)) * speed
Dim yVel As Single = Math.Sin(rndInst.Next(5, 10)) * speed
' The player's scores.
Dim compScore As Integer = 0
Dim plrScore As Integer = 0
#End Region
#Region "Keep the paddle and score labels in the correct position when the form is resized."
Private Sub pongMain_SizeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.SizeChanged
plrScoreDraw.Location = New Point(Me.Width - 54, plrScoreDraw.Location.Y)
End Sub
#End Region

#Region "Hide Cursor"
' Set up the game.
Private Sub pongMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Windows.Forms.Cursor.Hide()
End Sub
#End Region

#Region "End Game on Escape Press"
' Escape the game when escape has been pressed.
Private Sub pongMain_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.KeyValue = Keys.Escape Then
Me.Close()
End If
End Sub
#End Region

#Region "Move the paddle according to the mouse"
' Move the paddle according to the mouse position.
Private Sub pongMain_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove

If e.Y > 5 And e.Y < Me.Height - 40 - paddlePlayer.Height Then _

End Sub
#End Region

#Region "Main Timer"
Private Sub gameTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gameTimer.Tick
'Set the computer player to move according to the ball's position."
If gameBall.Location.Y > 5 And gameBall.Location.Y < Me.Height - 40 _
' Move the game ball.
gameBall.Location = New Point(gameBall.Location.X + xVel, gameBall.Location.Y + yVel)
' Check for top wall.
If gameBall.Location.Y < 0 Then
gameBall.Location = New Point(gameBall.Location.X, 0)
yVel = -yVel
End If
' Check for bottom wall.
If gameBall.Location.Y > Me.Height - gameBall.Size.Height - 45 Then
gameBall.Location = New Point(gameBall.Location.X, Me.Height - gameBall.Size.Height - 45)
yVel = -yVel
End If
gameBall.Location = New Point(paddlePlayer.Location.X - gameBall.Size.Width, _
gameBall.Location.Y)
xVel = -xVel
End If
gameBall.Location.Y)
xVel = -xVel
' Check for left wall.
If gameBall.Location.X < 0 Then
plrScore += 1
gameBall.Location = New Point(Me.Size.Width / 2, Me.Size.Height / 2)
plrScoreDraw.Text = Convert.ToString(plrScore)
End If
' Check for right wall.
If gameBall.Location.X > Me.Width - gameBall.Size.Width - paddlePlayer.Width Then
compScore += 1
gameBall.Location = New Point(Me.Size.Width / 2, Me.Size.Height / 2)
compScoreDraw.Text = Convert.ToString(compScore)
End If
End If

End Sub
#End Region
End Class

```

### #40 filiparag

Reputation: 0
• Posts: 1
• Joined: 28-May 12

Posted 28 May 2012 - 12:16 PM

I think there is a quite easy solution! I know VB.NET but I don't
know the correct solution in Visual Basic. Here is my "solution" :

```
Dim compSkill As Random()

...

If compSkill <= 100 Then
Else
paddleComputer.Location = New Point("Help me make PC like another human") 'I want to invert my moves or make them random
End If

```

...and thanks for the code, RodgerB!

### #41 NM138

Reputation: 0
• Posts: 2
• Joined: 03-June 12

Posted 03 June 2012 - 05:54 AM

Hi, i made the game but when i enable the timer the escape button doesn't work anymore. Do you know how i can solve this?
thx NM138

### #42 NM138

Reputation: 0
• Posts: 2
• Joined: 03-June 12

Posted 04 June 2012 - 11:08 AM

hi,i've got a problem with the escape key when I insert the timer then the escape key doesn't work anymore do you have any idea how I can solve this?
cheers

### #43 mina62

Reputation: 0
• Posts: 1
• Joined: 07-June 13

Posted 07 June 2013 - 08:48 AM

```Public Class frmPongMain
'This game is called pong and is a very fun game in which the human player has to compete with the computer player and the one with the most points wins.
Dim speed As Single = 10 ' Ball Speed
Dim rndInst As New Random() ' Random instance
Dim xVel As Single = Math.Cos(rndInst.Next(5, 10)) * speed
Dim yVel As Single = Math.Sin(rndInst.Next(5, 10)) * speed
' The player's scores.
Dim compScore As Integer = 0
Dim plrScore As Integer = 0
#Region "Hide cursor"
' Set up the game.
Private Sub pongMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Windows.Forms.Cursor.Hide()
End Sub
#End Region

#Region "Move the paddle according to the mouse"
' Move the paddle according to the mouse position.
Private Sub pongMain_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
If e.Y > 5 And e.Y < Me.Height - 40 - playerPaddle.Height Then _
End Sub
#End Region

#Region "Main Timer"
Private Sub gameTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gameTimer.Tick
If gameBall.Location.Y > 5 And gameBall.Location.Y < Me.Height - 40 _
gameBall.Location = New Point(gameBall.Location.X + xVel, gameBall.Location.Y + yVel)
If gameBall.Location.Y < 0 Then
gameBall.Location = New Point(gameBall.Location.X, 0)
yVel = -yVel
End If
If gameBall.Location.Y > Me.Height - gameBall.Size.Height - 45 Then
gameBall.Location = New Point(gameBall.Location.X, Me.Height - gameBall.Size.Height - 45)
yVel = -yVel
End If
gameBall.Location = New Point(playerPaddle.Location.X - gameBall.Size.Width, _
gameBall.Location.Y)
xVel = -xVel
End If
gameBall.Location.Y)
xVel = -xVel
End If
If gameBall.Location.X < 0 Then
plrScore += 1
gameBall.Location = New Point(Me.Size.Width / 2, Me.Size.Height / 2)
plrScoreDraw.Text = Convert.ToString(plrScore)
End If
If gameBall.Location.X > Me.Width - gameBall.Size.Width - playerPaddle.Width Then
compScore += 1
gameBall.Location = New Point(Me.Size.Width / 2, Me.Size.Height / 2)
compScoreDraw.Text = Convert.ToString(compScore)
End If
End Sub
#End Region

#Region "End Game on Escape Press"
' Escape the game when escape has been pressed.
Private Sub pongMain_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.KeyValue = Keys.Escape Then
Me.Close()
End If
End Sub
#End Region

#Region "Keep the paddle and score labels in the correct position when the form is resized."

Private Sub pongMain_SizeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.SizeChanged
plrScoreDraw.Location = New Point(Me.Width - 54, plrScoreDraw.Location.Y)
End Sub
#End Region
End Class
```

the problem occuring is that the player paddle is going to the side of the computer paddle (on the right side) when I debug. But, in the design view the player paddle is on the left side. What is wrong in the coding. Please help me out, my teacher wants to see it working by 14th. Please. Thank you very much.

This post has been edited by macosxnerd101: 07 June 2013 - 09:09 AM
Reason for edit:: Please use code tags. Removed personal info per user request.

### #44 PhobicVOid

Reputation: 0
• Posts: 2
• Joined: 17-November 13

Posted 17 November 2013 - 10:53 PM

Hi I've had a problem where my pong ball has being knocked out the top of the 640, 480 form it will disappear and when
it respawns it does it again continuously so I have to restart it.
Thanks PhobicVOid

### #45 pulpdrew

Reputation: 0
• Posts: 1
• Joined: Yesterday, 03:05 PM

Posted Yesterday, 03:10 PM

RodgerB, on 17 December 2007 - 12:34 AM, said:

Hello and welcome to this tutorial on creating a Pong game in VB.NET. This tutorial will cover:
• Making the paddle move according to the mouse position.
• Creating a computer player.
• Moving the ball.
• Making the ball bounce.
• Game Flow.
• Hiding the cursor.
• Ending the game on an Escape KeyPress.
• Keeping the controls in the right place when the form is resized.

I chose to create a tutorial on creating a Pong game as I have only seen snippets on the internet, and I thought it would be relatively hard for someone new to game design to understand how they worked. This tutorial won't require any 3D libraries such as DirectX or OpenGL, as we will be using PictureBox controls. Without any further ado, lets start creating our pong game!

1) Setting up our game room!

A vital part of any game is a place to play! Basketball requires a basketball court, boxing requires a ring (well it doesn't really but you get the picture), and this is no different. We will start by setting the Form's Size to 640x480. This will give ample playing space for a game of pong. Set the BackColor property to something nice, I chose LightSkyBlue, but again thats a personal preference thing. Set the Text property to Pong, obviously because this is a Pong game, and set the Form's name to pongMain, simply because this is the main room of the pong game.

Now, whats a room without furniture? We need to add some controls now, so add three PictureBox controls to the form. Set the Name properties to paddleComputer, paddlePlayer and gameBall. For both paddlePlayer and paddleComputer, set the Size property to 16x128. For gameBall, set the Size property to 20x20. Select all three controls, and set the BackColor to a color of your preference; I chose LimeGreen.

Now add two Label's to the Form. These will display the score of both the Computer and the Player. Name them compScoreDraw and plrScoreDraw. Set the Font property to a style you'd prefer. I chose Size 18 with Bold and kept the Microsoft Sans Serif font, but you can set it to whatever you'd like.

Now, move the controls so the form looks something like this:
[img]http://img339.imageshack.us/img339/4283/pongsq1.png[/img]

Now add a timer control to the form. This will be our main game loop. Name it gameTimer, and set the Interval property to 20ms, and the Enabled property to True. Now that we have our controls and form set up, we can move on to developing the actual game.

2) Making the paddle move according to the mouse position.

Making the paddle move according to the mouse position isn't as hard as you'd think, however it requires a little bit of math (not a lot) to ignore the mouse if it is below the minimum or maximum height we want. We will want to use pongMain's MouseMove event so we can easily get the Cursor position and we won't need to be checking for movement all the time, and make good use of the .NET Framework.

Assuming you named the controls correctly, you can copy and paste the following into your code.
```#Region "Move the paddle according to the mouse"
' Move the paddle according to the mouse position.
Private Sub pongMain_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove

If e.Y > 5 And e.Y < Me.Height - 40 - paddlePlayer.Height Then _

End Sub
#End Region

```

I like to use Region's as it is easier to browse through segments of code, and makes reading the source easier for people new to it. Breaking down the code, if e.Y (the Y position of the cursor) is more than 5 (it looks better having it more than 5) and e.Y is less than 40 (to be honest I am unsure why I needed to take 40 off, but it seemed too look right when I did so) minus the height of the paddle, then set the paddle's position relative to it's X position, but relative to the mouse's position on the Y Axis. This is how we make it follow the mouse.

3) Creating a Computer Player.

The computer player is our opposition, this is the person we want to beat. Unfortunately, the computer player we will be making is a god at pong. It would seem that it doesn't get tired or bored, doesn't rage quit quite as often as a human, so beating this player is relatively impossible. But don't fret, you can always move the code provided here into a new timer so you can adjust the difficulty by the speed of the timer. But that is something to worry about later on, now we just want to be able to play the game. />/>

To move the computer player, we are going to want it to move according to the ball's position. Add the following code to make the paddle follow the ball. We will be using the gameTimer control we made previously when we were designing the form.

```#Region "Main Timer"
Private Sub gameTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gameTimer.Tick
'Set the computer player to move according to the ball's position."
If gameBall.Location.Y > 5 And gameBall.Location.Y < Me.Height - 40 _
End Sub
#End Region

```

The code is almost exactly the same as the player following the mouse, rather we will be following the ball with the computer player. Well, if the ball were moving it would be following it. />/>

Now we need to create the code to move the ball.

4) Moving the ball.

Moving the ball requires some basic mathematic skills. We will be slightly touching Cosine's and Sine for the X and Y velocity of the ball, and the speed of the ball. However, you don't require any knowledge of Cosine and Sine with this tutorial, unless you'd like to understand what you were doing.

We are going to need some global variables so we can accomplish this, so we will add these just after the Public Class pongMain declaration.

```#Region "Globals"
Dim speed As Single = 10 ' Ball Speed
Dim rndInst As New Random() ' Random instance
Dim xVel As Single = Math.Cos(rndInst.Next(5, 10)) * speed
Dim yVel As Single = Math.Sin(rndInst.Next(5, 10)) * speed
#End Region

```

speed is obviously the rate of movement the ball will be performing. The higher the faster, the lower the slower. rndInst is our object for the randomisation of the angle of movement we will be undertaking on creation. xVel and yVel are given a random angle, with a minimum value of 5 and a maximum of 9. We will multiply this value by the speed.

Now we need to add the following line of code to the gameTimer timer to move the ball.
```' Move the game ball.
gameBall.Location = New Point(gameBall.Location.X + xVel, gameBall.Location.Y + yVel)

```

Now we should have a ball that moves, a computer player that follows the ball, and a paddle that follows the mouse. Now we need a way of keeping the ball in the playing area, and bouncing it off so we can continue playing without being so rudely interrupted. />/>

5) Making the ball bounce.

Making the ball bounce is easier than you may initially think. We need to put code in the gameTimer timer again, because we need it constantly checking if the ball needs to bounce or not.

To make the ball bounce, it is just a matter of setting the ball's position to contact the surface of the wall, and set the velocity opposite to it's current velocity. How would we set it opposite you ask? By making it negative. So hypothetically, we will be testing to see if the ball hits the wall, and if it does make it bounce off the wall. Here is how we would do this using the top wall. Note that you will need to add this to the Main Timer region, inside the timer subroutine.

```' Check for top wall.
If gameBall.Location.Y < 0 Then
gameBall.Location = New Point(gameBall.Location.X, 0)
yVel = -yVel
End If

```

Note that we only want to invert the Y Axis as we aren't dealing with any advanced spinning physics. The ball should now bounce off the wall and continue in it's path; which is obviously what we want.

Now we will need to make the code for the bottom wall. When checking for the collision, we need to to check if the ball is higher than the form's height minus the height of the ball, and we will take off 45 to line it up.

```' Check for bottom wall.
If gameBall.Location.Y > Me.Height - gameBall.Size.Height - 45 Then
gameBall.Location = New Point(gameBall.Location.X, Me.Height - gameBall.Size.Height - 45)
yVel = -yVel
End If

```

Now we have the ability to make the ball bounce up and down. Now that we can do this... I think it would be a good time to demonstrate how we can make the ball bounce off the paddles. It is actually relatively simpler than the form's walls, so don't worry, the head scratching is done for this section.. kinda. We will start with the player paddle. We will need to add the following to the main timer, as the main timer is for collisions and other miscellaneous tasks.

```' Check for player paddle.
gameBall.Location = New Point(paddlePlayer.Location.X - gameBall.Size.Width, _
gameBall.Location.Y)
xVel = -xVel
End If

```

This will check if the ball has intersected with the paddle object and bounce it off if it did. It is the same with the computer paddle too; the process involved is the same pretty much.

```' Check for computer paddle.
gameBall.Location.Y)
xVel = -xVel
End If

```

Now that we have the ball bouncing, we need to add Game Flow.

6) Game Flow.

Game Flow in pong is basically, you lose if the ball goes past the paddle. When it goes past the paddle we want the ball to go back to the middle of the form, and give the winner a point, which will be displayed in the label.

In order to give the players a score, we will need two global variables indicating them. In the Globals region, add the following code so we can start using these score variables.

```' The player's scores.
Dim compScore As Integer = 0
Dim plrScore As Integer = 0

```

Now we want to do something with these variables, otherwise we would just be wasting precious memory. Add the following to the main timer, as we are checking for a collision with the left wall.

```' Check for left wall.
If gameBall.Location.X < 0 Then
plrScore += 1
gameBall.Location = New Point(Me.Size.Width / 2, Me.Size.Height / 2)
plrScoreDraw.Text = Convert.ToString(plrScore)
End If

```

We will add one to the player's score, as he/she has scored, set the ball's position to the middle of the form and we will set the plrScoreDraw.Text property to display the player's score.

We will do the same thing if the computer wins, except we will be checking to see if the right wall has been hit.

```' Check for right wall.
If gameBall.Location.X > Me.Width - gameBall.Size.Width - paddlePlayer.Width Then
compScore += 1
gameBall.Location = New Point(Me.Size.Width / 2, Me.Size.Height / 2)
compScoreDraw.Text = Convert.ToString(compScore)
End If

```

Now that we have this functionality, the game is in a playable state. Now to a couple of 'nice to have' features.

7) Hiding the cursor.

Hiding the cursor is probably the easiest subject we will be covering in this tutorial. Basically, we want to hide the cursor while it's in the form, but not when it's outside it. We will want to add this functionally as soon as the form is loaded, so add the following code to the class.

```#Region "Hide Cursor"
' Set up the game.
Private Sub pongMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Windows.Forms.Cursor.Hide()
End Sub
#End Region

```

With this done, lets move on to ending the game on an Escape KeyPress.

8) Ending the game on an Escape KeyPress.

Ending the game on an Escape KeyPress is a pretty simple task, where we will be checking if the Escape key is down and we will close the form if this is the case. We will be using the KeyDown event, so please copy and paste the following code into your class.

```#Region "End Game on Escape Press"
' Escape the game when escape has been pressed.
Private Sub pongMain_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.KeyValue = Keys.Escape Then
Me.Close()
End If
End Sub
#End Region

```

This will add the functionality of escaping the program when Escape is pressed.

9) Keeping the controls in the right place when the form is resized.

When the form is resized, if the form is made smaller than our 640x480, the player's paddle will be lost, thus making it insanely easy for the computer to score. A free shot if you will. Now, being the human we rather this not happen to us (I'm sure there is a competitive side to everyone), so we would rather the paddle adjusted itself when the form is resized. Also, when the form is resized the the player's score may be hidden, or not situated on the screen properly. Because we'd rather have this functionality, lets add it now. We will be using the SizeChanged event kindly provided from our form, so checking if the form has been resized is easy. Add the following code to your class.

```#Region "Keep the paddle and score labels in the correct position when the form is resized."
Private Sub pongMain_SizeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.SizeChanged
plrScoreDraw.Location = New Point(Me.Width - 54, plrScoreDraw.Location.Y)
End Sub
#End Region

```

10) Conclusion.

You should now have a fully functional pong game. I hope you had fun creating this game, and will have learnt something from this. Thanks for reading, and enjoy. />/>

[code]
This is my edition. I added in the ability for the computer player to lose:

Public Class pongMain

#Region "Globals"
Dim speed As Single = 15 ' Ball Speed
Dim rndInst As New Random() ' Random instance
Dim xVel As Single = Math.Cos(rndInst.Next(7, 10)) * speed
Dim yVel As Single = Math.Sin(rndInst.Next(5, 7)) * speed
Dim compScore As Integer = 0
Dim plrScore As Integer = 0
Dim shouldIGo As Integer
#End Region

#Region "Move the paddle according to the mouse"
Private Sub pongMain_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
If e.Y > 5 And e.Y < Me.Height - 40 - paddlePlayer.Height Then
End If
End Sub
#End Region

#Region "Main Timer"
Private Sub gameTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gameTimer.Tick
If (shouldIGo > 6) Then
If gameBall.Location.Y > 5 And gameBall.Location.Y < Me.Height - 40 - paddlePlayer.Height Then
End If
End If
gameBall.Location = New Point(gameBall.Location.X + xVel, gameBall.Location.Y + yVel)
If gameBall.Location.Y < 0 Then
gameBall.Location = New Point(gameBall.Location.X, 0)
yVel = -yVel
End If
If gameBall.Location.Y > Me.Height - gameBall.Size.Height - 45 Then
gameBall.Location = New Point(gameBall.Location.X, Me.Height - gameBall.Size.Height - 45)
yVel = -yVel
End If
gameBall.Location = New Point(paddlePlayer.Location.X - gameBall.Size.Width, gameBall.Location.Y)
xVel = -xVel
End If
xVel = -xVel
End If
If gameBall.Location.X < 0 Then
plrScore += 1
gameBall.Location = New Point(Me.Size.Width / 2, Me.Size.Height / 2)
plrDrawScore.Text = Convert.ToString(plrScore)
End If
If gameBall.Location.X > Me.Width - gameBall.Size.Width - paddlePlayer.Width Then
compScore += 1
gameBall.Location = New Point(Me.Size.Width / 2, Me.Size.Height / 2)
compDrawScore.Text = Convert.ToString(compScore)
End If
End Sub
#End Region
#Region "Hide Cursor"
Private Sub pongMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Windows.Forms.Cursor.Hide()
End Sub
#End Region
#Region "End Game on Escape Press"
Private Sub pongMain_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.KeyValue = Keys.Escape Then
Me.Close()
End If
End Sub
#End Region
#Region "Keep the paddle and score labels in the correct position when the form is resized."
Private Sub pongMain_SizeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.SizeChanged
plrDrawScore.Location = New Point(Me.Width - 54, plrDrawScore.Location.Y)
End Sub
#End Region