【问题标题】:Hangman in C# Looping IssueC# 循环问题中的刽子手
【发布时间】:2014-05-20 14:15:48
【问题描述】:

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

示例 - Word was "Heaven" - User Enters "e" - Produces - _ 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();

【问题讨论】:

  • 获取字母的索引(如果存在)并用该索引上的字母替换'_'
  • 请将整个 switch 语句替换为:word = words[randomword - 1]; tries = word.Length;
  • @musefan 甚至只是将随机词更改为 rand.Next(0, 4) 并删除 -1。
  • @Gray:确实!没有什么让可怜的小伙子感到困惑

标签: c# loops


【解决方案1】:

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

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

【讨论】:

  • 请注意,您也可以在此处使用guessedLetters 以确保他们不会意外输入相同的字母两次。在解析guess 之后调用guessedLetters.Add 之前,你可以做if (guessedLetters.Contains(guess)) {Console.WriteLine("already guessed that!"); continue;}
【解决方案2】:

怎么样:

static void Main(string[] args)
{

    string[] words = new string[] { "Apple", "Banana", "Pear", "Pineapple", "Melon"};
    Random random = new Random();

    string wordToGuess = words[random.Next(5)].ToLower();
    char[] currentLetters = new char[wordToGuess.Length];
    for (int i = 0; i < currentLetters.Length; i++) currentLetters[i] = '_';
    int numTries = currentLetters.Length + 1;
    bool hasWon = false;
    do
    {
        string input = Console.ReadLine().ToLower();
        if (input.Length == 1) //guess a letter
        {
            char inputChar = input[0];
            for (int i = 0; i < currentLetters.Length; i++)
            {
                if (wordToGuess[i] == inputChar)
                {
                    currentLetters[i] = inputChar;
                }
            }
            if (!currentLetters.Contains('_'))
            {
                hasWon = true;
            }
            else
            {
                Console.WriteLine(new string(currentLetters));
            }
        }
        else
        {
            if (input == wordToGuess)
            {
                hasWon = true;
            }
            else
            {
                Console.WriteLine("Incorrect!");
                Console.WriteLine(new string(currentLetters));
            }
        }

        numTries--;

    } while (new string(currentLetters) != wordToGuess && numTries > 0 && !hasWon);

    if (hasWon)
    {
        Console.WriteLine("Congratulations, you guessed correctly.");
    }
    else
    {
        Console.WriteLine("Too bad! Out of tries");
    }
}

【讨论】:

【解决方案3】:

您需要存储猜测结果并检查您的循环(将您的 do while 循环更改为如下):

string resultword = word;
do
{
    char guess = char.Parse(Console.ReadLine());


    if (word.Contains(guess))
    {
        resultword = resultword.Replace(guess, ' ');

        for (int i = 0; i < resultword.Count(); i++)
        {
            if (resultword[i] == ' ')
            {
                Console.Write(word[i]);
            }
            else
            {
                Console.Write("_");
            }
        }
    }

    Console.WriteLine();
}
while (tries-- != 0 && resultword.Trim() != string.Empty);

【讨论】:

    【解决方案4】:

    怎么样,使用你现有的代码;

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication3
    {
        internal class Program
        {
            private static void Main(string[] args)
            {
                List<string> words = new List<string>();
                int tries = 0;
                Random rand = new Random();
                var currentLetters = new List<char>();
                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 (!currentLetters.Contains(guess))
                    {
                        currentLetters.Add(guess);
                        foreach (var l in word.ToCharArray().Intersect(currentLetters).ToArray())
                        {
                            word = word.Replace(l, '_');
                        }
                    }
                    Console.WriteLine(word);
                } //If my word contains A "_" i will keep looping
                while (word.Contains("_"));
    
            Console.ReadKey();
        }
    }
    

    }

    【讨论】:

      【解决方案5】:

      工作示例:

              List<string> words = new List<string>();
              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);
      
              List<char> guesses = new List<char>();
              string guessedWord = "";
      
              for(int i=0;i<word.Length;i++)
              {
                  guessedWord += "_";
              }
      
              //Works for the 1st Guess
              do
              {
                  char guess = char.Parse(Console.ReadLine());
      
                  if (word.Contains(guess))
                  {
                      guesses.Add(guess);
                  }
      
                  foreach (char storedGuess in guesses)
                  {
                      if(word.Contains(storedGuess))
                      {
                          int index = word.IndexOf(storedGuess);
                          while(index > -1)
                          {
                              StringBuilder sb = new StringBuilder(guessedWord);
                              sb[index] = storedGuess;
                              guessedWord = sb.ToString();
      
                              index = word.IndexOf(storedGuess, index+1);
                          }
                      }
                  }
      
                  Console.WriteLine(guessedWord);
              }
              while (guessedWord.Contains("_"));
      
              Console.ReadKey();
      

      【讨论】:

        【解决方案6】:

        您提到了尝试次数,但您在使用后从未在代码中使用它。大概,您想要执行以下操作:

        • 随机选择一个词(在您的情况下,您选择用户提供的五个词之一)
        • 将猜测(尝试?)的次数设置为单词的长度加 2。如果他们猜到了一个存在的字母,那么它是免费的。如果该字母不存在,那么他们将失去其中一项猜测。
        • 在每次猜测之前,将所有未猜测的字母替换为“_”来显示单词。
        • 当用户猜测存在的字母时,将显示的单词中的“_”替换为该字母。

        这是一些应该可以工作的示例代码(未经测试):

            string displayword = String.Copy(word);
            for (int j = 0; j < displayword.length; j++) displayword[j]='_';
            do {
                // Display the word so far.
                Console.WriteLine("Word is {0}", displayword);
        
                // Get a guess from the user
                char guess = char.Parse(Console.ReadLine());
                if (word.Contains(guess)) {
                    for (j=0; j<word.length; j++) {
                      if (word[j] == guess) displayword[j]=guess;
                    }
                } else {
                  // Decrease the tries.
                  tries--;
                }
            } while (displayword.Contains("_") && (tries > 0));
        

        【讨论】:

          【解决方案7】:

          到目前为止,您需要将输入的单词与结果区分开来。用下划线初始化结果,然后在人们猜测时将字母添加到结果中。如果将result 设为 char 数组而不是字符串,会更容易一些。

                  var result = new string('_', word.Length).ToCharArray();
                  do
                  {
                      char guess = char.Parse(Console.ReadLine());
                      for (var i = 0; i < word.Length; ++i)
                      {
                          if(word[i] == guess)
                          {
                              result[i] = guess;
                          }
                      }
                      Console.WriteLine(new string(result));
                  }
                  //If my word contains A "_" i will keep looping
                  while (result.Contains('_') && --tries != 0); 
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-02-22
            • 2016-02-13
            • 1970-01-01
            • 2013-03-05
            • 1970-01-01
            • 2021-12-30
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多