因此我需要制作类似于游戏HangMan的代码,您需要通过输入字母来猜测单词。一切都很好,但我需要,当我输入错误的字母时,它说,这封信不在那个词中。请帮忙!
string secretword = "m a n a m e j e f f";
string[] secretarray = secretword.Split(' ');
string letter = "";
string[] guessarray = new string[secretarray.Length];
int counter = 0;
int guess = 0;
for (int i = 0; i < guessarray.Length; i++)
{
guessarray[i] = "_";
}
foreach (string s in guessarray)
{
Console.Write(s + " ");
}
while (guess != secretarray.Length)
{
Console.WriteLine();
Console.Write("Enter a letter: ");
letter = Convert.ToString(Console.ReadLine());
for (int i = 0; i < secretarray.Length; i++)
{
if (secretarray[i] == letter)
{
guessarray[i] = letter;
guess++;
}
}
if (guess != 0)
{
foreach (string s in guessarray)
{
Console.Write(s + " ");
}
}
else if (guess == 0)
{
Console.WriteLine("There is no letter like that!");
}
counter++;
}
Console.WriteLine();
Console.WriteLine("You guessd the word with tries: " + counter);
Console.ReadLine();
答案 0 :(得分:0)
您可以使用布尔来跟踪猜测是否与任何字母匹配。
while (guess != secretarray.Length)
{
Console.WriteLine();
Console.Write("Enter a letter: ");
letter = Convert.ToString(Console.ReadLine());
bool correct = false;
for (int i = 0; i < secretarray.Length; i++)
{
if (secretarray[i] == letter)
{
guessarray[i] = letter;
guess++;
correct = true;
}
}
if (guess != 0)
{
foreach (string s in guessarray)
{
Console.Write(s + " ");
}
}
else if (!correct)
{
Console.WriteLine("There is no letter like that!");
}
counter++;
}
答案 1 :(得分:0)
也许这样的事情可以胜任这项工作。
string secretword = "m a n a m e j e f f";
string[] secretarray = secretword.Split(' ');
string letter = "";
string[] guessarray = new string[secretarray.Length];
int counter = 0;
int guess = 0;
bool goodguess = false;
for (int i = 0; i < guessarray.Length; i++)
{
guessarray[i] = "_";
}
foreach (string s in guessarray)
{
Console.Write(s + " ");
}
while (guess != secretarray.Length)
{
goodguess = false;
Console.WriteLine();
Console.Write("Enter a letter: ");
letter = Convert.ToString(Console.ReadLine());
for (int i = 0; i < secretarray.Length; i++)
{
if (secretarray[i] == letter)
{
guessarray[i] = letter;
guess++;
goodguess = true;
}
}
if (goodguess == true)
{
foreach (string s in guessarray)
{
Console.Write(s + " ");
}
}
else
{
Console.WriteLine("There is no letter like that!");
}
counter++;
}
Console.WriteLine();
Console.WriteLine("You guessd the word with tries: " + counter);
Console.ReadLine();