c# - C# 循环问题中的刽子手

标签 c# loops

所以我在这里得到了以下代码...我必须提供 5 个用户提供的单词,在 5 个上随机化并给出其中的任何一个进行猜测,tries = word length + 2。我遇到的主要问题是循环整个检查以填写第二个、第三个猜测等。第一个猜测很好。我将如何循环并保留被猜对的字符,同时仍将未被猜到的字符保留为“_”字符。

示例 - 单词是“Heaven” - 用户输入“e” - 生成 - _ e _ _ e _ 没有空格。 尝试次数将等于 6(字长)+ 2 = 8 次尝试

int tries = 0;
Random rand = new Random();
int randomword = rand.Next(1, 5);
string word = "";

Console.WriteLine("Please Enter 5 Words into the System");
Console.WriteLine();

for (int i = 0; i < 5; i++)
{
    words.Add(Console.ReadLine());
    Console.Clear();
}

Console.WriteLine("For Display Purposes. Here are Your 5 Words");
Console.WriteLine("===========================================");
Console.WriteLine();
foreach (var item in words)
{
    Console.WriteLine(item);
}

Console.WriteLine();
Console.WriteLine("Now Guess The word given Below");
Console.WriteLine();

switch (randomword)
{
    case 1:
        //Gets the List index 0 - 1st word in the list
        word = words[0];
        tries = word.Length;
        break;
    case 2:
        word = words[1];
        tries = word.Length;
        break;
    case 3:
        word = words[2];
        tries = word.Length;
        break;
    case 4:
        word = words[3];
        tries = word.Length;
        break;
    case 5:
        word = words[4];
        tries = word.Length;
        break;
    default:
        break;
}
//Default + addition to the Length
tries += 2;

Console.WriteLine();
Console.WriteLine("You Have {0} + tries",tries );
//Works for the 1st Guess
do
{
    char guess = char.Parse(Console.ReadLine());
    if (word.Contains(guess))
    {
        foreach (char item in word)
        {
            if (item == guess)
            {
                Console.Write(item);
            }
            else
            {
                Console.Write("_");
            }
        }
    }
    Console.WriteLine();
} 
//If my word contains A "_" i will keep looping
while (word.Contains("_"));

Console.ReadKey();

最佳答案

您的主要问题是您只跟踪当前的猜测,而不是之前的所有猜测。您可以使用 HashSet跟踪您之前的猜测。所以定义一个变量HashSet<char> guessedLetters在你的 do 之前循环,然后在解析“猜测”后作为循环中的第二行执行 guessedLetters.Add(guess) .然后替换 if(item==guess)if(guessedLetters.Contains(item)) .中提琴,只有三行代码更改!

最后你的退出条件可以是while (word.Any(c=>!guessedChars.Contains(c)) && --tries != 0); .

关于c# - C# 循环问题中的刽子手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17834515/

相关文章:

swift - 在数组中找到 kindOf 类并在 Swift 中替换它的最简单方法是什么?

c - C 中的数字求和

c# - 销毁不销毁GameObject

java - 如果给出无效响应,请重新运行 main 方法?

c - 如何遍历 char ** 指针?

c# - 从 C# 中的唯一(独立)元素获取索引

php - 从循环中的对象中删除项目

c# - 退出工作流程?

c# - 在列表集合中查找对象

c# - 如何使用 EF 在我的 asp.net core 3.1 MVC 应用程序中正确使用我的 SQLite db?