...

View Full Version : Help with hangman code



Sherby
02-25-2013, 03:55 AM
You’ve been tasked to create an educational game for a fifthgrade

reading class. The game must test students’ spelling

skills using a variation of the classic game Hangman. If you’re

unfamiliar with the rules and general game play, please

consult the online reference at http://en.wikipedia.org/

wiki/Hangman_(game) for more information.

Database

The application will use the HangManDB.MDF file. The

HangManDB database contains the tables shown in

Figure 59.

The UnitID column in the Words table is a foreign key to the

ID column in the Units table. The Word column contains the

actual word to guess, while the Description column contains

the description of words for that unit.

201

User Interface

The user interface will consist of a single Windows form. The

user interface will resemble Figure 60.

202 Final Graded Project

FIGURE 59—HangManDB Database Tables

FIGURE 60—Hangman

User Interface

When the application first loads, the textbox for the letter

guess should be disabled. If the New option is chosen in the

menu, then a new word and the unit description should be

loaded from the database. If the Quit option is chosen in the

menu, then the application should quit.

After each guess, one of two things should happen. If it was

a correct guess, then all occurrences of that letter should

appear in the labels at the bottom. If it’s an incorrect guess,

then the next stage of the hangman should appear in the

picture box. In either case, the textbox should highlight the

letter, so that the user can make another guess. The textbox

should not be cleared, or the user may attempt to guess the

same letter (Figure 61).

Final Graded Project 203

FIGURE 61—The incorrect

guessed letters should

appear in the picture box

and remain as other incorrect

guesses are added.

The game ends when either all letters of the

word are guessed correctly or the hangman

picture is completed. When the game is won,

a message box should display like this one

(Figure 62):

When the game is lost, the message box

should display words similar to Figure 63.

In either case, clicking the Yes button

should have the same effect as clicking the

New option in the menu and clicking the No

button should exit out of the application.

This will be the last graded project based on this scenario.

You’ll be graded on the end-user functionality, so variable

names and other aspects can differ, but the application must

work as intended.

Application Files

This application will consist of the following files in the solution

explorer:

1. GameForm.vb. The only form in the application.

2. HangmanDB.MDF. The database that contains the questions

and unit descriptions. See Provided Files section

below for more information.

3. Images folder. Hangman-0.png, Hangman-1.png,

Hangman-2.png, Hangman-3.png, Hangman-4.png,

Hangman-5.png, and Hangman-6.png. See “Provided

Files” section below for more information.

204 Final Graded Project

FIGURE 62—You won! Do you want to play

again?

FIGURE 63—You lost. Do

you want to play again?

4. QuestionDataSet.xsd. The DataSet for the HangmanDB

database. Should contain both tables Words and Units.

Provided Files

You’ll be provided the following files:

■ The HangmanDB.MDF database

■ The images folder that contains the image files

Hangman-0.png, Hangman-1.png, Hangman-2.png,

Hangman-3.png, Hangman-4.png, Hangman-5.png,

and Hangman-6.png

You should add these files to your project as described in

step 3 in the Instructions section.

INSTRUCTIONS

1. In Visual Studio, create a new Windows Forms project

named HangmanApp.

2. Rename the Form1.vb file to GameForm.vb.

3. Add the provide files to your project. Use the Add >

Existing Item… option in the Solution Explorer. Make

sure in the Properties panel to set the Copy To Output

property to Copy Always.

4. Create the DataSet named QuestionDataSet.xsd using

the HangmanDB.MDF file. Review Assignment 15.

5. Create the user interface for GameForm.vb. See the

User Interface section above for the layout. The form

will consist of the following controls:

a. One MenuStrip control that contains the Game menu

with the options New and Quit.

b. One Label control with the text Guess a letter.

c. One Label control with the text Choose New Game.

This label will display the unit description during the

game.

d. One TextBox control for the user type in letter

choices.

Final Graded Project 205

e. A PictureBox control that will display the hangman

images. You’ll set the ImageLocation property to load

the hangman images.

f. A Panel control that will contain the displayed letter

labels.

g. Eleven Label controls, one for each letter of the word.

These labels should be in the panel. You should set

the initial value for the Text property to the underscore

character (_) to act as a placeholder character.

You can chose to set the control properties to whatever

you like, but below are some helpful suggestions. If you

don’t name the controls the same names, you’ll need to

modify some provided code in the next steps.

For a further description on how to add and layout

controls, review Assignment 11 and Assignment 13.

6. In the code of GameForm.vb, you should define the

following variables:

a. dsQuestions. A QuestionDataSet object

206 Final Graded Project

GameForm Size: 500, 500

Label for unit description (Name): lblUnitDescription

Font.Size: 14

TextBox for letter guesses (Name): txtGuess

Font.Size: 22

MaxLength: 1

PictureBox for hangman images (Name): pboxHangman

Size: 256, 256

Panel for letter labels (Name): panelWord

Dock: Bottom

Eleven Label controls for letters Set the (Name) property for

each to lblLetter0 to

lblLetter11. The last character(

s) will match the character

index in the word.

Font.Size: 22

Text: _

b. numWord. The index of which word is being guessed.

This matches the row in the Words table that’s being

retrieved. Each game will increment this number by

one.

c. word. The actual word being guessed.

d. numWrongGuesses. Number of wrong guesses in a

game.

e. numRightGuesses. Number of right guesses in a

game.

f. gameStarted. Indicates whether the game has started

or not.

6. In the code of GameForm.vb, you should have the following

event procedures:

a. Form Load event handler—Disable the txtGuess

textbox, set the numWord variable and call the

LoadData method (provided below).

b. Quit button Click event handler—Exit the application

c. In the New button Click event handler, perform the

following tasks:

I. Initialize all variables, especially numRightGuesses,

numWrongGuesses, gameStarted, and

numWord. Make sure to increment numWord to

the next index.

II. Initialize controls. Clear the text of all labels,

enable and set the focus to the txtGuess textbox.

III. Set controls using the DataSet. If you followed

the same names, then you can use this code:

‘Gets word column row

word = CStr(dsQuestions.Words(numWord)(1))

‘Gets unit description

lblUnitDescription.Text = _

CStr(dsQuestions.Words(numWord).UnitsRow(1))

IV. Set the label control for each character in the

word. Set the Text property to the underscore

character (_).

Final Graded Project 207

d. In the txtGuess textbox TextChanged event, perform

the following tasks:

I. Check if the game is started using the

gameStarted variable.

II. Check to see if the word (word) contains the

guess (txtGuess).

III. If it does, then call the SetRightLetterLabels

method (provided below) and increment the

numRightGuesses variable.

IV. If it doesn’t, set the image in the pboxHangman

and increment the numWrongGuesses variable.

Your code should resemble the following:

pboxHangman.ImageLocation = “images\Hangman-” &

numWrongGuesses & “.png”

numWrongGuesses += 1

V. Check to see if the game has been won or lost

yet. Use the CheckProgress method. See step 7A

for how the CheckProgress method is defined.

VI. Select all of the text in the txtGuess textbox.

7. In the code of GameForm.vb, you might find it helpful to

define the following methods:

a. A method named CheckProgress that calculates the

total number of tries (numRightGuesses +

numWrongGuesses), displays the correct message box

for winning or losing, and starts the next game or

exits the application depending on the message box

button.

b. A method named WonGame that checks each letter in

the word is matched by its label and returns True if

this is the case.

c. A method named LostGame that checks to see if the

number of wrong guesses is greater than six and

returns True if this is the case.

d. A method named ResetAllLabels that sets each character

label to blank text.

208 Final Graded Project

8. In the code of the GameForm.vb, you might want to add

these helper methods:

Private Sub LoadData()

Dim taUnits As New

QuestionDataSetTableAdapters.UnitsTableAdapter

Dim taWords As New

QuestionDataSetTableAdapters.WordsTableAdapter

taUnits.Fill(dsQuestions.Units)

taWords.Fill(dsQuestions.Words)

End Sub

Private Function FindLabel(ByVal i As Integer) As

Control

‘Finds the right label in the Word panel

Dim label = panelWord.Controls.Find(“lblLetter” & i,

False)(0)

Return label

End Function

Private Sub SetRightLetterLabels(ByVal word As String,

ByVal ch As Char)

For i As Integer = 0 To word.Length - 1

‘Check for each letter and set the appropriate

letter

If word.Chars(i) = ch Then

FindLabel(i).Text = ch

End If

Next

End Sub

9. Save and run the application. Verify that all controls and

menus work correctly. You’ll submit the compiled application

for this project according to the submission

guidelines on that follow


Here is my code. My problem is that when i enter the first letter in the text box and press enter, that letter still remains in the box and i am not able to enter the second letter and so on. Just need some tips on what i might be doing wrong. Thanks in advance.



Public Class GameForm

' Define variables
Dim dsQuestions As String 'Object variable
Dim numWord As Integer ' To hold index of word
Dim word As String ' Hold actual word
Dim numWrongGuesses As Integer ' Hold number of wrong guesses
Dim numRightGuesses As Integer ' Hold number of right guesses
Dim gameStarted As Boolean = False ' Indicate if game has started or not
Private Sub GameForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
' Disable txtGuess textbox.
txtGuess.Enabled = False

' Set numWord variable.
Dim numWord As Integer = 0

' Call the Load Data method.
LoadData()

End Sub

Private Sub QuitToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles mnuQuit.Click
' Close the form
Me.Close()
End Sub

Private Sub NewToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles NewToolStripMenuItem.Click
Dim dsQuestions As New QuestionDataSet
Dim numWord As Integer = 1
numWord += 1
Dim word As String
Dim numWrongGuesses As Integer = 10
Dim numRightGuesses As Integer = 5
Dim gameStarted As Boolean = True

' Initialize controls
lblUnitDescription.Text = "Choose a game"
txtGuess.Text = lblGuessALetter.Text


' Clear text of all labels.
lblUnitDescription.Text = String.Empty
txtGuess.Clear()
lblLetter0.Text = String.Empty
lblletter1.Text = String.Empty
lblLetter2.Text = String.Empty
lblLetter3.Text = String.Empty
lblLetter4.Text = String.Empty
lblLetter5.Text = String.Empty
lblLetter6.Text = String.Empty
lblLetter7.Text = String.Empty
lblLetter8.Text = String.Empty
lblLetter9.Text = String.Empty
lblLetter10.Text = String.Empty
lblLetter11.Text = String.Empty
' Enable txtGuess.
txtGuess.Enabled = True
' Set the focus to txtGuess.
txtGuess.Focus()

' Gets word column row

Try
word = CStr(dsQuestions.Words(numWord)(1))
' Gets unit description
lblUnitDescription.Text = CStr(dsQuestions.Words(numWord).UnitsRow(1))

Catch

' Set label control for character.
lblLetter0.Text = "_"
lblletter1.Text = "_"
lblLetter2.Text = "_"
lblLetter3.Text = "_"
lblLetter4.Text = "_"
lblLetter5.Text = "_"
lblLetter6.Text = "_"
lblLetter7.Text = "_"
lblLetter8.Text = "_"
lblLetter9.Text = "_"
lblLetter10.Text = "_"
lblLetter11.Text = "_"


Dim ch As Char = CChar(CStr(0))
Dim ch1 As Char = "_"
Dim ch2 As Char = "_"
Dim ch3 As Char = "_"
Dim ch4 As Char = "_"
Dim ch5 As Char = "_"
Dim ch6 As Char = "_"
Dim ch7 As Char = "_"
Dim ch8 As Char = "_"
Dim ch9 As Char = "_"
Dim ch10 As Char = "_"
Dim ch11 As Char = "_"
End Try
End Sub

Private Sub txtGuess_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtGuess.TextChanged
Dim gameStarted As Boolean = True
Dim word As String = ""
Dim numRightGuesses As Integer = 5
Dim ch As Char

If gameStarted = True Then
If word.Contains(txtGuess.Text) Then
SetRightLetterLabels(word, ch)
numRightGuesses += 1
End If

ElseIf word.Contains(txtGuess.Text) = False Then
pboxHangman.ImageLocation = "Images \ Hangman- & numWrongGuesses & .png"
numWrongGuesses += 1
End If
CheckProgress()





End Sub
Private Sub CheckProgress()
' Calculates the total number of tries.
Dim numTries As Integer
numTries = numRightGuesses + numWrongGuesses
' Displays messages
If numRightGuesses = 5 Then
MessageBox.Show("You won in 5 tries!" & ControlChars.CrLf &
"Do you want to play another game?", "You won!",
MessageBoxButtons.YesNo, MessageBoxIcon.Information)
ElseIf numWrongGuesses = 10 Then
MessageBox.Show("You lost in 10 tries. The word was ''." & ControlChars.CrLf &
"Do you want to play another game?", "You lost",
MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation)
End If
End Sub
Private Sub WonGame()


End Sub
Private Sub LostGame()
Dim numWrongGuesses As Integer
If numWrongGuesses > 6 Then
numWrongGuesses = True
End If
End Sub
Private Sub ResetAllLabels()
lblLetter0.Text = "_"
lblletter1.Text = "_"
lblLetter2.Text = "_"
lblLetter3.Text = "_"
lblLetter4.Text = "_"
lblLetter5.Text = "_"
lblLetter6.Text = "_"
lblLetter7.Text = "_"
lblLetter8.Text = "_"
lblLetter9.Text = "_"
lblLetter10.Text = "_"
lblLetter11.Text = "_"

End Sub
Private Sub LoadData()
Dim dsQuestions As New QuestionDataSet
Dim taUnits As New QuestionDataSetTableAdapters.UnitsTableAdapter
Dim taWords As New QuestionDataSetTableAdapters.WordsTableAdapter
taUnits.Fill(dsQuestions.Units)
taWords.Fill(dsQuestions.Words)

End Sub
Private Function FindLabel(ByVal i As Integer) As Control
' Finds the right label in the word panel
Dim label = panelWord.Controls.Find("lblLetter" & i, False)(0)
Return label
End Function
Private Sub SetRightLetterLabels(ByVal word As String, ByVal ch As Char)
For i As Integer = 0 To word.Length - 1
' Check for each letter and set the appropriate letter
If word.Chars(i) = ch Then
FindLabel(i).Text = ch
End If
Next
End Sub


End Class

alykins
02-25-2013, 04:56 PM
tldr, and it's clearly an assignment... You are allowed to ask on help for specific problems though. Are you stuck with something? or is something not working?

Fou-Lu
02-25-2013, 05:46 PM
fixed it so you can see the separate sections. Instructions are far too long so I can see the tldr there :D
Don't do the basic programming languages, but looks like it'll be a pretty simple task overall for the only question at hand. Java world I'd use a document listener on it, not sure if VB has a similar option (I would presume so).

alykins
02-25-2013, 06:16 PM
Ok much easier to see now, and didn't see the question before... can you post what your text box has as properties from the designer?

Form.vb [Design] -- visual designer
Form.vb -- actual code
Form.Designer.vb <-- That one (it will be a child-tree of Form.vb)... You may have to click the button to 'see all files'

It will look something like attached (note: don't change thins in here unless you know what it is doing)

Sherby
02-25-2013, 11:30 PM
Me.txtGuess.Font = New System.Drawing.Font("Microsoft Sans Serif", 21.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.txtGuess.Location = New System.Drawing.Point(11, 105)
Me.txtGuess.MaxLength = 1
Me.txtGuess.Name = "txtGuess"
Me.txtGuess.Size = New System.Drawing.Size(89, 40)
Me.txtGuess.TabIndex = 2
'

alykins
02-26-2013, 03:13 PM
PM'ing you

alykins
02-26-2013, 05:54 PM
Ok, So I have the project and integrated it with my database... Now first problem I see is that you declare (global) objects at the top but then dim them within functions, and for your dataset it is even a conflicting datatype... I don't know why VB is letting you do this, I would have thought it would blow up errors at you, but alas it's not. So let's look at your dataset (as an example)...



Dim dsQuestions As String 'Object variable

....... and then elsewhere in code .....

Private Sub LoadData()
Dim dsQuestions As New QuestionDataSet
Dim taUnits As New QuestionDataSetTableAdapters.UnitsTableAdapter
Dim taWords As New QuestionDataSetTableAdapters.WordsTableAdapter
taUnits.Fill(dsQuestions.Units)
taWords.Fill(dsQuestions.Words)

End Sub


See? You reuse a global variable name, also it is called in a void, which would be fine if you were filling the global variable, but you are creating a dataset, which is then lost in the end Sub...
This would be better



Dim dsQuestions As New QuestionDataSet() 'Up top in global variables

.... and in that function ....

Dim taUnits As New QuestionDataSetTableAdapters.UnitsTableAdapter
Dim taWords As New QuestionDataSetTableAdapters.WordsTableAdapter
taUnits.Fill(dsQuestions.Units)
taWords.Fill(dsQuestions.Words)


Now you populate that global dataset. Work through changing that logic for all your variables. I started doing so, and then found a lot of logic flaws in your conditional statements (if's). So the next step, after the variables are set correctly is to start working through that logic. Let's see how far you get with that :)

Also, keep this in mind.... You are counting a tick (or wanting to) for each time the text changes in the textbox... it needs to be cleared out as well, because backspace is a change in the text, and it triggers that event.

Sherby
03-07-2013, 03:18 AM
Oh this one is really hard i am still stuck not understanding at all.

alykins
03-07-2013, 05:16 PM
What changes have you made so far? You can re-email me the solution

Sherby
03-19-2013, 09:08 PM
I have gotten majority of the project done. Still having 2 problems, for some of the words when i enter the letters in the textbox,even before i finish guessing the word the You Won message box pops up. Second problem I am not sure how to code the WonGame method.

Can someone please help, just to hint me on what i might be doing wrong. This project is due early next week.

Thanks i advance.

Sherby
06-06-2013, 10:21 PM
Got it!!!!!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum