.Net Beginner. Please help with game code

alibi jackson

Member
Joined
Jan 17, 2006
Messages
6
Programming Experience
Beginner
Hi

I'm new to VB.Net and have been trying some low-level coding. I'd like
to improve my knowlege and skill and am just about to attempt to code a
hide and seek type game for my daughter. Might anyone be able to spend
a few minutes reading thru some code I downloaded and describe the
function of each line so that I might understand the principle a little
better. I have VB books but am struggling to decipher them in relation
to this. Any help would be much appreciated.


Thanks in advance


Andy

VB.NET:
Public Class Game 
  Inherits System.Windows.Forms.Form 


  Dim GameOver As Boolean 
  Dim P(4, 2) As Integer, Map(9, 9) As Integer 
  Dim Tries As Integer 
  Dim Remaining As Integer 


  Dim MyMap As Graphics 
  Dim GridBorder As Integer 
  Dim GridDelta As Integer 


  Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load 
    MyMap = pnlGrid.CreateGraphics 
    Randomize() 
    'find grid dimensions 
    GridBorder = 10 
    GridDelta = CInt((pnlGrid.ClientSize.Width - 2 * GridBorder) / 10) 
    lblMessage.Text = "Find the four Ninjas hidden on a 10 x 10 grid. After each guess, you are told how far you are from each Ninja." 
    lblMessage.Text = lblMessage.Text + ControlChars.CrLf + 
    ControlChars.CrLf + ">Click Play To Start<" 'label text 
    btnPlay.Focus() 'display game start text 
  End Sub 

  Private Sub pnlGrid_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles pnlGrid.Paint 
    Dim I As Integer, J As Integer 
    For I = 0 To 10 'draw grid 
      MyMap.DrawLine(Pens.White, GridBorder, GridBorder + I * 
      GridDelta, GridBorder + 10 * GridDelta, GridBorder + I * GridDelta) 
      MyMap.DrawLine(Pens.White, GridBorder + I * GridDelta, 
      GridBorder, GridBorder + I * GridDelta, GridBorder + 10 * GridDelta) 
    Next I 
    'draw guesses and ninjas 
    For I = 0 To 9 
      For J = 0 To 9 
        If Map(I, J) = 1 Then 
          MyMap.FillRectangle(Brushes.White, GridBorder + I * 
          GridDelta + 1, GridBorder + (9 - J) * GridDelta + 1, GridDelta - 1, GridDelta - 1) 
        ElseIf Map(I, J) = -1 Then 
          MyMap.DrawImage(picninja.Image, GridBorder + I * GridDelta, GridBorder + (9 - J) * GridDelta, GridDelta, GridDelta) 
        End If 
      Next J 
    Next I 
  End Sub 

  Private Sub btnPlay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPlay.Click 
    Dim I As Integer, J As Integer 
    'Start new game 
    GameOver = False 
    lblMessage.Text = "" 
    btnPlay.Enabled = False 
    Remaining = 4 
    Tries = 0 
    lblNinjas.Text = "4" 
    lblGuesses.Text = "0" 
    MyMap.Clear(pnlGrid.BackColor) 
    For I = 0 To 9 
      For J = 0 To 9 
        Map(I, J) = 0 
      Next J 
    Next I 
    For I = 1 To 4 
      Do 
        For J = 1 To 2 
          P(I, J) = Int(10 * Rnd()) 
        Next J 
      Loop Until Map(P(I, 1), P(I, 2)) = 0 
      Map(P(I, 1), P(I, 2)) = 1 
    Next I 
    For I = 1 To 4 
      Map(P(I, 1), P(I, 2)) = 0 
    Next I 
    pnlGrid_Paint(Nothing, Nothing) 
    lblMessage.Text = "Four Ninjas are now in hiding." + 
    ControlChars.CrLf + "Click where you think they are." 
    lblMessage.Refresh() 
  End Sub 
  
  Private Sub btnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStop.Click 
    Dim I As Integer 
    'Either exit or stop current game 
    If btnStop.Text = "Exit" Then 
      Me.Close() 
    Else 
      btnPlay.Enabled = True 
      If Not (GameOver) Then lblMessage.Text = "Game Stopped" 
      btnPlay.Focus() 
    End If 
  End Sub 

  Private Sub pnlGrid_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles pnlGrid.MouseDown 
    Dim I As Integer 
    Dim M As Integer, N As Integer 
    Dim D As Single 
    Dim Found As Boolean 
    If btnStop.Text = "Exit" Then Exit Sub 
    If e.X < GridBorder Or e.X > GridBorder + 10 * GridDelta Then Exit Sub 
    If e.Y < GridBorder Or e.Y > GridBorder + 10 * GridDelta Then Exit Sub 
    'Find column 
    For M = 0 To 9 
      If e.X >= GridBorder + M * GridDelta And e.X <= GridBorder + (M + 1) * GridDelta Then Exit For 
    Next M 
    'Find row 
    For N = 9 To 0 Step -1 
      If e.Y >= GridBorder + (9 - N) * GridDelta And e.Y <= GridBorder + (10 - N) * GridDelta Then Exit For 
    Next N 
    If Map(M, N) <> 0 Then Exit Sub
     Map(M, N) = 1 
    Tries = Tries + 1 
    lblGuesses.Text = Format(Tries, "0") 
    lblGuesses.Refresh() 
    lblMessage.Text = "" 
    Found = False 
    For I = 1 To 4 
      If P(I, 1) <> -1 Then 
        If P(I, 1) <> M Or P(I, 2) <> N Then 
          D = Math.Sqrt((P(I, 1) - M) ^ 2 + (P(I, 2) - N) ^ 2) 
          lblMessage.Text = lblMessage.Text + "You are " + 
          Format(D, "0.0") + " units from Ninja" + Str(I) + ControlChars.CrLf 
        Else 
          Found = True 
          P(I, 1) = -1 
          Map(M, N) = -1 
          lblMessage.Text = lblMessage.Text + "You found Ninja" + Str(I) + ControlChars.CrLf 
          Remaining = Remaining - 1 
          lblNinjas.Text = Format(Remaining, "0") 
          lblNinjas.Refresh() 
        End If 
      End If 
    Next I 
    If Found Then 
      'draw ninja in column M, row N - use picture 
      MyMap.DrawImage(picninja.Image, GridBorder + M * GridDelta, GridBorder + (9 - N) * GridDelta, GridDelta, GridDelta) 
    Else 
      MyMap.FillRectangle(Brushes.White, GridBorder + M * GridDelta + 1, GridBorder + (9 - N) * GridDelta + 1, GridDelta - 1, GridDelta - 1) 
    End If 
    If Remaining = 0 Then 
      GameOver = True 
      lblMessage.Text = lblMessage.Text + ControlChars.CrLf + "You found all 4 Ninjas!" + ControlChars.CrLf + "It took you" + Str(Tries) + " guesses." 
      btnStop.PerformClick() 
    End If 
  End Sub
End Class
 
Last edited by a moderator:
Ok, i'll make a start for you. Hopefully someone else can help out a bit as it's rather late here.
But if not i'll get back to you tommorrow...

VB.NET:
[COLOR=darkgreen]'The declaration of the class and it's name.... Declared as public so can be seen by all. [/COLOR]
[COLOR=darkgreen]Game - the name to reference this class when instantiating it in another object i.e class etc.[/COLOR]
Public Class Game 
 
[COLOR=darkgreen]Inherits form - meaning it's a form which descends from a control class - [/COLOR]
[COLOR=darkgreen]checkout the inheritance hierachy of .net framework. In Vb.Net everything inherits [/COLOR]
[COLOR=darkgreen]from something except system.object which is the base class for all classes.
[/COLOR]Inherits System.Windows.Forms.Form 
 
[COLOR=darkgreen]'Gameover a variable declared as boolean (I.e True or False) used to [/COLOR]
[COLOR=darkgreen]indicate later if the game has completed.
[/COLOR]Dim GameOver As Boolean 
[COLOR=darkgreen]'Two 2 dimensional arrays. Think of them as X,Y axis 4 by 2, 9 by 9 ,except that [/COLOR]
[COLOR=darkgreen]arrays are zero based so actually you have a 10 by 10 map which is the game board i assume.[/COLOR]
  Dim P(4, 2) As Integer, Map(9, 9) As Integer 
 
[COLOR=darkgreen]' Tries declared a integer(a number) this will used in the game to indicate how many goes [/COLOR]
[COLOR=darkgreen]the user has had at finding the ninja. i.e everytime a square is clicked for example the [/COLOR]
[COLOR=darkgreen]tries variable will be incremented.
[/COLOR]Dim Tries As Integer 
[COLOR=darkgreen]' Same as above just a variable to hold a numeric value to indicate how many goes [/COLOR]
[COLOR=darkgreen]the player has left before the game exits - remember 'gameover as boolean?'
[/COLOR]Dim Remaining As Integer 
 
[COLOR=darkgreen]'A graphics object with which to draw the game surface - check out GDI+
[/COLOR]Dim MyMap As Graphics 
[COLOR=darkgreen]'A numeric value again to hold the x co-ordinate on the gameboard, [/COLOR]
[COLOR=darkgreen]so it knows where to draw the horizontal lines
[/COLOR]Dim GridBorder As Integer 
[COLOR=darkgreen]'Another numeric variable to hold a calculation a bit further down in code. [/COLOR]
[COLOR=darkgreen]If i'm honest it's too late to try to figure out what it does, but suffice to say the above [/COLOR]
[COLOR=darkgreen]two integer variables have to do with the drawing of the gameboard.[/COLOR]
 [COLOR=black] Dim GridDelta As Integer[/COLOR] 

End Class
 
Last edited by a moderator:
Thanks Vis!

Hi Vis

This helps immensely, having someone with good .Net knowledge explain is far clearer than trying to cherry pick the necessary info from Sam's 'Learn .Net'.

Thanks so much for your time, if you're able to do the same with the remainder then you are a true legend.

Andy
 
Ok, looks like i'm on my own then?! Never mind, next part....

The load Event....

VB.NET:
'[COLOR=darkgreen]Dead easy, subroutine that handles the load event of the game.[/COLOR]
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load 
[COLOR=darkgreen]'remember 'MyMap As Graphics' Well this is the bit that tells the panel( a control on the form [/COLOR]
[COLOR=darkgreen]itself (Called PnlGrid)) [/COLOR][COLOR=darkgreen]to create a graphics object(surface) to draw on.[/COLOR]
    MyMap = pnlGrid.CreateGraphics 
[COLOR=darkgreen]'Random Number generator[/COLOR]
    Randomize() 
    'find grid dimensions 
[COLOR=darkgreen]The two integer variables from above, to 'build' the game board. [/COLOR]
[COLOR=darkgreen]See what i mean about that complex math part?[/COLOR]
    GridBorder = 10 
    GridDelta = CInt((pnlGrid.ClientSize.Width - 2 * GridBorder) / 10) 
[COLOR=darkgreen]'Easy one. change the text of a label control to some game info.[/COLOR]
    lblMessage.Text = "Find the four Ninjas hidden on a 10 x 10 grid. 
After each guess, you are told how far you are from each Ninja." 
[COLOR=darkgreen]'Not sure why they did this, it could all have been put into the above line, [/COLOR]
[COLOR=darkgreen]but hey ho. Control chars.CrLf (Carriage Return i.e goto the point where the [/COLOR]
[COLOR=darkgreen]textalignment is set. LineFeed i.e Start a new line. [/COLOR]
[COLOR=darkgreen]And display the text >click play to start<. [/COLOR]
[COLOR=darkgreen]If i had written this i would have done...[/COLOR]
[COLOR=blue]LblMessage.text = "Finds the four ninjas hidden on a 10x10 grid. [/COLOR]
[COLOR=blue]After each guess, you will be told how far you are from each [/COLOR]
[COLOR=blue]ninja" + controlchars.CrLf + ">Click Play To Start<"
[/COLOR]lblMessage.Text = lblMessage.Text + ControlChars.CrLf + 
    ControlChars.CrLf + ">Click Play To Start<" 'label text 
[COLOR=darkgreen]'Set the focus to the play button.
[/COLOR]btnPlay.Focus() 'display game start text 
  End Sub
 
Last edited:
Makes sense so far

Hi Vis

This makes perfect sense so far, and I kind of understood that bit from my reading and net research. the real killer for me was the remainder. I can't see how the code checks which square has been clicked, whether it contains a ninja or not, and how it generates the "You are ...squares away from ninja .. etc.."

Thanks again

Andy
 
Ok, this is gonna get pretty complex so bear with me.......

VB.NET:
[COLOR=darkgreen]'Mouse Down event, you know this part....[/COLOR]
Private Sub pnlGrid_MouseDown(ByVal sender As Object, 
ByVal e As System.Windows.Forms.MouseEventArgs) Handles pnlGrid.MouseDown 
'[COLOR=darkgreen]Some variables, bring them in later....[/COLOR]
    Dim I As Integer 
    Dim M As Integer, N As Integer 
    Dim D As Single 
    Dim Found As Boolean 
[COLOR=darkgreen]If the text on the stop button has been changed to exit then stop  here..[/COLOR]
    If btnStop.Text = "Exit" Then Exit Sub 
[COLOR=darkgreen]Byval e as system.blah,blah.mouseeventargs. right this 'e' if you put a dot [/COLOR]
[COLOR=darkgreen]after it will expose some methods. This program is using e.x and e.y these are the [/COLOR]
[COLOR=darkgreen]current position of the mouse pointer in x,y co-ordinates.[/COLOR]
[COLOR=#006400]So code below is checking the mouse position to see if it's inside the game board [/COLOR]
[COLOR=#006400]when the mouse button is pressed. If its not then don't need to go any further. (exit sub)[/COLOR]
    If e.X < GridBorder Or e.X > GridBorder + 10 * GridDelta Then Exit Sub 
    If e.Y < GridBorder Or e.Y > GridBorder + 10 * GridDelta Then Exit Sub 
[COLOR=darkgreen]'If we got this far then the pointer is inside the gameboard sowe need to find out where.[/COLOR]
    'Find column 
[COLOR=darkgreen]'Loop through all the 10 columns(remember arrays are zero based) to find the [/COLOR]
[COLOR=darkgreen]position of the pointer[/COLOR]
    For M = 0 To 9 
[COLOR=darkgreen]If both these parts evaluate to true then we found the pointer on the x axis.[/COLOR]
      If e.X >= GridBorder + M * GridDelta [COLOR=blue]And[/COLOR] e.X <= GridBorder + (M + 1) * 
GridDelta Then Exit For 
[COLOR=darkgreen]Otherwise loop round again this time M will equal 1 then 2 and so on.
[/COLOR]  Next M 
    'Find row 
[COLOR=darkgreen]'Same as above really this time checking for the mouse position on the y axis. [/COLOR]
[COLOR=darkgreen]Notice EXIT FOR not EXIT SUB so the code will continue to execute after m = column [/COLOR]
[COLOR=darkgreen]number in our array, and n = a row number in our array.[/COLOR]
[COLOR=#006400]So there we have our current mouse position and that means we know [/COLOR]
[COLOR=#006400]where the mouse was clicked.[/COLOR]
    For N = 9 To 0 Step -1 
      If e.Y >= GridBorder + (9 - N) * GridDelta And e.Y <= GridBorder + 
(10 - N) * GridDelta Then Exit For 
    Next N 
[COLOR=darkgreen]' So here's our 2 dimensional MAP array and we check using the resulting variables [/COLOR]
[COLOR=darkgreen]form the previous 2 For, Next Loops. If the map co-ordinates does't equal 0 then we'er outta here.
[/COLOR]  If Map(M, N) <> 0 Then Exit Sub
[COLOR=darkgreen]'if it does, set it to 1
[/COLOR]   Map(M, N) = 1 
[COLOR=darkgreen]'Increment the tries variable. because they've had a guess[/COLOR]
    Tries = Tries + 1 
[COLOR=darkgreen]'Display the number of tries.
[/COLOR]  lblGuesses.Text = Format(Tries, "0") 
[COLOR=darkgreen]'Get the lblguesses label to repaint its self.
[/COLOR]  lblGuesses.Refresh() 
[COLOR=darkgreen]'Set the lblmessgae label to an empty string
[/COLOR]  lblMessage.Text = "" 
[COLOR=darkgreen]We didn't find a ninja so the variables at the top of the event, specifically [/COLOR]
[COLOR=darkgreen]the found variable equals false, cos we didn't find a ninja.
[/COLOR]  Found = False 
[COLOR=darkgreen]'All this part is to let you know how far away from the ninja you are.
[/COLOR]  For I = 1 To 4 
      If P(I, 1) <> -1 Then 
        If P(I, 1) <> M Or P(I, 2) <> N Then 
          D = Math.Sqrt((P(I, 1) - M) ^ 2 + (P(I, 2) - N) ^ 2) 
          lblMessage.Text = lblMessage.Text + "You are " + 
          Format(D, "0.0") + " units from Ninja" + Str(I) + ControlChars.CrLf 
        Else 
[COLOR=darkgreen]'We found one[/COLOR]
          Found = True 
          P(I, 1) = -1 
          Map(M, N) = -1
[COLOR=darkgreen]Set the text of the label
[/COLOR]        lblMessage.Text = lblMessage.Text + "You found Ninja" + Str(I) + ControlChars.CrLf 
[COLOR=darkgreen]Decrease the number of tries remaining
[/COLOR]        Remaining = Remaining - 1 
[COLOR=darkgreen]'Display how many tries are remaining.
[/COLOR]        lblNinjas.Text = Format(Remaining, "0") 
[COLOR=darkgreen]'Force a repaint.
[/COLOR]        lblNinjas.Refresh() 
        End If 
      End If 
    Next I 
[COLOR=darkgreen]we get here and if found has been set to true then..
[/COLOR]  If Found Then 
      'draw ninja in column M, row N - use picture 
[COLOR=darkgreen]'Draw an image on the map using a pre designed ninja image[/COLOR]
[COLOR=darkgreen](probably a bitmap)
[/COLOR]    MyMap.DrawImage(picninja.Image, GridBorder + M * GridDelta, 
GridBorder + (9 - N) * GridDelta, GridDelta, GridDelta) 
    Else 
[COLOR=darkgreen]We get here if a ninja wasn't found so found = false. Just color the [/COLOR]
[COLOR=darkgreen]square white so you know it's been clicked.
[/COLOR]    MyMap.FillRectangle(Brushes.White, GridBorder + M * GridDelta + 1, 
GridBorder + (9 - N) * GridDelta + 1, GridDelta - 1, GridDelta - 1) 
    End If 
[COLOR=darkgreen]Oh dear you've run out of tries
[/COLOR]  If Remaining = 0 Then 
[COLOR=darkgreen]remember 'gameover as boolean'[/COLOR]
      GameOver = True 
[COLOR=darkgreen]'if we found all four tell the user how many goes it took[/COLOR]
      lblMessage.Text = lblMessage.Text + ControlChars.CrLf + "You found all 4 Ninjas!" 
+ ControlChars.CrLf + "It took you" + Str(Tries) + " guesses." 
      btnStop.PerformClick() 
    End If 
  End Sub
 
Last edited:
Vis

I can't thank you enough for that mate, I'm now going to sit down for a few hours and get that straight in my mind. Will start my project this weekend, and post the finished code for your interest, I'm sure Megan is going to love this!

Your padawan

Andy
 
The Pythagorean Theorem

Just some useless info here.

VB.NET:
           D = Math.Sqrt((P(I, 1) - M) ^ 2 + (P(I, 2) - N) ^ 2) 
          lblMessage.Text = lblMessage.Text + "You are " + 
          Format(D, "0.0") + " units from Ninja" + Str(I) + ControlChars.CrLf
The program uses the Pythagorean Theorem (c2=a2+b2) to determine relative distance from a ninja and then displays it as a 1 place decimal - Format(D, "0.0").
 
Missed a bit....

Hi again

Sorry to bother you again but we missed some lines of code out. It's as below in the original post...your help, as ever, is invaluable


PrivateSub pnlGrid_Paint(ByVal sender AsObject, ByVal e As System.Windows.Forms.PaintEventArgs) Handles pnlGrid.Paint
Dim I AsInteger, J AsInteger
For I = 0 To 10 'draw grid
MyMap.DrawLine(Pens.White, GridBorder, GridBorder + I * GridDelta, GridBorder + 10 * GridDelta, GridBorder + I * GridDelta)
MyMap.DrawLine(Pens.White, GridBorder + I * GridDelta, GridBorder, GridBorder + I * GridDelta, GridBorder + 10 * GridDelta)
'draw white grid
Next I
'draw guesses and ninjas
For I = 0 To 9
For J = 0 To 9
If Map(I, J) = 1 Then'if incorrect guess then fill white
MyMap.FillRectangle(Brushes.White, GridBorder + I * GridDelta + 1, GridBorder + (9 - J) * GridDelta + 1, GridDelta - 1, GridDelta - 1)
ElseIf Map(I, J) = -1 Then'if correct guess then show ninja pic
MyMap.DrawImage(picninja.Image, GridBorder + I * GridDelta, GridBorder + (9 - J) * GridDelta, GridDelta, GridDelta)
EndIf
Next J
Next I
EndSub
PrivateSub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Dim I AsInteger, J AsInteger
'Start new game
GameOver = False
lblMessage.Text = "" 'clear previous label text
btnStart.Enabled = False'disable new game button
Remaining = 4
Tries = 0
lblNinjas.Text = "4"
lblGuesses.Text = "0"
MyMap.Clear(pnlGrid.BackColor)
For I = 0 To 9
For J = 0 To 9
Map(I, J) = 0
Next J
Next I
For I = 1 To 4
Do
For J = 1 To 2
P(I, J) = Int(10 * Rnd())
Next J
LoopUntil Map(P(I, 1), P(I, 2)) = 0
Map(P(I, 1), P(I, 2)) = 1
Next I
For I = 1 To 4
Map(P(I, 1), P(I, 2)) = 0
Next I
pnlGrid_Paint(
Nothing, Nothing)
lblMessage.Text = "Four Ninjas are now in hiding." + ControlChars.CrLf + "Click where you think they are."
lblMessage.Refresh()
EndSub
PrivateSub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Dim I AsInteger
'Either exit or stop current game
If btnExit.Text = "Exit" Then
Me.Close()
Else
btnStart.Enabled = True
IfNot (GameOver) Then lblMessage.Text = "Game Stopped"
btnStart.Focus()
EndIf
EndSub

Thanks

Andy


 
Back
Top