r/visualbasic • u/DoffyPikaTrebolCora • Jan 22 '16
WordGuess
How would I modify this code to keep track of the letters guessed in an array with meaningful indexes. Also how do include in the modification code a message box that pops up if the user emters the same guess twice? Don't give me the code. Tell me how to do it. Can you also give me a few hints here and there? I'm only a beginner. Here is my code:
Public Class Form1 Private Sub btnPlayGame_Click(sender As Object, e As EventArgs) Handles btnPlayGame.Click Const SECRET_WORD As String = "VELOCITY" Const FLAG As Char = "!" Const GUESS_PROMPT As String = "Enter a letter or " & FLAG & " to guess word:" Dim numGuesses As Integer = 0 Dim letterGuess As Char Dim wordGuess As String Dim tempWord As String Dim endGame As Boolean
Dim wordGuessedSoFar As String = ""
Dim length As Integer = SECRET_WORD.Length
wordGuessedSoFar = wordGuessedSoFar.PadLeft(length, "-")
Me.lblSecretWord.Text = wordGuessedSoFar
Dim tempLetterGuess = InputBox(GUESS_PROMPT, Me.Text)
If tempLetterGuess = Nothing Then
endGame = True
Else
letterGuess = tempLetterGuess
End If
Do While letterGuess <> FLAG And wordGuessedSoFar <> SECRET_WORD _
And Not endGame
numGuesses += 1
For letterPos As Integer = 0 To SECRET_WORD.Length - 1
If SECRET_WORD(letterPos) = Char.ToUpper(letterGuess) Then
tempWord = wordGuessedSoFar.Remove(letterPos, 1)
wordGuessedSoFar = tempWord.Insert(letterPos, Char.ToUpper(letterGuess))
Me.lblSecretWord.Text = wordGuessedSoFar
End If
Next letterPos
If wordGuessedSoFar <> SECRET_WORD Then
tempLetterGuess = InputBox(GUESS_PROMPT, Me.Text)
If tempLetterGuess = Nothing Then
endGame = True
Else
letterGuess = tempLetterGuess
End If
End If
Loop
If wordGuessedSoFar = SECRET_WORD Then
MessageBox.Show("You guessed it in " & numGuesses & " guesses!")
ElseIf letterGuess = FLAG Then
wordGuess = InputBox("Enter a word: ", Me.Text)
If wordGuess.ToUpper = SECRET_WORD Then
MessageBox.Show("You guessed it in " & numGuesses & " guesses!")
Me.lblSecretWord.Text = SECRET_WORD
Else
MessageBox.Show("Sorry you lose.")
End If
Else
MessageBox.Show("Game over.")
End If
End SubEnd Class
1
u/TheFotty Jan 23 '16
Use a list of char
When the user inputs a character to guess, first see if it exists in the list of guessed characters. List objects have a .contains() method you can pass the char to and it will return true/false if the char is already in the list. If it is, they already guessed it and should be prompted again. If it is not, you can add it to the list and then proceed to see if it is found in the secret word.