C# 从列表中随机选取单词?
我很难从另一个文件的列表中随机挑选一个单词。 事实上,我甚至不能选择任何一个词。也就是说,我不知道如何连接这两个文件。 希望有人能帮忙,我是初学者,所以请尽可能简单地解释:) 我有两个文件,一个叫做program.cs,另一个叫做WordList.cs 我将粘贴所有代码,但首先是我遇到问题的小剪报。我就是不知道如何正确地编写代码 下面是一个小部分,称为Pick word:C# 从列表中随机选取单词?,c#,list,C#,List,我很难从另一个文件的列表中随机挑选一个单词。 事实上,我甚至不能选择任何一个词。也就是说,我不知道如何连接这两个文件。 希望有人能帮忙,我是初学者,所以请尽可能简单地解释:) 我有两个文件,一个叫做program.cs,另一个叫做WordList.cs 我将粘贴所有代码,但首先是我遇到问题的小剪报。我就是不知道如何正确地编写代码 下面是一个小部分,称为Pick word: //PICK WORD static string pickWord() { strin
//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);
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.IO;
阶级刽子手
{
静态void Main(字符串[]参数)
{
Console.ForegroundColor=ConsoleColor.Red;
Console.Title=“C#Hangman”;
Console.WriteLine(“欢迎来到C#Hangman!”);
//菜单
int MenuChoice=0;
while(MenuChoice!=4)
{
Console.Write(“\n\t1)添加单词”);
Console.Write(“\n\t2)显示单词列表”);
Console.Write(“\n\t3)Play”);
控制台。写入(“\n\t4)退出\n\n”);
Console.Write(“\n\t选择1-4:”);//选择菜单项
MenuChoice=Convert.ToInt32(Console.ReadLine());
单词列表显示=新单词列表();
开关(MenuChoice)
{
案例1:
Console.Write(“\n\t输入一个单词\n\n”);
var insert=Console.ReadLine();
显示.AddWord(插入);
Console.Write(“\n\t单词列表\n\n”);
showing.ListOfWords();
打破
案例2:
Console.Write(“\n\t单词列表\n\n”);
showing.ListOfWords();
打破
案例3://跑步游戏
int numguesesint=-1;
而(numguesesint==-1)
{
/*设置用户猜测单词的次数*/
选取数值(参考数值);
}
/*随机选择一个单词*/
字符串字=pickWord();
/*创建将显示的字符列表*/
List guessedLetters=新列表();
布尔解算=假;
while(已解决==false)
{
/*根据用户的正确猜测向用户显示字符串。
*如果没有任何内容是正确的,字符串将返回“\uu\uu”*/
string wordToDisplay=displayWord(猜字母、单词);
/*如果返回的字符串包含“\”字符,则所有
*正确的字母没有被猜到,所以检查用户
*已丢失,请检查numguessleft是否小于1*/
如果(!wordToDisplay.Contains(“”))
{
已解决=正确;
Console.WriteLine(“你赢了!单词是“+单词”);
/*检查用户是否想要再次播放。如果他们想要,
*然后“已求解”设置为true,将结束循环,
*否则,再次选中播放将关闭程序*/
再次选中复选框();
}
否则,如果(numguesesint我已经对你的代码做了一些更改。代码现在可以工作了,但还远远不够完美。
您的解决方案有两个文件Program.cs
和Wordlist.cs
,如下所示
Program.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);
}
}
}
using System;
using System.Collections.Generic;
public class WordList : List<string>
{
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.IO;
公共级刽子手
{
/*
*关于代码的一些注释:
*对方法和字段使用命名约定,即方法名称以大写字母开头
*在方法声明中为方法使用修饰符,即private、public和protected
*如果在多个方法上使用变量,则将其设为私有变量
*最后:读一本关于c语言的书#
*
*/
私有静态词表词;
私有静态随机生成=新随机();
公共静态void Main(字符串[]args)
{
Console.ForegroundColor=ConsoleColor.Red;
Console.Title=“C#Hangman”;
Console.WriteLine(“欢迎来到C#Hangman!”);
初始化wordlist();
//菜单
int MenuChoice=0;
while(MenuChoice!=4)
{
Console.Write(“\n\t1)添加单词”);
Console.Write(“\n\t2)显示单词列表”);
Console.Write(“\n\t3)Play”);
控制台。写入(“\n\t4)退出\n\n”);
Console.Write(“\n\t选择1-4:”);//选择菜单项
MenuChoice=Convert.ToInt32(Console.ReadLine());
开关(MenuChoice)
{
案例1:
Console.Write(“\n\t输入一个单词\n\n”);
var insert=Console.ReadLine();
添加(插入)字样;
Console.Write(“\n\t单词列表\n\n”);
foreach(字中的字符串w)//显示以供验证
控制台写入线(w);
打破
案例2:
Console.Write(“\n\t单词列表\n\n”);
foreach(字中的字符串w)//显示以供验证
控制台写入线(w);
打破
案例3://跑步游戏
int numguesesint=-1;
而(numguesesint==-1)
{
/*设置用户猜测单词的次数*/
选取数值(参考数值);
}
/*随机选择一个单词*/
using System;
using System.Collections.Generic;
public class WordList : List<string>
{
}
private void PopulateTheWordList()
{
Console.Write("\n\tAdd a word\n\n");
WordList.Add(Console.ReadLine());
}
private string PickWord()
{
Random ran = new Random();
return WordList[ran.Next(0, WordList.Count)];
}
static List<string> WordList = new List<string>();
static class WordList
{
static List<string> words = new List<string>();
public static 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 static List<string> GetWords()
{
return words;
}
public static void AddWord(string value)
{
words.Add(value);
}
}
switch (MenuChoice)
{
case 1:
Console.Write("\n\tAdd a word\n\n");
var insert = Console.ReadLine();
WordList.AddWord(insert);
Console.Write("\n\tList of words\n\n");
WordList.ListOfWords();
break;
case 2:
Console.Write("\n\tList of words\n\n");
WordList.ListOfWords();
break;
....
static string pickWord()
{
string returnword = "";
Random randomGen = new Random();
returnword = WordList.GetWords()[randomGen.Next(0, WordList.GetWords().Count() - 1)];
return returnword;
}
static class WordList
{
static string filePath = @"C:\temp\Word.txt";
static List<string> words = new List<string>();
private static void CheckFile()
{
//Makes sure our base words are saved to the file
if (!File.Exists(@"C:\temp\Word.txt"))
{
using (TextWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("test");
writer.WriteLine("dog");
writer.WriteLine("shit");
}
}
}
public static void ListOfWords()
{
CheckFile();
words.Clear();
using (TextReader file = new StreamReader(filePath))
{
char[] delineators = new char[] { '\r', '\n' };
string[] tempWords = file.ReadToEnd().Split(delineators, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in tempWords)
{
words.Add(line);
}
}
foreach (string word in words) // Display for verification
{
Console.WriteLine(word);
}
}
public static List<string> GetWords()
{
return words;
}
public static void AddWord(string value)
{
CheckFile();
using (TextWriter writer = new StreamWriter(filePath,true ))
{
writer.WriteLine(value);
}
}
}