Hangman Game在c#中使用for循环迭代数组

本文关键字:for 循环 迭代 数组 Game Hangman | 更新日期: 2023-09-27 17:53:22

那么,早些时候我发布了一个问题,询问如何通过字符数组运行字符串以使每个字母等于数组中的单独字符值

我尝试使用foreach循环,然后将数组中的每个对象标记为"Guess",然后根据用户输入的值测试每个值,但是如果用户输入了一个假值,我无法弄清楚如何在循环结束时输出。由于循环被设计为对每个值执行一些操作,因此不再在每次值为false时输出数组值。

所以我有点卡住了。我认为有一种方法可以用for循环来做,但我还是有点笨。我想知道是否有人能帮我。

        char letter;
        int score = 0;
        string hangWord;
        //input inputs
        Console.WriteLine("Welcome to the hangman game!");
        Console.WriteLine();
        Console.WriteLine();
        Console.WriteLine();
        Console.WriteLine("Player 1 please enter a word.");
        hangWord = Convert.ToString(Console.ReadLine());
        char[] hangCharacters = hangWord.ToCharArray();
        char[] asteriskWord = hangWord.ToCharArray();
        string displayWord;
        foreach (char guess in asteriskWord)
        {
            asteriskWord[guess] = '*';
        }
        while (score < 5)
        {
            Console.WriteLine("Enter a letter please");
            Console.WriteLine();
            foreach (char guess in hangCharacters)
            {                //How do I write a loop that tests all values and if none are correct
                             //displays "You guessed incorrectly"?
                letter = Convert.ToChar(Console.ReadLine());
                if( guess == letter)
                {
                    Console.WriteLine("You guessed correctly!");
                    Console.WriteLine
                        //Also I don't know how to change the correct value      in the asteriskWord[] so that it displays
                        //only the character that was guessed in asteriskWord[]
                }
            }
        }
        Console.WriteLine("Your score is " + score);
        if (displayWord == hangWord)
            Console.WriteLine("You Win! Thank you for playing!");
        else
        {
            Console.WriteLine("Thank you for playing! Try again!");
        }

Hangman Game在c#中使用for循环迭代数组

在foreach将bool标志设为false之前,只有当字母匹配时才在foreach中设置为true,否则将保持false。在迭代之后测试条件,并根据标志状态显示消息。

您可以稍微改变一下逻辑,看看猜测是否在挂起字符中。此时,您只检查用户输入的字母是否为当前迭代的字母

letter = Convert.ToChar(Console.ReadLine());
if(hangCharacters.Any(c => c == letter))
    Console.WriteLine("You guessed correctly!");
else
    Console.WriteLine("You guessed incorrectly!");

要使用上述内容,您需要包含System.Linq