从列表中选择随机单词?

2024-03-30

我无法从另一个文件的列表中随机选择单词。 事实上我什至无法让它选择任何单词。我不确定如何连接这两个文件。 希望有人能帮忙,我是初学者,所以请尽可能简单地解释一下:)

我有 2 个文件,一个名为 program.cs,另一个名为 WordList.cs 我将粘贴所有代码,但首先粘贴我遇到问题的小片段。我只是不知道如何正确编写代码。

这是称为“Pick word”的小部分:

 //PICK WORD

    static string pickWord()
    {
        string returnword = "";

        TextReader file = new StreamReader(words);
        string fileLine = file.ReadLine();


        Random randomGen = new Random();
        returnword = words[randomGen.Next(0, words.Count - 1)];
        return returnword;
    }

这是 Program.cs 中的所有代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

class Hangman
{

    static void Main(string[] args)                                                  
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.Title = "C# Hangman";
        Console.WriteLine("Welcome To C# Hangman!");

        //MENU
        int MenuChoice = 0;
        while (MenuChoice != 4)
        {

        Console.Write("\n\t1) Add words");
        Console.Write("\n\t2) Show list of words");
        Console.Write("\n\t3) Play");
        Console.Write("\n\t4) Quit\n\n");

        Console.Write("\n\tChoose 1-4: ");        //Choose meny item

        MenuChoice = Convert.ToInt32(Console.ReadLine());
        WordList showing = new WordList();

        switch (MenuChoice)
        {
            case 1:               
                Console.Write("\n\tAdd a word\n\n");
                var insert = Console.ReadLine();
                showing.AddWord(insert);
                Console.Write("\n\tList of words\n\n");
                showing.ListOfWords();                
                break;
            case 2:
                Console.Write("\n\tList of words\n\n");
                showing.ListOfWords();
                break;


            case 3:   //Running game

                int numGuessesInt = -1;

                while (numGuessesInt == -1)
                {
                    /* Sets the number of guesses the user has to guess the word*/
                    pickNumGuesses(ref numGuessesInt);
                }

                /* Randomly picks a word*/
                string word = pickWord();


                /* Creates a list of characters that will show */
                List<char> guessedLetters = new List<char>();
                bool solved = false;
                while (solved == false)
                {
                    /* Displaying a string to the user based on the user's correct guesses.
                     * If nothing is correct string will return "_ _ _ " */
                    string wordToDisplay = displayWord(guessedLetters, word);
                    /* If the string returned contains the "_" character, all the
                    * correct letters have not been guessed, so checking if user
                    * has lost, by checking if numGuessesLeft is less than 1.*/
                    if (!wordToDisplay.Contains("_"))
                    {
                        solved = true;
                        Console.WriteLine("You Win!  The word was " + word);
                        /* Check if the user wants to play again.  If they do,
                        * then solved is set to true, will end the loop,
                        * otherwise, checkIfPlayAgain will close the program.*/
                        checkIfPlayAgain();
                    }
                    else if (numGuessesInt <= 0)
                    {
                        solved = true;
                        Console.WriteLine("You Lose!  The word was " + word);
                        checkIfPlayAgain();
                    }
                    else
                    {
                        /* If the user has not won or lost, call guessLetter,
                        * display the word, minus guesses by 1*/
                        guessLetter(guessedLetters, word, wordToDisplay, ref numGuessesInt);
                    }
                }

                    break;

            case 4:
                Console.WriteLine("\n\tEnd game?\n\n");
                break;
            default:
                Console.WriteLine("Sorry, invalid selection");
                break;  
        }

        }

    }

    // ****** PICK NUMBER OF GUESSES ******

    static void pickNumGuesses(ref int numGuessesInt)
    {
        string numGuessesString = "";
        Console.WriteLine("Pick a number of guesses");
        numGuessesString = Console.ReadLine();
        try
        {
            numGuessesInt = Convert.ToInt32(numGuessesString);
            if (!(numGuessesInt <= 20 & numGuessesInt >= 1))
            {
                throw new Exception();
            }
        }
        catch (Exception)
        {
            numGuessesInt = -1;
            Console.WriteLine("Error: Invalid Number of Guesses");
        }
    }

    //PICK WORD

    static string pickWord()
    {
        string returnword = "";

        TextReader file = new StreamReader(words);
        string fileLine = file.ReadLine();


        Random randomGen = new Random();
        returnword = words[randomGen.Next(0, words.Count - 1)];
        return returnword;
    }


    // ****** Display word ******

    static string displayWord(List<char> guessedCharacters, string word)
    {
        string returnedWord = "";
        if (guessedCharacters.Count == 0)
        {
            foreach (char letter in word)
            {
                returnedWord += "_ ";
            }
            return returnedWord;
        }
        foreach (char letter in word)
        {
            bool letterMatch = false;
            foreach (char character in guessedCharacters)
            {
                if (character == letter)
                {
                    returnedWord += character + " ";
                    letterMatch = true;
                    break;
                }
                else
                {
                    letterMatch = false;
                }
            }
            if (letterMatch == false)
            {
                returnedWord += "_ ";
            }
        }
        return returnedWord;
    }


    // ****** Guess letter ******

    static void guessLetter(List<char> guessedCharacters, string word, string wordToDisplay, ref int numGuessesLeft)
    {
        string letters = "";
        foreach (char letter in guessedCharacters)
        {
            letters += " " + letter;
        }
        Console.WriteLine("Guess a letter");
        Console.WriteLine("Guessed Letters: " + letters);
        Console.WriteLine("Guesses Left: " + numGuessesLeft);
        Console.WriteLine(wordToDisplay);
        string guess = Console.ReadLine();
        char guessedLetter = 'a';
        try
        {
            guessedLetter = Convert.ToChar(guess);
            if (!Char.IsLetter(guessedLetter))
            {
                throw new Exception();
            }
        }
        catch (Exception)
        {
            Console.WriteLine("Error: Invalid Letter Choice");
            //guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft);
        }
        bool repeat = false;
        for (int i = 0; i < guessedCharacters.Count; i++)
        {
            if (guessedCharacters[i] == guessedLetter)
            {
                Console.WriteLine("Error: Invalid Letter Choice");
                repeat = true;
                //guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft);
            }
        }
        if (repeat == false)
        {
            guessedCharacters.Add(guessedLetter);
            numGuessesLeft -= 1;
        }
    }

    // ****** Check to see if player wants to play again. ******

    static void checkIfPlayAgain()
    {
        Console.WriteLine("Would you like to play again? (y/n)");
        string playAgain = Console.ReadLine();
        if (playAgain == "n")
        {
            Environment.Exit(1);
        }
    }
}

这是 WordList.cs 的代码

using System;
using System.Collections.Generic;

class WordList
{
    List <string> words = new List<string>();

    public void ListOfWords()
    {
        words.Add("test");         // Contains: test
        words.Add("dog");          // Contains: test, dog
        words.Insert(1, "shit"); // Contains: test, shit, dog

        words.Sort();
        foreach (string word in words) // Display for verification
        {
            Console.WriteLine(word);

        }

    }

    public void AddWord(string value){
        words.Add(value);
      }
}

我对您的代码做了一些更改。该代码现在可以运行,但还远远不够完美。 您的解决方案有两个文件Program.cs and Wordlist.cs,看起来像这样

程序.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

public class Hangman
{
    /* 
     * Some notes on your code:
     *   use naming convention for methods and fields, i.e. methods names start with a capital letter
     *   use modifiers for methods, i.e private, public, protected in your method declarations
     *   make variables private if you use them on several methods
     *   and finally: read a book on c#
     *   
     */

    private static WordList words;
    private static Random randomGen = new Random();

    public static void Main(string[] args)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.Title = "C# Hangman";
        Console.WriteLine("Welcome To C# Hangman!");
        initializeWordList();

        //MENU
        int MenuChoice = 0;
        while (MenuChoice != 4)
        {

            Console.Write("\n\t1) Add words");
            Console.Write("\n\t2) Show list of words");
            Console.Write("\n\t3) Play");
            Console.Write("\n\t4) Quit\n\n");

            Console.Write("\n\tChoose 1-4: ");        //Choose meny item

            MenuChoice = Convert.ToInt32(Console.ReadLine());
            switch (MenuChoice)
            {
                case 1:
                    Console.Write("\n\tAdd a word\n\n");
                    var insert = Console.ReadLine();
                    words.Add(insert);
                    Console.Write("\n\tList of words\n\n");
                    foreach (string w in words) // Display for verification
                        Console.WriteLine(w);
                    break;
                case 2:
                    Console.Write("\n\tList of words\n\n");
                    foreach (string w in words) // Display for verification
                        Console.WriteLine(w);
                    break;


                case 3:   //Running game

                    int numGuessesInt = -1;

                    while (numGuessesInt == -1)
                    {
                        /* Sets the number of guesses the user has to guess the word*/
                        pickNumGuesses(ref numGuessesInt);
                    }

                    /* Randomly picks a word*/
                    string word = PickWord();


                    /* Creates a list of characters that will show */
                    List<char> guessedLetters = new List<char>();
                    bool solved = false;
                    while (solved == false)
                    {
                        /* Displaying a string to the user based on the user's correct guesses.
                         * If nothing is correct string will return "_ _ _ " */
                        string wordToDisplay = displayWord(guessedLetters, word);
                        /* If the string returned contains the "_" character, all the
                        * correct letters have not been guessed, so checking if user
                        * has lost, by checking if numGuessesLeft is less than 1.*/
                        if (!wordToDisplay.Contains("_"))
                        {
                            solved = true;
                            Console.WriteLine("You Win!  The word was " + word);
                            /* Check if the user wants to play again.  If they do,
                            * then solved is set to true, will end the loop,
                            * otherwise, checkIfPlayAgain will close the program.*/
                            checkIfPlayAgain();
                        }
                        else if (numGuessesInt <= 0)
                        {
                            solved = true;
                            Console.WriteLine("You Lose!  The word was " + word);
                            checkIfPlayAgain();
                        }
                        else
                        {
                            /* If the user has not won or lost, call guessLetter,
                            * display the word, minus guesses by 1*/
                            guessLetter(guessedLetters, word, wordToDisplay, ref numGuessesInt);
                        }
                    }

                    break;

                case 4:
                    Console.WriteLine("\n\tEnd game?\n\n");
                    break;
                default:
                    Console.WriteLine("Sorry, invalid selection");
                    break;
            }

        }

    }


    private static void initializeWordList()
    {
        words = new WordList();
        words.Add("test");         // Contains: test
        words.Add("dog");          // Contains: test, dog
        words.Insert(1, "shit"); // Contains: test, shit, dog
        words.Sort();
    }


    // ****** PICK NUMBER OF GUESSES ******

    private static void pickNumGuesses(ref int numGuessesInt)
    {
        string numGuessesString = "";
        Console.WriteLine("Pick a number of guesses");
        numGuessesString = Console.ReadLine();
        try
        {
            numGuessesInt = Convert.ToInt32(numGuessesString);
            if (!(numGuessesInt <= 20 & numGuessesInt >= 1))
            {
                throw new Exception();
            }
        }
        catch (Exception)
        {
            numGuessesInt = -1;
            Console.WriteLine("Error: Invalid Number of Guesses");
        }
    }

    //PICK WORD

    private static string PickWord()
    {
        return words[randomGen.Next(0, words.Count() - 1)];
    }


    // ****** Display word ******

    private static string displayWord(List<char> guessedCharacters, string word)
    {
        string returnedWord = "";
        if (guessedCharacters.Count == 0)
        {
            foreach (char letter in word)
            {
                returnedWord += "_ ";
            }
            return returnedWord;
        }
        foreach (char letter in word)
        {
            bool letterMatch = false;
            foreach (char character in guessedCharacters)
            {
                if (character == letter)
                {
                    returnedWord += character + " ";
                    letterMatch = true;
                    break;
                }
                else
                {
                    letterMatch = false;
                }
            }
            if (letterMatch == false)
            {
                returnedWord += "_ ";
            }
        }
        return returnedWord;
    }


    // ****** Guess letter ******

    static void guessLetter(List<char> guessedCharacters, string word, string wordToDisplay, ref int numGuessesLeft)
    {
        string letters = "";
        foreach (char letter in guessedCharacters)
        {
            letters += " " + letter;
        }
        Console.WriteLine("Guess a letter");
        Console.WriteLine("Guessed Letters: " + letters);
        Console.WriteLine("Guesses Left: " + numGuessesLeft);
        Console.WriteLine(wordToDisplay);
        string guess = Console.ReadLine();
        char guessedLetter = 'a';
        try
        {
            guessedLetter = Convert.ToChar(guess);
            if (!Char.IsLetter(guessedLetter))
            {
                throw new Exception();
            }
        }
        catch (Exception)
        {
            Console.WriteLine("Error: Invalid Letter Choice");
            //guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft);
        }
        bool repeat = false;
        for (int i = 0; i < guessedCharacters.Count; i++)
        {
            if (guessedCharacters[i] == guessedLetter)
            {
                Console.WriteLine("Error: Invalid Letter Choice");
                repeat = true;
                //guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft);
            }
        }
        if (repeat == false)
        {
            guessedCharacters.Add(guessedLetter);
            numGuessesLeft -= 1;
        }
    }

    // ****** Check to see if player wants to play again. ******

    static void checkIfPlayAgain()
    {
        Console.WriteLine("Would you like to play again? (y/n)");
        string playAgain = Console.ReadLine();
        if (playAgain == "n")
        {
            Environment.Exit(1);
        }
    }
}

单词表.cs

using System;
using System.Collections.Generic;

public class WordList : List<string>
{   
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从列表中选择随机单词? 的相关文章

随机推荐

  • 重用 Runnable 的最佳方式

    我有一个实现的类Runnable目前我正在使用 Executor 作为线程池来运行任务 将文档索引到 Lucene executor execute new LuceneDocIndexer doc writer 我的问题是我的 Runna
  • fancyBox 3 中的转换

    是否可以指定在 fancyBox 3 中使用哪个转换 我对 3 个转变感兴趣 打开幻灯片 画廊 在幻灯片之间导航 关闭幻灯片 图库 默认情况下 fancyBox 3 对不同类型的内容使用不同的过渡 a href img jpg img sr
  • Android 意图数据库

    是否有一个意图数据库可以搜索发布公共服务的应用程序 例如 我可能有一个关于可以应用于照片应用程序中的照片的过滤器的想法 但是我应该出于什么目的发布我的过滤器以便其他应用程序可以找到它并使用它 所以问题是是否有一个或多或少标准的意图数据库以及
  • 如何在容器化世界中独特地解决“流程”?

    这是一个普遍问题 但出于争论的目的 您可以假设我们有一组通过 AMQP 和 HTTP 组合进行通信的进程 有两种具体情况需要考虑 最简单的一个 Q 如果 A 向 B 发送消息 B 如何识别 A 发送回复的位置 A A 必须以某种方式告诉 B
  • 如何在悬停时更改父
  • 的样式
  • 我有一个 WordPress 网站 在我的本地主机上 它使用 ul 用于自定义菜单 我怎样才能改变CSS li 悬停时only如果它有一个 ul 子菜单 所有主菜单项都有一个边框半径 我想在当前项目 下面的服务 上删除它 例如 div cl
  • 我可以使用 Jython 运行 numpy 和 pandas

    我们有一些 Java 代码想要与计划用 Python 编写的新代码一起使用 因此我们对使用 Jython 感兴趣 然而 我们还想使用 numpy 和 pandas 库在此 Python 代码中进行复杂的统计分析 是否可以从 Jython 调
  • 提高 Android 位图上 getpixel() 和 setpixel() 的速度

    All 当我注意到有多慢之后getPixel and setPixel是 不确定是哪一个 猜想两者都不是涡轮增压的 我快速编码了一个容器Bitmap使用int 数组来处理位图操作 已经 它明显更快 但这还不够 请问您能建议如何进一步加快速度
  • 使用 Scala 中的可变参数

    我正在抓狂地试图弄清楚如何执行以下操作 def foo msf String o Any os Any println String format msf o List os 我必须用一个来声明该方法是有原因的o and an os Seq
  • 如何在 RXJS 中启动和停止可观察的间隔?

    我有一个非常简单的 timeInterval 可观察对象 我想在不断开订阅者连接的情况下启动 停止传输 无论可观察状态如何 都应该坐下来等待 有可能吗 如果可以的话怎么办 var source Rx Observable interval
  • 在 MS-Access 中插入带有日期时间的 SQL 命令

    我正在 MS Access 2007 中尝试以下查询 但在时间字段上失败 INSERT INTO LOG EMPLOYEECODE STATUSID LOCATIONID TIME DURATION SHIFTID LATECOMING E
  • 创建索引需要很长时间

    我在 MongoDB 中创建了一个集合 其中包含11446615文件 每个文档具有以下形式 id ObjectId 4e03dec7c3c365f574820835 httpReferer http www somewebsite pl a
  • wamp 本地主机上的 Amazon S3 SSL 错误

    我尝试在本地主机上使用 PHP Amazon S3 进行测试 但不断收到相同的错误 致命错误 未捕获异常 cURL Exception 消息为 cURL 资源 资源 ID 69 cURL 错误 SSL 证书问题 请验证 CA 证书没问题 详
  • java 的 System.getProperty("user.dir") 在 .NET 中的等价物是什么?

    我试图获取单元测试中文件的完整路径 该文件位于项目的文件夹中 我尝试使用 Directory GetCurrentDirectory 但这会返回我的测试正在运行的目录 我想要项目 或解决方案 的目录 而不必在其中进行硬编码 然后我可以附加文
  • angular2:如何将对象复制到另一个对象中

    请帮助我使用 Angular 2 将对象复制到另一个对象中 在 Angular 中 我使用 angular copy 将对象复制到旧对象的松散引用 但是 当我在 Angular 2 中使用相同的方法时 出现以下错误 错误 角度未定义 Sol
  • React Router v4 - 如何防止重定向循环?

    我想要实现的目标是拥有我的App如果状态的 uid 为 null 则组件重定向到 login 路由 重定向工作正常 如果 uid 为空 它将始终将您重定向到 login 但问题是一旦您进入 login 路线 它就不会停止重定向 抛出的错误是
  • 我应该使用什么标准来评估 Perl“应用程序服务器”(mod_perl 替代品)?

    简洁版本 我应该使用什么标准来评估 Perl 应用程序服务器 mod perl 替代品 的可能候选者 我们正在寻找某种框架 它允许重复执行各种 Perl 程序 作为服务 而不会产生以下成本 每次执行时重新启动 perl 解释器一次 每次执行
  • 如何在python 3中按本地语言对拉丁语进行排序?

    在很多情况下 用户的语言不是 latin 脚本 示例包括 希腊语 俄语 中文 在大多数情况下 排序是通过 首先对特殊字符和数字进行排序 虽然是当地语言的数字 其次是当地语言文字中的单词 最后是一般 utf 排序规则中的任何非本地字符 例如法
  • 如何在 python-igraph 中种子图生成器?

    有没有什么方法可以为使用 python igraph 生成的以下 Watts Strogatz 图提供种子 以便每次运行脚本时我都能得到相同的 SW 图实现 import igraph graph igraph Graph Watts St
  • 学习 VHDL 的最佳方法? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • 从列表中选择随机单词?

    我无法从另一个文件的列表中随机选择单词 事实上我什至无法让它选择任何单词 我不确定如何连接这两个文件 希望有人能帮忙 我是初学者 所以请尽可能简单地解释一下 我有 2 个文件 一个名为 program cs 另一个名为 WordList c