Hello VB
Article Index
Hello VB
Running the program
A Lunar Lander
Event routines and liftoff!

 

This is the basis of the lander game but to turn it into something more fun we are going to need quite a lot more VB code.

In particular we need a fire button and something to represent the ground.

Add a button to the form. Change the button's Text to "Fire Rocket".

If you want to make your rocket look more interesting then you can also create another picture of it with its engines firing. This can be loaded into the image control whenever the fire button is clicked.

 

Fire

You need to add this to the Project resources file, just as you did for the first image of the lander. This second image isn't displayed in the PictureBox - it is waiting ready for us to use it.

Now we have all of the objects in place on the form, all that remains is to define the event routines to make it work.

First you need to define two variables in the declarations section. To do this simply use the Code window and enter just below Public Class Form1:

Dim velocity As Integer
Dim fuel As Integer = 100.

What all this means will be discussed in full in later chapters. Next go to the Timer1 object's event handling routine and enter:

Private Sub Timer1_Tick(
    ByVal sender As System.Object,
    ByVal e As System.EventArgs) 
                 Handles Timer1.Tick
 velocity += 1
 Lander.Image = My.Resources.LAND1
 Lander.Top += velocity
 If (Lander.Top + Lander.Height) >=
                 (Me.Height - 35) Then
  Timer1.Enabled = False
  If velocity < 20 Then
   MsgBox("Good Landing",
                   MsgBoxStyle.OkOnly)
  Else
   MsgBox("C R A S H",
                   MsgBoxStyle.OkOnly)
  End If
  End
 End If
End Sub
Finally select the button's event and enter:
Private Sub Fire_Click(
    ByVal sender As System.Object,
     ByVal e As System.EventArgs)
       Handles Fire.Click
 fuel -= 30
 If fuel > 0 Then
  velocity -= 2
  Lander.Image = My.Resources.LAND2
 End If
End Sub

That's all there is to it. Now when you run the program you can try to land your craft. It isn't difficult and there are lots of extras you could add to the game, such as a read out of fuel, side thrusters etc. We will return to this simple game later on to add all of these.

 

game

 

To access the complete project including the graphics once you have registered,  click on CodeBin.

This is the first chapter of the ebook Master Visual Basic 2010.

See also:

Chapter 2 - Mastering VB Properties

Chapter 3 - Mastering VB Events

Chapter 4 - Mastering VB Controls

Chapter 5 - Graphics and Animation

If you would like to be informed about new articles on I Programmer you can either follow us on Twitter, on Facebook , on Digg or you can subscribe to our weekly newsletter.

<ASIN:0672331004 >

<ASIN:0470499834>

<ASIN:0470502223>

<ASIN:0735626693>

0672331004