Noob having problems with Hangman loop

Hang man program goes into infinite loop or straight to game over

Page 1 of 1

6 Replies - 1315 Views - Last Post: 08 May 2009 - 08:16 AM Rate Topic: -----

#1 skaboywrx  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 08-May 09

Noob having problems with Hangman loop

Post icon  Posted 08 May 2009 - 06:16 AM

Hello all,

I am a student working on the venerable "Hangman" project. We were tasked to create a hangman game that would get a random word from one of three sources either by file, by array, or by database file. I have managed to get a random word to import from all three but I run into a problem once I start to play the game. The program seems to run into an infitinite loop as soon as you enter a letter or it automatically dispays character entered and gives a game over. Please take a look any help is massivly apreciated. P.S. If there is a better way to paste the code please let me know. I will also attach .txt document

Imports System.IO
Imports System.Data.OleDb
Imports System.Data


Public Class Form1
Dim byFileName As String 'the name of the text file that contains a list of words in a column
Dim wordArray(20) As String ' the array that holds the list of words for random selection
Dim myStreamReader As StreamReader
Public word2guess As String 'the word that is to be guessed
Dim randomNumber As Integer
Dim dashReplaced As Boolean 'indicates whether a dash was replaced
Dim gameOver As Boolean 'indicates wheter the game is over
Dim letter As String
Dim incorrectGuess As Integer




Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles byFileButton.Click

' Open a file dialog that allows the user to select a file from a hard drive resource
' Create the OpenFileDialog object
Try
Dim myOpenFileDialog As New OpenFileDialog()

' Set properties as appropriate.
myOpenFileDialog.CheckFileExists = True
myOpenFileDialog.DefaultExt = "*.txt"
myOpenFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"

myOpenFileDialog.InitialDirectory = "C:\"
myOpenFileDialog.Multiselect = False

' Use the OpenFileDialog and put the path and name of the
' selected file in the txtFileName text box.
If myOpenFileDialog.ShowDialog = DialogResult.OK Then
byFileName = myOpenFileDialog.FileName
'MessageBox.Show(byFileName) 'used only to show that we are capturing the path and name of the file that contains words
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

' Upon successful selection of the file that contains a list of words; now open the file for reading the words and
' placing all the words in an array

Dim myWordFromFile As String
Dim rowCount As Integer = 0

' Ensure that the creation of the new StreamReader is wrapped in a 
' Try-Catch block, since an invalid filename could have been used.
Try
' Create a StreamReader using a Shared (static) File class.
myStreamReader = File.OpenText(byFileName)

' Begin by reading a single line
myWordFromFile = myStreamReader.ReadLine()
' Continue reading while there are still lines to be read
While Not myWordFromFile Is Nothing
wordArray(rowCount) = myWordFromFile
'MessageBox.Show(wordArray(rowCount)) 'this line is used only to show if the word is being placed into our array
rowCount += 1
' Read the next line.
myWordFromFile = myStreamReader.ReadLine()
End While
Catch ex As Exception
' Show the error to the user.
MsgBox("File could not be opened or read." + vbCrLf + _
"Please verify that the filename is correct, " + _
"and that you have read permissions for the desired " + _
"directory." + vbCrLf + vbCrLf + "Exception: " + ex.Message)
Finally
' Close the object if it has been created.
If Not myStreamReader Is Nothing Then
myStreamReader.Close()
End If
End Try

Randomize()
randomNumber = Int(Rnd() * 20) 'select a random number for use in selecting random word from array


word2guess = "" 'resets word2guess variable
word2guess = wordArray(randomNumber).ToUpper 'gets random word and coverts to uppercase

' GuessedLetters.Text = word2guess 'test to see if random word
' GuessedLetters.Visible = True 'is selected

'display dashes

If word2guess.Length = 4 Then
GuessedLetters.Text = "----"
ElseIf word2guess.Length = 5 Then
GuessedLetters.Text = "-----"
ElseIf word2guess.Length = 6 Then
GuessedLetters.Text = "------"
ElseIf word2guess.Length = 7 Then
GuessedLetters.Text = "-------"
ElseIf word2guess.Length = 8 Then
GuessedLetters.Text = "--------"
ElseIf word2guess.Length = 9 Then
GuessedLetters.Text = "---------"
ElseIf word2guess.Length = 10 Then
GuessedLetters.Text = "----------"
End If
GuessedLetters.Visible = True


End Sub
Private Sub byArrayButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles byArrayButton.Click
Dim wordArray() As String = {"Computer", "Apple", "Orange", "Plastic", "Table", "Desk", "Paper", "mouse", "turbo", "Skyline", "Victrory", "Dummy", "Fish", "Trombone", "Hula", "Canada", "Xylophone", "Dolphin", "Wolverine", "Gibbit"}

Randomize()
randomNumber = Int(Rnd() * 20) 'set reandom number

word2guess = "" 'resets word2guess variable
word2guess = wordArray(randomNumber).ToUpper 'gets random word and coverts to uppercase

' GuessedLetters.Text = word2guess 'test to see if random word
' GuessedLetters.Visible = True 'is selected

'displays dashes

If word2guess.Length = 4 Then
GuessedLetters.Text = "----"
ElseIf word2guess.Length = 5 Then
GuessedLetters.Text = "-----"
ElseIf word2guess.Length = 6 Then
GuessedLetters.Text = "------"
ElseIf word2guess.Length = 7 Then
GuessedLetters.Text = "-------"
ElseIf word2guess.Length = 8 Then
GuessedLetters.Text = "--------"
ElseIf word2guess.Length = 9 Then
GuessedLetters.Text = "---------"
ElseIf word2guess.Length = 10 Then
GuessedLetters.Text = "----------"
End If
GuessedLetters.Visible = True





End Sub



Private Sub byDbButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles byDbButton.Click
Static word2guess As String

Try
' I had to set the file location to my desktop as I am unsure where you would like the default file location to be
Dim dbConn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Documents and Settings\josh\Desktop\words.mdb")
Dim strSelect As String = "SELECT * from WordsTable"
Dim daWords As New OleDbDataAdapter(strSelect, dbConn)
Dim dsWords As New DataSet("Words")
Dim rowCount As Integer = 0

daWords.Fill(dsWords)

Dim row As DataRow
For Each row In dsWords.Tables(0).Rows
wordArray(rowCount) = row(0)
rowCount += 1
Next

Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

Randomize()
randomNumber = Int(Rnd() * 20) 'set reandom number

word2guess = "" 'resets word2guess variable
word2guess = wordArray(randomNumber).ToUpper 'gets random word and coverts to uppercase

' GuessedLetters.Text = word2guess 'test to see if random word
' GuessedLetters.Visible = True 'is selected

'show dashes

If word2guess.Length = 4 Then
GuessedLetters.Text = "----"
ElseIf word2guess.Length = 5 Then
GuessedLetters.Text = "-----"
ElseIf word2guess.Length = 6 Then
GuessedLetters.Text = "------"
ElseIf word2guess.Length = 7 Then
GuessedLetters.Text = "-------"
ElseIf word2guess.Length = 8 Then
GuessedLetters.Text = "--------"
ElseIf word2guess.Length = 9 Then
GuessedLetters.Text = "---------"
ElseIf word2guess.Length = 10 Then
GuessedLetters.Text = "----------"
End If
GuessedLetters.Visible = True

End Sub

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
If IsNumeric(TextBox1.Text) = True Then
Beep()
MessageBox.Show("Only letters are allowed")
End If



End Sub









Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click

Dim indexNum As Integer 'controls the loop thatsearches the word

' GuessedLetters.Text = word2guess 'test to see whats displayed
'reset hangman
Head.Visible = False
Body.Visible = False
LeftArm.Visible = False
LeftLeg.Visible = False
RightArm.Visible = False
RightLeg.Visible = False

IncorrectLettersLabel.Text = ""
incorrectGuess = 0
'allow player to guess a letter
'the game is over when the words guessed or 6 wrong guesses are made whichever comes first

Do While Not gameOver
letter = TextBox1.Text 'gets guessed letter
letter = letter.ToUpper 'converts to upper case
'search word for letter
For indexNum = 0 To word2guess.Length - 1
If word2guess.Substring(indexNum, 1) = letter Then
Mid(GuessedLetters.Text, indexNum + 1) = letter
'indicate a replacement was made
dashReplaced = True
End If
Next indexNum
'determine whether a replacement was made
If dashReplaced Then
'if the word doesn't contain any dashes then the user won so game over
If GuessedLetters.Text.IndexOf("-") = -1 Then
gameOver = True
MessageBox.Show("Congratulasions!", "Hangman Game", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else 'reset the dashReplaced variable
dashReplaced = False
End If
Else 'processed when no dash was replaced
'display incorrect letter
IncorrectLettersLabel.Text = IncorrectLettersLabel.Text & " " & letter
'update the counter variable, diplay the result
incorrectGuess = incorrectGuess + 1
If incorrectGuess = 1 Then
Head.Visible = True
ElseIf incorrectGuess = 2 Then
Head.Visible = True
Body.Visible = True
ElseIf incorrectGuess = 3 Then
Head.Visible = True
Body.Visible = True
LeftArm.Visible = True
ElseIf incorrectGuess = 4 Then
Head.Visible = True
Body.Visible = True
LeftArm.Visible = True
RightArm.Visible = True
ElseIf incorrectGuess = 5 Then
Head.Visible = True
Body.Visible = True
LeftArm.Visible = True
RightArm.Visible = True
LeftLeg.Visible = True
ElseIf incorrectGuess = 6 Then
Head.Visible = True
Body.Visible = True
LeftArm.Visible = True
RightArm.Visible = True
LeftLeg.Visible = True
RightLeg.Visible = True
End If
If incorrectGuess = 6 Then
'game is over
gameOver = True
GuessedLetters.Text = "Game Over"
MessageBox.Show("Sorry, the word is " & word2guess, "Hangman Game", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End If

Loop


End Sub
End Class 

Attached File(s)



Is This A Good Question/Topic? 0
  • +

Replies To: Noob having problems with Hangman loop

#2 aceofspades686  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 6
  • View blog
  • Posts: 334
  • Joined: 08-October 07

Re: Noob having problems with Hangman loop

Posted 08 May 2009 - 06:39 AM

The reason you're getting stuck in the loop is that it doesn't currently wait for input. It just loops through and gets the same value from the textbox each time. Problem is, even if you were to reset the textbox, then it would just attempt to find an empty character within the string and do the same thing.

Ask yourself this, do you really need a loop in the first place? While, if you were doing something like this in, say C++, then using a loop to wait for input would make sense, but in this example you're only going to need to run the checks against the guess each time the value is change (or a button is pressed).
Was This Post Helpful? 0
  • +
  • -

#3 skaboywrx  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 08-May 09

Re: Noob having problems with Hangman loop

Posted 08 May 2009 - 06:51 AM

View Postaceofspades686, on 8 May, 2009 - 05:39 AM, said:

The reason you're getting stuck in the loop is that it doesn't currently wait for input. It just loops through and gets the same value from the textbox each time. Problem is, even if you were to reset the textbox, then it would just attempt to find an empty character within the string and do the same thing.

Ask yourself this, do you really need a loop in the first place? While, if you were doing something like this in, say C++, then using a loop to wait for input would make sense, but in this example you're only going to need to run the checks against the guess each time the value is change (or a button is pressed).


It's funny you say that. Originally I wasn't using a loop but when my Prof. looked at my code he asked where my loop was as if it couldn't be done without one. I am still at a loss where to begin. I am 28+ hours into just coding the game, I thought geting inputs and setting up the random word from an array would be the hard part. Is there any way to salvage this loop as a crash ate my previous code?
Was This Post Helpful? 0
  • +
  • -

#4 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 8364
  • View blog
  • Posts: 31,074
  • Joined: 12-June 08

Re: Noob having problems with Hangman loop

Posted 08 May 2009 - 06:53 AM

Maybe a replace the loop (keep the innards) with... an event of some kind? ;)
Was This Post Helpful? 0
  • +
  • -

#5 aceofspades686  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 6
  • View blog
  • Posts: 334
  • Joined: 08-October 07

Re: Noob having problems with Hangman loop

Posted 08 May 2009 - 07:12 AM

For indexNum = 0 To word2guess.Length - 1
If word2guess.Substring(indexNum, 1) = letter Then
Mid(GuessedLetters.Text, indexNum + 1) = letter
'indicate a replacement was made
dashReplaced = True
End If
Next indexNum



I have a feeling this was the loop he was looking for, not the one you're getting stuck in.
Was This Post Helpful? 0
  • +
  • -

#6 skaboywrx  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 08-May 09

Re: Noob having problems with Hangman loop

Posted 08 May 2009 - 07:49 AM

View Postaceofspades686, on 8 May, 2009 - 06:12 AM, said:

For indexNum = 0 To word2guess.Length - 1
If word2guess.Substring(indexNum, 1) = letter Then
Mid(GuessedLetters.Text, indexNum + 1) = letter
'indicate a replacement was made
dashReplaced = True
End If
Next indexNum



I have a feeling this was the loop he was looking for, not the one you're getting stuck in.


So that loop is okay? If so then what is the best way to go about fixing the rest of the loop?
Was This Post Helpful? 0
  • +
  • -

#7 aceofspades686  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 6
  • View blog
  • Posts: 334
  • Joined: 08-October 07

Re: Noob having problems with Hangman loop

Posted 08 May 2009 - 08:16 AM

That loop is fine (although I wouldn't use mid personally, but one step at a time ;)).

The thing is that the other loop is not needed at all. As it stands all you're doing is repeating the user's choice of letters until it throws "game over". You could just take the loop out, but then you're going to be resetting the hangman each time they make a guess. To fix this, you'll need to separate the reset action and the guess action.

In psuedocode (because I don't have a compiler handy and I'm not going to throw this long of a block of code out without testing it first).

Guess Button Pressed
...If the word contains the guessed letter
......Swap out the letter guessed for the right blank

...Else If the word does not contain the guessed letter
......Add one to incorrect guesses
......Draw another part of the hangman

......If the hangman is completed
.........Game Over


Reset Button Pressed
...Reset Hangman and get a new word

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1