-2

我正在尝试创建一个简单的 Hangman 游戏,到目前为止,我已经让它从文本文件中读取所有单词,但我不知道如何使代码适用于每个单词。我有另一个项目,使用 3/4 个单词但重复嵌套的 if 语句。我想让它尽可能短。这是我到目前为止的代码:

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] words = System.IO.File.ReadAllLines(@"C:\Users\ADMIN\Desktop\Letters\Letters.txt");
        int LengthOfArray = words.Length;
        Random rnd = new Random();
        int random = rnd.Next(1, 3);
        char[] letters = words[random].ToCharArray();
        bool WordIsHidden = true;
        char hiddenChar = '_';
        char GuessedLetter = hiddenChar;

        var retry = true;
        while (retry = true)
        {
            Console.WriteLine(letters);
            letters = GuessedLetter.ToString().ToCharArray();
            for (int i = 1; i <= LengthOfArray; i++)
            {
                Console.Write("{0} ", GuessedLetter);
            }
            Console.WriteLine("Enter a letter!");
            char letter = char.Parse(Console.ReadLine());
            if (words[random].Contains<char>(letter))
            {
                WordIsHidden = false;
                GuessedLetter = letter;
                Console.Write(letters);
            }
            else
            {
                 if (WordIsHidden == true)
                {
                    Console.Write("You guessed wrong!");

                }
            }

        }
    }
}

另外我试图让游戏显示每个字母,用户已经猜到它的对应位置,但现在字母比单词的其余部分高一行,并且不在正确的位置。

编辑:

Here is the result :
cat
___Enter a letter!
a
__
aaaEnter a letter!
t
aa
tttEnter a letter!

如果有人知道这是从哪里来的以及如何解决它,任何帮助将不胜感激。

4

2 回答 2

3

好的,我在这里猜测问题,但我认为您在这里描述的是一个错误:

for (int i = 1; i <= LengthOfArray; i++)

应该:

for (int i = 0; i < LengthOfArray; i++)

由于 C# 中的索引从 0 开始。这可能导致您看到的问题。但是,这里的 foreach 循环会更好,因为您根本不使用值“i”。

foreach(var c in words)
  Console.Write(GuessedLetter);

至于使程序更短,现在不要太担心,让程序运行起来,然后再重构。我建议从研究 LINQ/IEnumerable 扩展开始,也可以通过 var 关键字进行类型推断。

编辑:

好的,我花了 5 分钟查看您的代码,并进行了一些修复(请参阅评论)。请检查原始代码。这不是一个漂亮、高效或优雅的解决方案,但希望它的行为更符合您的预期。

using System;
using System.Linq
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        string[] words = System.IO.File.ReadAllLines(@"C:\Users\ADMIN\Desktop\Letters\Letters.txt");
        int LengthOfArray = words.Length;
        Random rnd = new Random();
        int random = rnd.Next(1, 3);
        char[] letters = words[random].ToCharArray();
        bool WordIsHidden = true;
        char hiddenChar = '_';
        //fix 1 use a list or hashset or similar to store the selected chars
        var guessed = new List<char>();
        var retry = true;
        while (retry = true)
        {
            Console.WriteLine(letters);
            //fix 2, loop over the letters, checking whether they have been guessed
            foreach(var c in letters)
            {
                if (guessed.Contains(c))
                    Console.Write(c);
                else
                    Console.Write("_");
            }
            Console.WriteLine("\nEnter a letter!");
            char letter = char.Parse(Console.ReadLine());
            if (words[random].Contains<char>(letter))
            {
                WordIsHidden = false;
                guessed.Add(letter);
            }
            else
            {
                if (WordIsHidden == true)
                {
                    guessed.Clear();
                    Console.WriteLine("You guessed wrong!");
                }
            }

        }
    }
};
于 2013-05-25T20:59:18.393 回答
0

尝试这个

 using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace HangMan.cs.hange_man
    {
        class HangManGame
        {   // checking for word 
            static bool IsWord(string secreword, List<string> letterGuessed) 
            {

                bool word = false;
                // loop through secretword
                for (int i = 0; i < secreword.Length; i++) 
                {
                    // initialize c with the index of secretword[i]
                    string c = Convert.ToString(secreword[i]);
                    // check if c is in list of letters Guess
                    if (letterGuessed.Contains(c))
                    {
                        word = true;
                    }
                        /*if c is not in the letters guessed then we dont have the
                         * we dont have the full word*/
                    else 
                    {
                        // change the value of word to false and return false
                        return word = false;

                    }

                }
                return word;
            }

            // check for single letter 
            static string Isletter(string secretword, List<string> letterGuessed) 
            {
                // set guessedword as empty string
                string correctletters = "";
                // loop through secret word
                for (int i =0 ; i < secretword.Length; i++)
                {
                    /* initialize c with the value of index i
                     * mean when i = 0
                     * c = secretword[0] is the first index of secretword
                     * c = secretword[1] is the second index of secretword and so on */
                    string c =Convert.ToString( secretword[i]);

                    // if c is in list of lettersGuessed 
                    if (letterGuessed.Contains(c))
                    {
                        // add c to correct letters
                        correctletters += c;
                    }
                    else
                    {
                        // else print (__) to show that the letter is not in the secretword
                        correctletters += "_ ";
                    }

                }
                // after looping return all the correct letters found
                return correctletters;

            }

            // The alphabet to use
            static void GetAlphabet(string letters) 
            {
                List <string>  alphabet = new List<string>();

                for (int i = 1; i <= 26; i++) 
                {
                    char alpha = Convert.ToChar(i+96);
                    alphabet.Add (Convert.ToString(alpha));                
                }

                // for regulating the number of alphabet left
                int num = 49;
                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.WriteLine("Letters Left are :");

                for (int i = 0; i < num; i++)
                {
                    if (letters.Contains(letters))
                    {
                        alphabet.Remove(letters);
                        num -= 1;
                    }
                    Console.Write("["+alphabet[i]+"] ");
                }

                Console.WriteLine();

            }
            /* random strings
            static string RandomWord(string secretword) 
            {
               Random rnd = new Random();

            }*/


            static void Main() 
            {
                Console.Title = ("HangMan");

                // secretWord
                string secretword = "foreground";
                List <string> letterGuessed = new List<string>();


                int live = 5;
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Welcome to Hangman Game");
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.WriteLine("Guess for a {0} letter Word ", secretword.Length);
                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.WriteLine("You have {0} live", live);
                Isletter(secretword,letterGuessed);
                // while live is greater than 0
                while (live > 0 ) 
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    string input = Console.ReadLine();

                    // if letterGuessed contains input



                        if (letterGuessed.Contains(input))
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("You Entered letter [{0}] already",input);
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.WriteLine("Try a different word");
                            GetAlphabet(input);
                            continue;                    
                        }                                     


                    // if word found
                    letterGuessed.Add(input);
                    if (IsWord(secretword,letterGuessed)) 
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine(secretword);
                        Console.WriteLine("Congratulations");
                        break;
                    }
                        // if a letter in word found
                    else if (secretword.Contains(input))
                    {
                        Console.ForegroundColor = ConsoleColor.Magenta;
                        Console.WriteLine("wow nice entry");
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        string letters = Isletter(secretword, letterGuessed);
                        Console.Write(letters);

                    }
                        // when a wrong code is entered
                    else 
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Oops, letter not in my word");
                        live-=1;
                        Console.ForegroundColor = ConsoleColor.Magenta;
                        Console.WriteLine("You have {0} live", live);
                    }
                    Console.WriteLine();
                    // print secret word 
                    if (live == 0) 
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("Game over \nMy secret Word is [ {0} ]",secretword);
                        break;
                    }

                }
                Console.WriteLine("press any key to Exit");
                Console.ReadKey();




            }
        }
    }
于 2015-01-25T15:55:04.473 回答