我如何确定用户在刽子手 c# 游戏中猜错了



我正在研究刽子手的游戏,我正在尝试弄清楚如何显示消息并在用户猜出单词中没有的字母时将数字增加 1。现在正在发生的事情是,当用户猜出单词中没有的字母时,会为单词中的每个字母显示一条消息,并为单词中的每个字母增加一个数字。

我正在尝试这样做,以便当用户做出错误的猜测时,它只显示该消息一次,并且只将数字增加一。这是我拥有的代码,用于确定用户何时猜错

for (int index = 0; index < charArray.Length; index++)
{
if (charArray[index] == userGuess && userGuess != lettersUsed[index])
{
found[index] = userGuess;
lettersUsed[index] = userGuess;
}
else if (lettersUsed[index] == userGuess)
{
Console.WriteLine($"{userGuess} is already in the word");
}
else if (charArray[index] != userGuess)
{
Console.WriteLine($"{userGuess} is not in the word");
guesses++;
}
}

任何建议都会很棒!

如果字母已经在单词中。您打印"x 已经在单词中"消息 charArray.Length(( 次数。使用布尔值确定是否找到了该字母,然后仅打印一次消息。

class HangmanGame
{
char[] charArray = {'h', 'a', 'n', 'g', 'm', 'a', 'n'};
char[] found = {'*', '*', '*', '*', '*', '*', '*'};
int guesses = 0;
public void TestLetter(char userGuess)
{
bool foundLetter = false, alreadyInWord = false;
for (int index = 0; index < charArray.Length; index++)
{
if(userGuess == found[index])
{
alreadyInWord = true;
break;
}
else if(userGuess == charArray[index])
{
found[index] = charArray[index];
foundLetter = true;
}
}
if(alreadyInWord)
{
String s = "The letter " + userGuess + " was already in the word: " + new string(found) + ".";
Console.WriteLine(s);
}
else if(foundLetter)
{
String s = "You guessed correctly: " + new string(found) + ".";
Console.WriteLine(s);
}
else
{
guesses++;
}
}
}

我认为charArray旨在存储用户试图猜测的原始单词。如果我是你,我会查看列表来存储用户找到的字符。

var found = new List<char>();
...
if (charArray.Any(c => c == userGuess)) // If any character in the char array equals to the guess
{
if (found.Any(c => c == userGuess))
{
Console.WriteLine($"{userGuess} is already in the word");
}
else
{
found.Add(userGuess);
}
}
else 
{
Console.WriteLine($"{userGuess} is not in the word");
guesses++;
}

顺便说一下,Any 是一个 Linq 扩展方法,它检查集合的任何元素是否与您作为参数输入的谓词匹配。为此,您必须使用类似javascript的箭头函数语法。

相关内容

最新更新