Я думаю, что это работает, хотя я признаю, что могут быть некоторые крайние условия, которые я не тестировал (прошло около 30 лет с тех пор, как я играл в игру палача ...)
Я получилизбавиться от переменных области модуля и немного реструктурировать его, чтобы разделить различные функции / действия.
Основная процедура - Hangman
, которая:
ResetGame
, котораяочищает рабочий лист и делает формы невидимыми) - получает ответ из функции inputbox
- Вызывает процедуру
PlayGame
с параметром Answer
.
The *Процедура 1019 * обрабатывает цикл над догадками игрока (с помощью функции GetNextGuess
) и завершается, когда ответ правильный, или если пользователь исчерпал все догадки (на основе числа фигур на рабочем листе, при необходимости измените его).).
Важно: я не позволил игроку угадать «букву или слово».Я также разрешаю отменить / выйти из игры, если пользователь не вводит буквы.
Option Explicit
Sub Hangman()
Dim Answer As String
Call ResetGame
Answer = UCase(Application.InputBox("Choose the word", "Hangman Game"))
If Answer = "" Then
MsgBox "You did not type a word"
Exit Sub
End If
Call PlayGame(Answer)
End Sub
Private Sub ResetGame()
Dim sh As Shape
With Worksheets("Game")
.Range("A1:B1").Clear
.Range("B1").Font.ColorIndex = 3
For Each sh In .Shapes
sh.Visible = msoFalse
DoEvents
Next sh
End With
End Sub
Private Sub PlayGame(Answer As String)
Dim i As Long
Dim correctGuesses As String
Dim wrongGuesses As Long
Dim thisGuess As String
i = 1
thisGuess = GetNextGuess()
Do While Len(correctGuesses) <= Len(Answer)
Select Case True
Case (thisGuess <> Mid(Answer, i, 1))
' Player has not correctly guessed the next letter in sequence
wrongGuesses = wrongGuesses + 1
Call ShowShape(wrongGuesses)
DoEvents
Case Else
correctGuesses = correctGuesses + thisGuess
Worksheets("Game").Range("A1").Value = correctGuesses
i = i + 1
If (correctGuesses = Answer) Then
MsgBox "You Win!", vbExclamation
Exit Do
End If
End Select
If wrongGuesses >= Worksheets("Game").Shapes.Count Then
'Player has made too many guesses and unable to solve the game
Worksheets("Game").Range("B1").Value = Answer
MsgBox "You lose!", vbCritical
Exit Do
End If
' prompt for the next letter/guess:
thisGuess = GetNextGuess()
Loop
End Sub
Private Sub ShowShape(index As Long)
Worksheets("Game").Shapes(index).Visible = msoTrue
DoEvents
Worksheets("Game").Shapes(index).Select
End Sub
Private Function GetNextGuess() As String
Dim thisGuess As String
thisGuess = Trim(UCase(Application.InputBox("Choose a letter", "Hangman")))
If Len(Trim(thisGuess)) < 1 Then
If MsgBox("You did not choose a letter", vbRetryCancel) = vbRetry Then
thisGuess = GetNextGuess()
Else
End
End If
End If
GetNextGuess = Left(thisGuess, 1)
End Function