我需要帮助来尝试创建一个绞刑游戏。我以某种方式无法正确显示正确的字母。我使用的是intGuessed数组和word数组。比较两者并显示正确的字母,并显示“ *”代表不正确的字母。
代码:
For I As Integer = 0 To 9
Console.WriteLine(“Enter a letter please: ”)
strInput = Console.ReadLine()
Console.WriteLine()
Console.WriteLine()
If [Char].TryParse(strInput, charInput) Then
For G As Integer = 0 To word.Length - 1
Select Case strInput
Case word(G)
ReDim Preserve aryGuessed(G + 1)
If Not aryGuessed.Contains(charInput) Then
aryGuessed(intGuessed) = charInput
intGuessed += 1
End If
For A As Integer = 0 To aryGuessed.Length - 1
For B As Integer = 0 To word.Length - 1
If aryGuessed(A) = word(B) Then
Console.Write(word(B))
End If
Next
Next
If G >= word.Length Then
Console.Write("correct")
End If
Case Else
Console.Write("*")
If G >= word.Length Then
bolwrong = True
End If
End Select
Console.WriteLine()
Next
End If
If bolwrong = True Then
intScore += 1
Console.WriteLine("incorrect")
Console.WriteLine("your score is now " + intScore.ToString())
Console.ReadLine()
bolwrong = False
End If
Next
答案 0 :(得分:0)
我建议不要使用很多代码,而要循环很多。为了使您更有意义,我进行了一些改动,但是主要的变化是,我创建了一个与原始单词相同的'*'数字的字符串,并用更简单,更高效的代码替换了一部分代码
最终您的For .. Select Case .. End Case .. Next
块中的大部分都可以替换为..
For G As Integer = 0 To word.Length - 1
If word(G) = charInput Then
guessedWord = guessedWord.Remove(G, 1).Insert(G, strInput)
boolWrong = False
End If
Next
猜测/完成检查逻辑可以移到外循环的末尾。
这就是您最终的代码。.
Dim guessedWord As New String("*"c, word.Length)
For I As Integer = 0 To 9
Console.WriteLine(“Enter a letter please: ”)
strInput = Console.ReadLine()
Console.WriteLine()
Console.WriteLine()
boolWrong = True
If Char.TryParse(strInput, charInput) Then
aryGuessed(I) = strInput
For G As Integer = 0 To word.Length - 1
If word(G) = charInput Then
guessedWord = guessedWord.Remove(G, 1).Insert(G, strInput)
boolWrong = False
End If
Next
Console.WriteLine()
Console.WriteLine(guessedWord)
ReDim Preserve aryGuessed(aryGuessed.Count)
End If
If guessedWord = word Then
Console.Write("Correct!")
Exit For
End If
If boolWrong = True Then
intScore += 1
Console.WriteLine("incorrect")
Console.WriteLine("your score is now " + intScore.ToString())
End If
Next
顺便说一句
guessedWord = guessedWord.Remove(G, 1).Insert(G, strInput)
是完成字符删除并将字符全部插入一行的一种相当简洁的方法
与写作相同
guessedWord = guessedWord.Remove(G, 1)
guessedWord = guessedWord.Insert(G, strInput)