gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:10:03 25 4
gpt4 key购买 nike

所以我在这里得到了以下代码...我必须提供 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com