Home > Code Dump > Simple Implementation of Pong in VB.NET

Simple Implementation of Pong in VB.NET

A simple implementation of pong
By 28/12/10 [Last Edited by Joseph 04/02/11]
BOOKMARK
LOGIN
REGISTER
Made this in one of my computing lessons

Download Visual Basic Express 2005 sources: PingPong.zip

Form Elements Required

  • Panel named 'panBall'
  • Timer named 'timMoveObj'
  • Panel named 'panPlayer'

Screenshot

Source

Public Class frmMain
    Dim moveBackX As Boolean
    Dim moveBackY As Boolean
    Dim panBallNextLoc As Point
    Dim panUserNextLoc As Point
    Dim speedX As Integer = 5
    Dim speedY As Integer = 5

    Private Sub timMoveObj_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timMoveObj.Tick
        If panBall.Location.X >= Me.Size.Width - panBall.Size.Width - 15 Then moveBackX = True
        If (panBall.Location.Y >= panPlayer.Location.Y And panBall.Location.Y <= (panPlayer.Location.Y + panPlayer.Size.Height)) _
                And panBall.Location.X <= (panPlayer.Location.X + panPlayer.Size.Width) Then
            moveBackX = False
        ElseIf panBall.Location.X <= 0 Then
            moveBackX = False
            timMoveObj.Enabled = False
            If MsgBox("Game Over, You lost. Do you want to start a new game?", MsgBoxStyle.YesNo, "Game Over") = MsgBoxResult.Yes Then
                timMoveObj.Enabled = True
            Else
                End
            End If
        End If
        If moveBackX = True Then panBallNextLoc.X = panBallNextLoc.X - speedX Else panBallNextLoc.X = panBallNextLoc.X + speedX
        If panBall.Location.Y >= Me.Size.Height - panBall.Size.Height - 30 Then moveBackY = True
        If panBall.Location.Y <= 0 Then moveBackY = False
        If moveBackY = True Then panBallNextLoc.Y = panBallNextLoc.Y - speedY Else panBallNextLoc.Y = panBallNextLoc.Y + speedY
        panBall.Location = panBallNextLoc
    End Sub


    Private Sub frmMain_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        Select Case e.KeyValue
            Case 83 'Down S key
                If (panPlayer.Location.Y + panPlayer.Size.Height) + 20 <= Me.Size.Height Then panUserNextLoc.Y = panUserNextLoc.Y + 20
            Case 87 'Up W key
                If panUserNextLoc.Y - 20 >= 0 Then panUserNextLoc.Y = panUserNextLoc.Y - 20
        End Select
        panUserNextLoc.X = 0
        panPlayer.Location = panUserNextLoc
    End Sub
End Class