C#一个简单的Hangman游戏

时间:2013-05-25 20:46:16

标签: c# project words

我正在尝试创建一个简单的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!

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

2 个答案:

答案 0 :(得分: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!");
                }
            }

        }
    }
};

答案 1 :(得分: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();




            }
        }
    }