【发布时间】:2019-12-03 12:32:32
【问题描述】:
我正在尝试制作一个刽子手游戏,它从单词的文本文件中随机选择一个单词。然后它以星号显示单词,并要求用户猜测单词的每个字母,如果他们猜对了它就会发现那个字母。他们一直玩,直到猜出单词中的所有字母。猜出单词后,它将显示数字错过并询问他们是否想再玩一次。
我遇到的问题是,当单词被正确猜到时,即使单词未被发现,它也会一直要求输入字母。我不知道如何解决这个问题。如果可能的话,我想在不使用 linq 的情况下做到这一点。 任何帮助都会得到帮助
static void Main(string[] args)
{
char[] guessed = new char[26];
char guess = ' ';
char playAgain= ' ';
bool validLetterInput = false;
bool validAnswer = false;
int amountMissed = 0, index = 0;
do
{
// initilization of word and testword so that we could generate a testword with the same length as original
char[] word = RandomLine().Trim().ToCharArray();
char[] testword = new string('*', word.Length).ToCharArray();
char[] copy = word;
Console.WriteLine(testword);
Console.WriteLine("I have picked a random word on animals");
Console.WriteLine("Your task is to guess the correct word");
//Check if the 2 arrays are equal
while (testword != word)
{
while (!validLetterInput)
{
try
{
Console.Write("Please enter a letter to guess: ");
guess = char.Parse(Console.ReadLine().ToLower());
//Checks if guess is letter or not
if (((guess >= 'A' && guess <= 'Z') || (guess >= 'a' && guess <= 'z')))
{
validLetterInput = true;
}
else
{
Console.WriteLine("Invalid Input");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
validLetterInput = false;
bool right = false;
for (int j = 0; j < copy.Length; j++)
{
if (copy[j] == guess)
{
Console.WriteLine("Your guess is correct.");
testword[j] = guess;
guessed[index] = guess;
index++;
right = true;
}
}
if (right != true)
{
Console.WriteLine("Your guess is incorrect.");
amountMissed++;
}
else
{
right = false;
}
Console.WriteLine(testword);
}
Console.WriteLine($"The word is {string.Join("",testword)}. You missed {amountMissed} times.");
while (!validAnswer)
{
try
{
Console.WriteLine("Do you want to guess another word? Enter y or n: ");
playAgain = char.Parse(Console.ReadLine());
if(playAgain == 'y' || playAgain == 'Y' || playAgain == 'n' || playAgain == 'N')
{
validAnswer = true;
}
else
{
Console.WriteLine("Invalid input try again");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
validAnswer = false;
} while (playAgain == 'y' || playAgain == 'Y');
Console.WriteLine("Good-Bye and thanks for playing my Hangman game.");
}
public static string RandomLine()
{
// store text file in an array and return a random value
string[] lines = File.ReadAllLines("E:\\Amimals1.csv");
Random rand = new Random();
return lines[rand.Next(lines.Length)].ToLower();
}
}
【问题讨论】:
-
这是了解调试器工作原理的好机会。您可以在代码中放置断点,单步通过代码中的语句,并在程序停止时观察变量的值
标签: c#