Hangman Game VB.NET

Part 1


This tutorial shows how to make a very simple game in visual studio 2010, I’m sure that all of you know the rules of hangman so this should be pretty simple.  I’ll give a quick summery on the different statement, loops, controls etc.

Downloading visual studio and starting a project

So the first thing that you need to do is download visual studio express 2010, the language that I’m using is visual basic.
You can download it from here: Visual Basic 2010 Express

Once you have downloaded the tool; open it and click on ‘New project’, then choose ‘Windows forms application’, give your application a name (I’ll call mine simply “hangman tutorial”) and press OK.

Visual Studio Overview

I’ll give a quick visual overview of visual studio before we begin.


Adding Controls

Now, the first thing we want to do is add the various controls that the user needs to play the game.

In the toolbox; click on the ‘buttons’ control and then click somewhere on your app to place it.




These buttons will be used for when the user wants to select a letter; so we need 26 of them. Select the first button, copy it with ctrl – c and paste it with ctrl – v, 25 times. You can change the size of the application form by dragging at one of its corners like you would with a window in any OS, in case the buttons start appearing outside of the form.

We need every button to represent a letter in the alphabet. But first we need to put them in a groupbox. A groupbox is basically a frame where you put controls that belong together. So select ‘groupbox’ from the toolbox and place it in your applications.


Now rename your groupbox by selecting it, then going to the properties panel and look for the ‘text’ property.


Where it says ‘groupbox1’ type in whatever you want to call it. I’ll call mine ‘letters’ .

Now comes the tedious part, we need to rename every button so that they represent a letter. We’ve already gone through how to rename a control so do this now. Also optionally we need to resize them; you do this the same way you would resize the form, by selecting the button and dragging at the corners. Also a very useful tip is to make sure that the letters all correspond to the number on the buttons, so the button that was called “button1” should be ‘A’ and the button that was "button2” should be ‘B’ and so on. When you are done it should look something like this


Now we need a place to display the word. We’ll do this with yet another group box and labels, a label is basically just text, you can write whatever you want in it with any font, but for now we're using them to display individual letter (we'll do this via code later). So select a groupbox from the toolbox panel, and then place labels in the group box, the labels can be found in the toolbox panel, we’ll be using words with a maximum of 8 letters, so use 8 labels. When you are done it should look something like this:


Now, in typical hangman style, we need a picture that displays the various states of the hangman. To do this we use a ‘picturebox’ which we select from the toolbox panel. Place the picturebox on top of the groupboxes and when you are done it should look something like this:


And lastly we want a button that initializes a new game. Take a button from the toolbox and place it under the groupboxes and call it ‘new game’.


Now we’re done with the UI for the most part, and we want to move on to the coding. As I said this isn’t a general introduction to programming, if you are having a hard time following along you should check out some tutorials on visual basic and play around a little before coming back. But if you feel like you can understand this then let’s move on.

Writing The Code

Double click on the ‘new game’ button and you will arrive at the coding tab. Here I’ll give another quick overview.


Now, you’re probably asking “am I supposed to type in every word that’s going to be included in the game?” Well no, of-course not, we’re going to read a .txt file from the game which contains all of the words. Download the file from here 

(right-click, save as) Dictionary.txt

And place it in your main harddrive as C:\dictionary.txt

Now we’re going to read this from the game. The first thing we need to do is import a namespace so that we can use .net’s file functions (I'll explain later).

So click at the very top of your code and type: 

 Imports System.IO

It should look like this:


Next we want to check if the dictionary file exists and give a message if it doesn’t.
So click in the sub (the area between 'private sub' and 'end sub') and type:

If File.Exists (“C:\dictionary.txt”then

Else

Messagebox.show(“Could not find the dictionary”)

End if


I’ll explain what this code does in the following picture, by adding comments (the green text). Visual basic ignores the green text, it’s just for show, so you don’t have to include it, if you don't want to. Otherwise if you do you just put any text after a " ' " sign (the one between the quotation marks)


The “IF” statement that we’ve used above should be self-explanatory, but in case you didn’t get what it does I’ll explain:

Basically the IF statement tells the machine to execute code if certain requirements are met, in this case the requirement was that the dictionary file existed, which we check with the 'file.exists' funtion.

The ELSE statement tells the machine what to do if the dictionary is not found I.E if the requirements for the IF statement are not met. In this case it shows a message to the user.

If you want, you can try this code out by pressing the little green play button at the top or pressing f5.
If it works then nothing will happen when you press the ‘New game’ button. If it doesn’t work then it will show the message (if it doesn't then it's probably a typo, check your code for errors).

This concludes Part 1 of this tutorial. Part 2 is here: Hangman Game Part 2

To save your project; click on 'File' and then 'Save all'.


Part 2



In the last tutorial: I showed you how to make the UI for the game and started very lightly on the coding side. Now we’re going to do a little more programming. So open visual studio and click on your project. It should be on the front page. If not then got to ‘File’ then ‘Open project’.

Read the words

Now that you’ve opened your project go to the coding tab. If you can’t see it then double click on the ‘New button’ button.Last time we told the machine what to do if the dictionary file was not found. This time we are going to tell the machine what to do if it is found.
Between the IF statement and the ELSE statement type:

Dim words() As String = File.ReadAllLines("C:\dictionary.txt")
What this does is reads all the lines in the dictionary and declares them as an array.

Dim = declare
words() = the name of the array (an array is basically a collection of strings, you indicate that a string is an array by having parentheses after the name)
As String = what we declare it as (a string is basically text which we can use for various things)
File.ReadAllLines = read all the lines in the dictionary.

When you are done it should look like this:


You can try this out by placing Messagebox.show(words(0)) under that code above. (the 0 is what line you want to show, in this case it’s the first word in the dictionary)

Randomness

Once you’re done playing around, remove the message box and where the message box was type:

Dim r As New Random(Sytem.DateTime.Now.Millisecond)
This declares ‘r’ as a random value based on what millisecond it’s declared. But we want this to be a random number. So next we need to declare r as a number that we can use whenever we want to.
Between ‘Public Class form1’ and ‘Private Sub’ type:

Public n as Integer 
Like this:


Basically we are saying that ‘n’ is a number and that we will tell the machine what number it is later.

So, under where we declared ‘r’ as random, type:

n = r.Next(0, 80368)

Here we are saying that ‘n’ is any random number between 0 and 80368, because that’s how many words there are in the dictionary.

So now we can randomly generate a word. To see each word you can create a new message box like this: 
Messagebox.show(words(n))

Now every time you press on ‘New game’ you should get a random word.

Next we want to find out which letters are in each word. We do this with our random number ‘n’ and a loop.

Loop through letters

A loop is basically a piece of code that runs over and over again depending on what kind of loop it is or what it does. In this case we’re using a ‘For Each’ loop, which is a loop that runs as many times as there are things to run through, or “for each item” as the name implies.

So remove your messagebox (or you can keep it if you want, it can be good for seeing if everything works) and type:

For Each i In words(n)

MessageBox.Show(i)

Next


We declare ‘i’ as any item (in this case letters) in a random word and show a messagebox “for each” letter that is in the word, pretty simple huh?

Just as a reminder, the messageboxes are only for testing, we won’t be using them in the game, since that wouldn’t be that much fun.

How many letters are there?

This is another simple one. Basically we tell the machine to count how many letters there are in a word and return it as a string.

Under your “For Each" loop type: 

Dim amount As Integer = words(n).Count()
This should be pretty self-explanatory by now. We’re saying that the variable ‘amount’ is a number and that the number is how many letters there are for each word.
Again you can display this with a messagebox by typing Messagebox.show(amount)

In case you missed something this is what my code looks like now:


To save your project go to 'File' and select 'Save all'.

Thus concludes Part 2.


Part 3


So we’ve got the words, letters and amount of letters, but how do we implement this graphically?

Show how many letters there are

Let’s start off simply by showing the number of letters in the word. Go the ‘design’ tab and from the toolbox select a label box. Place it wherever you want on your form, and in the properties for the label; go to ‘Font’. There you can select the size (click on the little button that appears when you click on the text besides ‘Font’) I chose 16 as my font size. Also I’ve renamed my labels so that I could fit them closely together. This is what it looks like:


Now in the coding tab place this code under where we declared the ‘amount’ variable:


Label9.Text = "Letters:" & " " & amount
The ampersand is used to concatenate the strings together (basically show the strings side by side). The first string is ‘Letters:’ the second string is empty space and the third string is the number of letters which we have declared as ‘amount’.

Run this to see what it looks like; as you can see the number of letters is presented in the label.


Show the letters in the game

If you have any message boxes remaining you can remove them since we are going to insert the letters into the game now, also remove the “for each” loop. 

Just for reference; this is what the code should look like:


 Now, where the “for each” loop was type: 


Dim letters() As Char = words(n)


Here we’re making an array which includes all the letters (aka “char”) in the word.

And under this we need to declare another integer which we will use soon.

Dim idxnum As Integer = 0

Next we will make a “For Each” loop, coupled with an “IF” statement which will place the letters in each label.



For Each labelitm As Label In Me.GroupBox2.Controls 
          If idxnum = amount - 1 Then               
                         labelitm.Text = letters(idxnum)    
      
                  Else labelitm.Text = ""          

                  End If
idxnum = idxnum + 1 
Next 



If you understood this code then you can skip the italicized text below.

What we’ve done here is declare “labelitm” as all of the labels in Me.Groupbox2.Controls. We could have declared it as any label in the form but that would have included labels which aren’t meant for showing letters.

We’ve also said that for each label that we find in the groupbox we are going to increment idxnum by 1. Idxnum is used to specify which letter in the word goes is used. For example if we wanted to use the first letter then we would type “letters(0)” if we wanted to use the second letter then we would type “letters(1)” and so on. But since we don’t want to write a huge block of code for each letter that’s used; we just declare an integer an increment it by one for each label.

However this causes problems since we might get a word with fewer letters than there are labels. That’s why we use the IF statement to tell the machine that “As long as idxnum is less than the amount of letters: insert the letters into the labels. But when the idxnum is greater than the labels: forget the idxnum and just rename the rest as an empty space.


You can try this now. You don’t need a messagebox. Just start the game and press on the ‘new game’ button.

Misplaced letters and changing the font


Now I don’t know about you but my letters are all misplaced. I actually have no idea why this happens (maybe it doesn’t happen to you) but if it does you can go to the design tab; and then right click on the first label in the groupbox, then click on “bring to front”, and then for the rest of the labels select “bring to back” but do this in order from left to right and it should work.

Also I personally think that the letters are too small. We can change this be changing the font for each label. I’ll raise mine to 12. You’ll probably need to make the groupbox bigger in order to fit the labels as well. Mine now looks like this:


Hide the letters

Now that we’ve got the words to appear where we want them to, we’re going to make sure that the user can’t see them unless he presses the correct button.

First and foremost we make sure that the words aren’t visible when someone presses “New game”. To do this; enter this code at the top of the 'new game' button sub:


For Each labelitm As Label In GroupBox2.Controls

       

        labelitm.Visible false

Next


So it looks like this:






Now when you start a new game; the label will be invisible.

This is the end of Part 3.



Part 4



In the last tutorial I showed you how to show the information that we’ve retrieved, such as letters and the amount of letters. In this tutorial I’m going to show you how to unhide a letter once the correct button is pressed in the alphabet groupbox.


Unhide the correct letter


First we need to create a new sub:


Between End sub and End class type:


Private sub labelcheck() 
End sub


This creates a new sub called “labelcheck”. Inside the new sub we’re going to use another “For Each” loop. But first we need to declare another public variable.


Under where we declared 'n' type:


Public a as String




It should look like this:






Now in the new sub that we created type:


For Each labelitm As Label In GroupBox2.Controls 
       If a = labelitm.Text Then 
             labelitm.Visible = True 
       Else 
       End If 
Next




Here we’re saying that “For each” labelitm in groupbox: If the variable ‘a’ = the text on one of the labels, then show that label. Otherwise do nothing (we’re going to put in what happens if you press the wrong button later).


Choosing a letter


Now we’re going to tell the machine what to do if one of the buttons is pressed. Got to the design tab and double click on the “a” button.


You will then get a new sub which looks like this:








There are two directions we can go from here. Either we create a new sub for each button. Or we have one sub for every button.


We’ll go with the second option to keep things organized.


First where it says Button1_Click; rename it to simply 'ButtonClick' since this subs is for all of the buttons.
Like this:








Then where it says “Handles Button1.Click” we need to add the rest of the buttons like this:


Handles Button1.Click, Button2.Click, Button3.Click, Button4.Click, Button5.Click, Button6.Click, Button7.Click, Button8.Click, Button9.Click, Button10.Click, Button11.Click, Button12.Click, Button13.Click, Button14.Click, Button15.Click, Button16.Click, Button17.Click, Button18.Click, Button19.Click, Button20.Click, Button21.Click, Button22.Click, Button23.Click, Button24.Click, Button25.Click, Button26.Click




It should now look like this (I couldn’t fit them all in the pic, but it goes on till button26):








Next we tell the machine what to do depending on which button is clicked with this code:


Select Case DirectCast(sender, Button).Name
Case "Button1"
Button1.Enabled = False
a = "a"
labelcheck()
Case "Button2"
Button2.Enabled = False
a = "b"
labelcheck()
Case "Button3"
Button3.Enabled = False
a = "c"
labelcheck()
Case "Button4"
Button4.Enabled = False
a = "d"
labelcheck()
Case "Button5"
Button5.Enabled = False
a = "e"
labelcheck()
Case "Button6"
Button6.Enabled = False
a = "f"
labelcheck()
Case "Button7"
Button7.Enabled = False
a = "g"
labelcheck()
Case "Button8"
Button8.Enabled = False
a = "h"
labelcheck()
Case"Button9"
Button9.Enabled = False
a = "i"
labelcheck()
Case "Button10"
Button10.Enabled = False
a = "j"
labelcheck()
Case "Button11"
Button11.Enabled = False
a = "k"
labelcheck()
Case "Button12"
Button12.Enabled = False
a = "l"
labelcheck()
Case "Button13"
Button13.Enabled = False
a = "m"
labelcheck()
Case "Button14"
Button14.Enabled = False
a = "n"
labelcheck()
Case "Button15"
Button15.Enabled = False
a = "o"
labelcheck()
Case "Button16"
Button16.Enabled = False
a = "p"
labelcheck()
Case "Button17"
Button17.Enabled = False
a = "q"
labelcheck()
Case "Button18"
Button18.Enabled = False
a = "r"
labelcheck()
Case "Button19"
Button19.Enabled = False
a = "s"
labelcheck()
Case "Button20"
Button20.Enabled = False
a = "t"
labelcheck()
Case "Button21"
Button21.Enabled = False
a = "u"
labelcheck()
Case "Button22"
Button22.Enabled = False
a = "v"
labelcheck()
Case "Button23"
Button23.Enabled = False
a = "w"
labelcheck()
Case "Button24"
Button24.Enabled = False
a = "x"
labelcheck()
Case "Button25"
Button25.Enabled = False
a = "y"
labelcheck()
Case "Button26"
Button26.Enabled = False
a = "z"
labelcheck() 
End Select


This looks like a lot, but that’s because we need to tell the machine what to do depending on which of the 26 buttons is pressed. But I’ll try to explain it as best as I can.


Select Case DirectCast(sender, Button).Name = Tell the machine to select a case depending on the name of the case and process the commands under the selected case as an event.
Case "Button1" = Create a case and name it “button1“
Button1.Enabled = False = Disable the button so that it can’t be pressed again.
a = "a" = Declare the Public variable ‘a’ as the letter ‘a’
labelcheck() = Call the labelcheck sub


Repeat 25 times for each button and then-


End Select = End the case selection function.


You can try this out by starting a new game and pressing on the buttons you think are in the hidden word.


A small mistake


As you can see there’s no function that tells the game what to do once you’ve revealed the entire word.
Before I show you how to do this I need to correct a small mistake. Follow the instructions on the following image:






And make the “For Each” loop that you just moved look like this:


For Each labelitm As Label In GroupBox2.Controls 
       If labelitm.Text = "" Then 
       Else 
          labelitm.Visible = False 
       End If 
Next


The code should look like this now.






We do this because we need to tell the machine not to hide the labels that don’t have any text in them.


Why we need to do this will be revealed in the next instruction.


Check if you won the game


Remember the sub we created? The one called labelcheck? In there we had an “if statement”. Now under that “if” statement we are going to make another if statement. This one checks if we have completed the word and it goes as follows:


If Label1.Visible AndAlso Label2.Visible AndAlso Label3.Visible AndAlso Label4.Visible AndAlso Label5.Visible AndAlso Label6.Visible AndAlso Label7.Visible AndAlso Label8.Visible = True Then


MessageBox.Show("You won!")


End If


This checks if every label is visible (I.E if you’ve won the game) and if they are; it displays a message telling the user that they won.


It might look a little weird on this blog so I’ll take a screenshot:






I’m going to end this part here because this is going to be way longer than the other parts if I’m going to include the rest of the game in here.


So in part 5 I’m fairly certain that I will be able to show you the rest.


To save your project go to ‘file’ then select ‘save all’.


Part 5


This will be the final part of this tutorial. In the last part we created a way for the player to know if we had won the game. The problem is that the game doesn’t reset once you’ve won. To fix this we are going to press the ‘new game’ button programmatically.


Under the messagebox that displays the “You Won” message type:


Button28.PerformClick()

Simple enough! All this does is send a ‘button click’ event to the ‘new game’ button that resets the game once the player has won.


Here’s a screenshot for reference






As you may have noticed the buttons won’t go back to their original state once the 'new game' button is pressed. To fix this; place this “For Each” statement at the top of the ‘new game’ button sub.



For Each btn As Button In GroupBox1.Controlsbtn.Enabled = TrueNext




Next; we will load our pictures into the game.


You can use my pictures if you want here’s a download link, although I warn you: They are pretty low quality and crudely drawn.


Hangman.zip


You can also create your own if you want. Remember though that the amount of pictures that you use determines how many chances the player has. I have eight pictures, which means that the player has seven chances (since the first one will be shown from the beginning)


Now to insert the pictures into the game; go to the design tab and click on the little arrow that shows up when you select the picturebox.






Click on ‘choose image’ and this window should show up.






In the new window; click on ‘import’, find the hangman pictures (make sure that they are named in either numerical or alphabetical order).


Select all of them and click on ‘open’.


Now you should see this:






Select ‘(none)’ and press OK. We’ll add the pictures programmatically instead.


In the top-right corner of Visual Studio (in the solution explorer) you should see your pictures in a folder called “resources” here’s a screenshot for reference:






Before we add the pictures to the application we are going to declare two variables which we will use later. The first one is an integer, so you can place it next to the ‘n’ integer.


 Public c as integer = 0




And next we need to declare a string.


Public pic as string




Here’s a screenshot:






To insert the first picture we need to create a new sub. We’ll do this by double clicking on the top border of the form1 in the design tab. This will create a new sub which looks like this:






This sub runs when the form starts up.


In the sub we’ll tell the application to load a certain picture into the picture box and declare pic as “hangman1” (or whatever your picture is called).

PictureBox1.Image = My.Resources.hangman1pic = "hangman1"




We declare this variable as such since we need to know which picture is in the picturebox.
Next we’ll go to the labelcheck sub and insert an IF statement.


We need to place the IF statement outside of the loop, so place it under ‘Next’.
Here’s the IF statement:

If c = 0 ThenIf pic = "hangman1" ThenPictureBox1.Image = My.Resources.hangman2pic = "hangman2"ElseIf pic = "hangman2" ThenPictureBox1.Image = My.Resources.hangman3pic = "hangman3"ElseIf pic = "hangman3" ThenPictureBox1.Image = My.Resources.hangman4pic = "hangman4"ElseIf pic = "hangman4" ThenPictureBox1.Image = My.Resources.hangman5pic = "hangman5"ElseIf pic = "hangman5" ThenPictureBox1.Image = My.Resources.hangman6pic = "hangman6"ElseIf pic = "hangman6" ThenPictureBox1.Image = My.Resources.hangman7pic = "hangman7"ElseIf pic = "hangman7" ThenPictureBox1.Image = My.Resources.hangman8pic = "hangman8"MessageBox.Show("You lost!)Button28.PerformClick()End IfEnd If




This is actually an IF statement within an IF statement. The code within the first IF statement is executed if c = 0 (I’ll explain later), and the code within the second of statement is executed depending on which picture is in the picturebox.


So if the picture within the picturebox is the first picture I.E “hangman1” then this code changes the picture to “hangman2” and declares pic as “hangman2”. This goes on until “hangman8” which is the last picture. Since it’s the last we’ll display a messagebox to the user telling them that they lost. We’ll also reset the game by programmatically pressing the ‘new game’ button again.
We’ll need to reset the picture as well, so at the top of the ‘new game’ button sub add this line of code



PictureBox1.Image = My.Resources.hangman1pic = "hangman1"




Next; in the labelcheck sub we need to increment c by 1 each time a label is shown. So in the “For Each” loop (under labelitm.Visible = True) type:


c = c 1


Now if C is more than 1 (I.E if the correct letter has been pressed) then the picture won’t be changed.


Here’s a screenshot of the labelcheck sub:






But we’ll also need to reset C every time a button is pressed so that it doesn’t just increment into infinity.


Go to the ButtonClick sub and add: c = 0 to the code so that each case now looks like this:

Case "Button1"Button1.Enabled = Falsea = "a"c = 0labelcheck()




Here’s another screenshot for reference:






I couldn’t fit them all into the screenshot but they should all have the c = 0 statement.


And now, for all intents and purposes, your application is done. Before we build the application you might want to take it for a spin by pressing f5 (or the little green play button). If the picture is too big for the picturebox; you can click on that little arrow button and play around with the settings until it fits, or just change the size of the picture box.


You might also want to remove any unnecessary messageboxes (if you have any).


Also if you want the .exe file: click on ‘debug’ at the top and then select ‘Build’ then go to: C:\Users\Mike\Documents\Visual Studio 2010\Projects\Hangman tutorial\Hangman tutorial\bin\Release and the .exe file will be there. Anyone who uses this application will need .Net 4.0 which you can download from microsofts website.


Leave a comment if there’s anything missing, unclear or could have been done better and I’ll change it.