Thursday, November 4, 2010

Pong in VB.NET!

Hey there everyone, today I am going to show you how you can make pong in visual basic.net.  Please note that I am not going to put all of the code up here because that would be crazy.

This is what the main form looks like:

This is all drawn with objects from the tool bar, no special graphics experience required.

Now lets look at some code:
First of all, here are the variables used:

Dim speed As Single = 10 'This stores the speed of the ball
Dim rndInst As New Random() 'This is a random number generator
Dim xAng As Single = Math.Cos(rndInst.Next(5, 10)) 'X and Y
Dim yAng As Single = Math.Sin(rndInst.Next(5, 10)) 'Angles
Dim xVel As Single = xAng * speed 'The x and y velocities
Dim yVel As Single = yAng * speed 'Computed from angle and speed
Dim pScore As Int16 = 0 'Player's score
Dim cScore As Int16 = 0 'Computer's score
Dim cSpeed As Int16 = 10 'Movement speed of computer (difficulty)
Dim p As Boolean 'Is the game paused?



I used a timer to control the speed of the game, that way it doesn't go super fast on your brand new gaming computer.  To pause the game I used the code:


p = True
gameTimer.Stop()
speedTimer.Stop()
lblPaused.Visible = True


The speed timer is used to increase the speed every few seconds to make the game progress (otherwise you would be hitting the ball between you and the computer until you or your computer died).  


I made the user control their paddle by moving the mouse, their paddle would simply stay with the mouse as it moved.  The following code was used to accomplish this:



If e.Y > 29 And e.Y < Me.Height - 30 - playerPaddel.Height Then
  playerPaddel.Location = New Point(playerPaddel.Location.X, e.Y)
End If


This code was placed in the 'mouseMove' form event.  The logic in the if statement was used to keep the paddle within the vertical bounds of the screen.


The computer's paddle tried to follow the ball no matter where the ball was in the hopes that it would be in the way of the ball when the ball reached it's side.  The following code was used for the 'AI':



If gameBall.Location.Y > compPaddle.Location.Y Then
If compPaddle.Location.Y < Me.Height - 40 - playerPaddel.Height Then
If compPaddle.Location.Y - (gameBall.Location.Y) > -cSpeed Then
   compPaddle.Location = New Point(compPaddle.Location.X, gameBall.Location.Y)
Else
   compPaddle.Location = New Point(compPaddle.Location.X, compPaddle.Location.Y + cSpeed)
End If


The first if statement just decides if the computer needs to move.  If it is already at the same level as the ball, then it does not need to move.  The second if statement decides if the computer paddle needs to move the full amount it can, or if a smaller amount will get it where it wants to be.  Finally, if it did need to move, and it did need to go as far as it can, then that is exactly what it does.


To update the location of the game ball, the following code was used:


gameBall.Location = New Point(gameBall.Location.X + xVel, gameBall.Location.Y + yVel)


I think that is pretty self-explanatory, so I will move on.  (On a completly unrelated note, the text editor I am using is saying that 'yVel' is spelled wrong, but 'xVel' is not.  I don't know what the deal is there, I am pretty sure that xVel is not a word.)  


The last piece of interesting code is the code that decides when the ball has hit a paddle.  The following was used to complete this task:



If gameBall.Bounds.IntersectsWith(playerPaddel.Bounds) Then
   gameBall.Location = New Point(playerPaddel.Location.X - gameBall.Size.Width, gameBall.Location.Y)
   xVel = -xVel
End If


The same code was used for the walls and for the computer's paddle.  It basically asks if the bounds of the ball are intersecting with the bounds of the player's paddle.  If they are, it changes the position of the ball so that it is not inside the paddle and then makes the ball travel in the opposite x direction.  This results in a very realistic bounce effect without even using elastic physics!


Well, that is pretty much all I have to say,  I hope you enjoyed this and hopefully learned something.  Until next time, 'Happy Coding!'


Wednesday, November 3, 2010

Multi-threading With Visual Basic

Ok, today we are going to talk about multi-threading.  I would give this lesson a difficulty of MODERATE not because it is difficult to code it, but because multi-threading can be a bit confusing conceptually.

First off, what is multi-threading and why is it useful?  Well, when your program is running normally, aka you are not using multi-threading, it can only execute one instruction at a time.  Only one line of code is running at any given time.  If you use multi-threading, you can be running as many lines of code at once as you want.  Now don't go and try to make a program where each line of code has its own thread and think you have discovered ultimate efficiency, because there are a few catches to multi-threading.  Any segments of code that run at the same time cannot be dependent on each other.  For example, if you have two functions, and the output of the first function is used as input for the second, you cannot run them at the same time.  If the first one isn't finished, the second one can't start.  Another catch to multi-threading is that if you are using a single core computer, the benefits of multi-threading will not be as great.  This is because when there are multiple threads on a single core computer, they cannot truly run at the same time, so instead, the take turns running a little bit.  This occurs so quickly that they appear to be running at the same time, but in reality they are not.  If you have a computer with more than one processor core, then your computer can actually run more than one instruction at the same time. .

On to the programming...

To create a new thread, you declare a variable of type thread.

Dim newThread as Thread


Then you must initialize it as a new thread.  The new function for threads accepts an argument of type ThreadStart.  The best way to handle this is to create a new ThreadStart.  The argument for this new sub is 'AddressOf' and the name of the subroutine that you want the new thread to run.


newThread = new Thread(new ThreadStart(AddressOf doStuff))


That code assumes that you have defined a subroutine named 'doStuff'.  For the subroutine that you want the new thread to run, you can put just about anything in it.  In one program I created, I wanted to use every core the computer had to find prime numbers.  I did this by creating a loop that created a new thread for each processor and added them to an arraylist of threads.  Then each one was told to run the same subroutine that found prime numbers.  I made this subroutine a loop so that the threads would run continuously until I stopped them.  That is one way you can use multi-threading, but there are many more.  Say for example you are writing a game and you want the character's stats to be updated every half of a second regardless of what the program is doing. You could create a timer that would run the update subroutine on a separate thread every half a second.  This would allow the stats to update even if the rest of the program was busy.  For that example it is very important that you do not let any of the other threads modify the controls that your update thread is using, if that happens the entire universe may unravel at it's seams.  Not really but it would be bad so just don't do it.


That is about all I have to say on multi-threading, I hope you enjoyed reading this and hopefully you learned something.  Multi-threading is a powerful tool, especially in today's world of many core computers, multi-threading is the way of the future.


On a side note, I just realized that I am writing about programming and I didn't even provide a link to free software that you can use to program in. Tsk, tsk, on me...


So here it is: Visual Basic 2010 Express
To download visual basic 2010 express, just go to the visual basic header and expand it, then select the language that you prefer.  This is free software that is provided by Microsoft, so enjoy it.

Note: If this link does not work because you are reading this way after it was written, just google 'Visual Studio Express Download'
Wait, I will even do that for you: Click here to Google it!


Thanks for reading, if you have any good ideas for more topics, feel free to email them to me.




Monday, November 1, 2010

Best Way To Learn Programming

Ok, first of all this is excluding the obvious answer of going to a programming class.  This is also assuming that you have enough basic programming knowledge that most beginner tutorials are kind of a waste of time.  This is a phase that many self taught programmers get stuck in.  They can program enough that writing 'Hello World' isn't going to teach them anything.  Unfortunately there are not near as many intermediate tutorials out there as there are beginner tutorials.  However there is still hope for self teaching.

The method I have used to expand my programming knowledge after the beginner stage was to simple write lots of programs.  Any time I would think of something that could be done by the computer, I would make it into a program.  I got to the point where I wanted to program but could not think of any ideas of what to make.  At that point I started to ask the people around me if they had any ideas of programs that they would like to use but have never seen.  I have found that a very good way to learn programming is to just program.  My recontamination to anyone who wants to learn programming is to write every program that comes to mind.  Even if you are not sure how to do everything that will be needed for that program, go ahead and start it and when you find you need to do something that you have no clue how to do, google it. If you can't figure out what google tells you or there is not very much info on the topic you need, you could also find help at a talk board for the language you are using.  If Visual Basic .NET is your thing, which I would think it is since you are reading this, then VB.NET Forums is a pretty good place to go for help.  When you are thinking of ideas to make, it is good to be ambitious, but only to a point.  You must keep your ideas realistic, you don't know how badly I would like to write SKYNET, but that just isn't going to happen from one person with no AI experience.  You can make the program do something very complex or difficult, but you need to keep the scale relatively small or you will have to devote a huge amount of time to writing it and you won't be able to learn other things.

So basically, the best way, in my opinion, to learn programming is to practice.  I know that is a foreign concept to many people.  But practice really does help.  Also try to work together with other programmers, sometimes they will have a different way of doing things that you may like.

I hope you enjoyed this and maybe learned something.  Remember if you have any ideas for future topics, please email them to me.

Sunday, October 31, 2010

Custom Classes

Alright, today we are going to talk about custom classes.  This is, in my opinion, a really cool aspect of Object Orientated Programming.  This allows you to create custom data types that can be used throughout your project.  Not only does this save tons of code, but it makes keeping your program organized easier and makes everything look neater.

The difficulty is EASY!!!

Ok, let's say you are writing a program that will track gas mileage for cars.  Now lets pretend that you are writing the piece of code that will deal with adding a new trip.  Let's say you have a form that has places to put in the different pieces of data.  Let's also assume that you have a database class that is used to read and write from the database. You could write:

Dim tripMileage as Int16
Dim tripDate as Date
Dim gasUsed as Double




DataBase.AddTrip(tripMileage, tripDate, gasUsed)


And that would work fine.  But when you got to a point where you wanted to list all of the trips a user had put in, what are you going to do?


You could:
Dim tripMileage() as Int16
Dim tripDate() as Date
Dim gasUsed() as Double


This would be creating arrays of each type to use to store the data for each trip.  The biggest problem with that is you must know beforehand how many trips you are dealing with.  Also I personally never liked using arrays like this.  What I would recommended doing is create a class called Trip.vb and using it to store trip information as its own data type.  Ex:


Public Class Trip
  Public tripMileage as Int16
  Public tripDate as Date
  Public gasUsed as Double


  Public sub new()
    tripMileage = 0
    tripDate = new Date()
    gasUsed = 0.0
  End Sub
End Class


Then you could have the sub that gives you the list of every trip just give you an ArrayList of type Trip.  You would use these trips as data types in your programming like this:


Dim t as new Trip()
t = DataBase.getNewestTrip()
labelTripMileage.Text = t.tripMileage
labelTripDate.Text = t.tripDate.ToShortDateString()
labelGasUsed.Text = t.gasUsed
labelGasMileage.Text = Math.Round(t.gasUsed / t.tripMileage, 2)


As you can see the variable t is of type Trip, this can make things a lot easier when programming to have a data type that is exactly what you are dealing with in your program.  


I hope you had fun and learned something.  If you have any good ideas for topics, feel free to email them to me.

Wednesday, October 6, 2010

First Post

Alright, here we go...
This is my new blog.  First a little about me, I am a student at Virginia Tech.  I am currently a freshman.  I plan to study Computer Engineering.  All of the Visual Basic programming knowledge I have is self taught, I have never taken a VB class in my life, and I don't think I ever will.  I am a very big fan of the .NET framework, and I absolutely love Visual Studio.  I have never felt quite as comfortable with any other IDE (Integrated Development Environment) other than Visual Studio.  I started programming on a TI-84 calculator and then moved on to VB.NET which I still use to this day.  I can also program in JAVA and C#.NET and will soon be learning C++.

But enough about me, lets do something with programming...

For my fist example / lesson, I will be demonstrating the use of Message Boxes.  I know that this is a very elementary topic, but you have to start somewhere, and I don't want to scare away any new programmers out there.

Difficulty: VERY EASY

To use a message box as a notification, you simply use the code:

MsgBox("Your message goes here!", ,"Message Box Title")


The reason I have that blank argument in there is because that is where the message box style would go.  For this example, we just wanted the message box to be a notification, so it only needs an 'OK' button.  Lucky for us that is the default style.  If you don't have a specific title in mind for the message box, you can simply close end the argument list with the message and the title will be the name of your application.


If you want to ask a question with the message box, such as yes or no, you must set a style parameter.  You must also be ready to receive the answer.



Dim ans As New MsgBoxResult
ans = MsgBox("Do you want to save before exiting?", MsgBoxStyle.YesNoCancel, "Save?")


If ans = MsgBoxResult.Yes Then
     ' Save and exit
End If
If ans = MsgBoxResult.No Then
     ' Don't save and exit
End If
If ans = MsgBoxResult.Cancel Then
     ' Don't save and don't exit
End If


As you can see here, I allowed there to be three possible answers to the question I asked: Yes, No, or Cancel.  First I had to declare a variable to store the user's response in.  This type of variable is aptly named 'MsgBoxResult'.  Then I told the program to assign the value of the message box to the variable I declared.  As you can see for the style parameter, I used 'MsgBoxStyle.YesNoCancel'  this tells the computer that you want a message box with those three options.  Now don't get confused, you can just put any old thing there, you must pick a style that exists.  


I can't think of much else to say about message boxes, that is about the limit of their functionality, so I will wrap up with a few notes to remember about message boxes.


- While the message box is showing, the program does not run.  What I mean is the code stops at the line of the message box and waits for the user to dismiss the message box before continuing.  This can be useful if you want to check on variable values in the middle of a complex operation. 
- Message boxes usually pop up on top of your application.  One exception to his is in ASP.NET (web page programming)  where the message box may not popup on top of the web browser.  I have not figured out how to fix this and it is very annoying.  Due to that flaw, message boxes are virtually useless in web programming.


I hope you enjoyed this little talk, and hopefully learned something.  If you have a good idea for next time feel free to email them to me.