Public Class HangmanGame
Private wordList As String() = {"PROGRAM", "VISUAL", "BASIC", "COMPUTER", "DEVELOPER", "APPLICATION"}
Private secretWord As String
Private guessedLetters As New List(Of Char)()
Private maxAttempts As Integer = 6
Private attemptsLeft As Integer
Public Sub New()
StartNewGame()
End Sub
Public Sub StartNewGame()
' Select a random word
Dim random As New Random()
secretWord = wordList(random.Next(wordList.Length))
' Reset game state
guessedLetters.Clear()
attemptsLeft = maxAttempts
End Sub
Public Function GuessLetter(letter As Char) As Boolean
letter = Char.ToUpper(letter)
' Check if letter was already guessed
If guessedLetters.Contains(letter) Then
Return True ' Already guessed, no penalty
End If
' Add to guessed letters
guessedLetters.Add(letter)
' Check if letter is in the word
If secretWord.Contains(letter) Then
Return True
Else
attemptsLeft -= 1
Return False
End If
End Function
Public Function GetDisplayWord() As String
Dim display As New StringBuilder()
For Each c As Char In secretWord
If guessedLetters.Contains(c) Then
display.Append(c & " ")
Else
display.Append("_ ")
End If
Next
Return display.ToString().Trim()
End Function
Public Function IsWordGuessed() As Boolean
For Each c As Char In secretWord
If Not guessedLetters.Contains(c) Then
Return False
End If
Next
Return True
End Function
Public Function IsGameOver() As Boolean
Return attemptsLeft <= 0 OrElse IsWordGuessed()
End Function
Public Function GetHangmanImageIndex() As Integer
Return maxAttempts - attemptsLeft
End Function
End Class
VB.NET Hangman Game Explanation
This VB.NET implementation demonstrates the core logic of the Hangman game:
- Game Initialization: The game starts by selecting a random word from a predefined list.
- Letter Guessing: Players guess letters which are checked against the secret word.
- Game State Tracking: The class tracks guessed letters and remaining attempts.
- Word Display: Generates the display version of the word with underscores for unguessed letters.
- Win/Loss Conditions: Checks if the word has been completely guessed or if attempts have run out.
This backend logic can be connected to a Windows Forms UI to create a complete application.