|
Intro
Alright, welcome to the tips and tricks tutorial. This tutorial is just here to introduce to you more code so we can move on pretty quickly in future tutorials without having to explain everything in depth.
The Loops
The first thing we're gonna look at is different types of loops(you don't have to create a project for this tutorial, most of it is pretty self explanatory)
What is the purpose of a loop? Loops are used for a variety of things, ranging from animation to outputting data to the user, to reading textfiles..etc.
-For Loop-
The For loop, in my opinion, has the easiest syntax out of all of them. The syntax is
For [variable] = [number] To [Number]
'Stuff to do
Next
For example,
For x = 1 To 3
MessageBox.Show(X) '(Dreamweaver wont let me add a space here!?)
Next
This would result in 3 messageboxes, displaying 1, 2 and 3. Simple wasn't it? Alright then, let's throw in some changes to this.
For x = 3 To 1 Step -1
MessageBox.Show(X)
Next
This would result in 3 messageboxes, displaying (this time) 3,2 and 1. This is because of the fact that you're going down by 1 each time you step through the loop(hence the step -1).
-While Loop-
The While Loop is also easy, it may not be as simplistic as the For loop, but it's still easy to follow.
The structure is pretty basic:
While [condition}
'do stuff
End while
An example:
x = 0
While x < 3
MessageBox.Show(x)
x = x + 1
End While
This would result in 3 MessageBoxes showing up, displaying (note the difference) 0, 1 and 2. If you wanted it to display 1, 2, and 3, do this then:
x = 1
While x <= 3
MessageBox.Show(x)
x = x + 1
End While
Note: it says <= instead of <. So it'll include the number 3. If you actually follow through the loop, you'll see that this will work. Another way of getting it to display 1,2 and 3 is:
x = 0
While x <= 3
x = x + 1
MessageBox.Show(x)
End While
Take a look at the changes a little more closely. You'll, with a little logic, that it does display 1,2, and 3. This is why i tend to prefer the For loop better, because there's (essentially) only 1 way of doing it. Those are the 2 basic types of loops.
Tips & Tricks
These are basic tips and tricks listed below to make your coding a little easier. I'll go through these breifly as they are self-evident :-p
-Variables-
Instead of saying:
Dim x as integer
Dim y as integer
You can say:
Dim x,y as integer
This next thing, you might not be able to understand right away, so it might help if you create a project.
Create a button, and in button1_click, type in
Dim x as Integer
MessageBox.Show(x)
x = x + 1
Now wait a second, you'd expect that the next time you click the button you'll get 0.. and then 1... and then 2..and so on. But you wont. Why? Becuase you're dimming it again each time you click the button. Everytime you Dim an integer, its automatically set to 0. When you MessageBox this, you'll get 0 and then 0.. and then 0.. and then 0.. etc. You could put the dim at the declarations and get away with this, but what if you didn't want too many varialbes in your declarations (or something random like that :-p)
Static x as Integer
MessageBox.Show(x)
x = x + 1
Static means, next time you dim it (or technically, static it), it'll have the same value as before. So now when you messageBox, you'll get your expected results. Again, it might make a little more sense if you create a project and experiment this, but if you understand it, great!
--
The next thing we're gonna do is basically to save you some time. Lets say you have a collection of variables to store the position,direction, and frame of each sprite:
Dim alexPos as point
Dim alexDir as string
Dim alexFrame as integer
Dim pentPos as point
Dim pentDir as string
Dim pentFrame as integer
Dim guyPos as point
Dim guyDir as string
Dim guyFrame as integer
Now, it would take QUITE a long time to do this if you had a LOT of sprites. Another way of making this easier to code is to create a Structure
Structure Sprite
Dim Pos As Point
Dim Dir As String
Dim Frame As Integer
End Structure
Dim alex As Sprite
Dim pent As Sprite
Dim guy As Sprite
'and then in order to use these things, you would do:
alex.Dir = "something"
pent.Frame = something
guy.Pos.X = something
Note: Remember, a point has an X and a Y property, which is why we have to say guy.pos.X and guy.pos.Y.
The method above saves a LOT of code. Instead of typing in 9 lines of code, you an just create a structure and type in 3! Test it out yourself ;) its useful.
--
This part deals with arrays(Remember our Tic-Tac-Toe game?). Lets say, (for some reason), we didn't know how big a tic tac toe feild was, but we KNOW that it is a 2 dimensional array(such as gamefield(3,3) or gamefield(5,7), 1 dimensional arrays are like something(2) or something(4)) When we declare our ClickedSquare Boolean array(and we DONT know what the size of the array is, we can declare it like so:
Dim ClickedSquare(,) as Boolean 'the comma tells it its a 2d array, a 1d array would look like ().
and when we
DO know the size of the array, we can say
ReDim ClickedSquare(3,3) as Boolean
*Note: Let's say that earlier in the program you set (for example) ClickedSquare(1,1) = true. When you ReDim it, it'll become false(remember how we used Static variables because when you Dim agian, the boolean will become its default value(for booleans, the default is False)). A way to PRESERVE that (1,1) = true or any element in the array is by saying:
ReDim Preserve ClickedSquare(3,3) as Boolean
This would preserve each element in the array without setting them back to their default values.
--
This part deals with speeding up your program. Remember back in the calculator tutorial where the inputs would be stored from the textbox? (it was something like MyNumber = TextBox1.Text) Well, TextBox1.Text returns a STRING, and MyNumber is an Integer.
In most languages, the compiler would NOT let you do that(set a string equal to an integer, or vice versa, as with any other different types). VB.NET automatically converts the string(TextBox1.Text) to an Integer in order to store that value into; but, the problem is, VB.NET has to find a way of converting it, and it has to choose the right one. If we chose the right converter ourself, it would execute the code much quicker because VB.NET doesnt have to choose.
There's various types of Type Converters.
CInt 'means 'Convert to Integer'
CBool 'Convert to Boolean"
CString 'Convert to String'
CSng 'Convert to Single(integer w/ decimal)'
CDbl 'Conver to Double(A single, but holds more digits(decimal places), singles may round off some numbers, but doubles wont)'
How would you use this? Easy! Let's go back to the MyNumber = TextBox1.Text example. Pretend MyNumber is an Integer.
MyNumber = CInt(TextBox1.Text)
If MyNumber was a Double then you'd say
MyNumber = CDbl(TextBox1.Text)
Another example, let's say you wanted TextBox1.Text = MyNumber
TextBox1.Text is a string, so you'd do
TextBox1.Text = CStr(MyNumber)
Again, whats the point of all this? The point is, when doing this, it speeds up your application. If you were making a game, you'd need as much speed as you can get; AND, programming a game usually requires a great deal of math(well, it depends on the type of game you're making), so this will speed up calculations.
What's a good way of making SURE that im doing this? At the VERY top, where it says Public Class Form1, type in Option Strict On, and it'll notify you of anything you might have forgotten. Also, if you don't know what type of variable it is, hover over it. For example, type in TextBox1.Text = "hi" , and hover over "text", it'll say something like, "Public Overlods property Text as String()", the As String will tell you what type it is...(obviously its a String!!)
-Debugging-
This section deals with Debugging errors, the most annoying thing you have to deal with when you program. VB.NET introduces a way to handle erros. Its called a Try..Catch..Block. You might not really find use for it now, but as you go advanced in programing you WILL find that this is very useful. Here's the structure for a Try Catch block
Try
-'type in the
code that might cause an error
Catch
-'if there is an error, type in some code to report it to the user
End Try
For example, let's say you have a 3 by 3 integer array called Stuff (Dim stuff(3,3) as integer). You KNOW that there's no element Stuff(3,4) becuase the array is 3 by 3. So let's use that as an example.
Try
Stuff(3,4) = 1
Catch
MessageBox.show("Stuff(3,4) is out of bounds of the array Stuff(3,3)
End Try
However, this is useless because we'd have to go around trying to guess what each error is. A way of actually reporting the error without guessing what it is, is throwing an exception>
Try
Stuff(3,4) = 1
Catch ex as Exception
MessageBox.Show(ex.ToString)
End Try
This would report the error. The reason why you have to say "ToString" is, an Exception is a Type, and it cannot be directly MessageBox'ed. The ToString basically tells you to return the String value of the Exception. If we ran this, it would MessageBox, "Index was out of bounds of the array Stuff(3,3)."
However, you might think that this is also useless. The program is going to report an error anyways, regardless of weather you used Try..Catch..EndCatch or no. Actually, the advantage of using this is it lets your program continue, so that you can fix the error after you're done testing everything else out. Think about it, if you're making an RPG, and you find one error, and you have to fix that.. and then you fix it and run it again, you find another error, and then you stop and fix this other error -- this gets really tedious. Why not just keep a note of it in your mind, and fix it later.
There's one more thing i want to point out. Obviouisly while you're executing a program, you can't continue until you close the MessageBoxes. If your program had tons of errors, it would be hard to keep note of that. Here's another alternative:
Change: MessageBox.Show(ex.ToString)
To: Console.Writeline(ex.ToString)
When your program is done executing, at the bottom of your IDE, there's a little "Output" tab (if you haven't messed with the IDE settings, it should be there by default), you can view your errors and stuff there.
--
This section deals with finding out variable names while your program is running. Of course, you could always messagebox them, but that gets tedious. VB.NET offers an alternative. Let's say there is a place in your program that you are unsure of what a variable is set to, or someting like that(trust me, when you program more advanced programs, you'll experience this problem a lot), and you wanted to know what a variable is. Here's what you would do:
In your code editor, there's a little grey area, to the right of the tool box, but to the left of where the + (or - ) signs are. When you're typing code that's in a sub, click that.
You'll immediately see your code be highlighted in a maroon color. This is known as a breakpoint.
In form1_load, type in:
Dim X as integer
X = 1 <-- insert breakpoint here; for some reason you cant insert a breakpoint when you Dim.
X = 2
MessageBox.Show(X).
(This program is useless becuase you set X to 1 and then to 2.. but its there just for an example). Run your program. When it executes the code in maroon, your program will pause. (It might be easier to understand if you created a project for this and tested it yourself). Ok, now minimize your form. In the VS.NET IDE, go to Debug | Windows | Autos(Control + alt + V). Look for 3 icons that says "Step Into" "Step Over" and "Step out" on one your VS.NET toolbars(for me, it's the 3rd one down from the top, to the right of the yellow arrow).
In the autos, an "x" will appear, succeeded by "value". In our case, "value" will be 1. Press Step Into (you might have to do this twice), the "value" column for the x variable will change to 2. Step Into goes to the next line, and it will take you through the entire sub. Step over will execute the statement BLOCK by BLOCK. Step out will take you out of the sub.
Let's say your code was this:
Sub DoSomething()
Dim x as integer
x = 1
x= 2
End Sub
in form1_load:
DoSomething() <-- place a breakpoint on this line
The first time you run the program, keep pressing Step Into. You'll see that when it gets to the "DoSomething()" line, it'll take you through the entire sub. Close the program and run again. This time keep pressing Step Over. When it gets to the "DoSomething()" line, it will execute that sub without going through and checking each and every line. (Its much easier to see this visually)
This tool is very useful if you want to know the way your program executes and learn your program flow of execution; and this is also useful to know what your variables are before messageboxing them :)
Note: Did you notice how the form didn't show up until AFTER form1_load? Form1_load just means "when the form was loaded into memory", it doesnt mean when it was shown. To fix that, type in Me.Show at the beginning of form1_load :)
-Tips and Tricks-
"All in 1 line" - Type a colon at the end of a line in order to join all your lines together
MessageBox.Show("hi") : MessageBox.Show("hi again")
"Multiline" - Use a _ to let your code continue on multiple lines
MessageBox.Show("this is your really long message which you cant fit on more than one line or you dont _
want to scroll through it, use a _ to notify that you want to *continue* on the next line _
you _
can _
do _
as many as you want _
make sure that the _
has a space before it")
"Dimming quickly" -
instead of
Dim X as integer
X = 3
do this
Dim X as integer = 3
--
If you've got any more tips and tricks, post it on the forum (my mind is blank right now :p)
The Source
Code for this tutorial is located here: (OK there's no source for this tut :p)
You can also
locate this by logging in to vbProgramming Forums and going
to: Tutorials > Tutorial Source Code >
Source Code
|
|