Check ReadKey only for letters (alphabet) in string - c#

i am doing game "Hangman" but i have a problem. I am using ReadKey to find the guess of player, but he can use even numbers or buttons like "Enter" etc. I want to stop this, but i don't know how :/ Can you help me please? I want control, if in result of ReadKey is letter from alphabet or no (but it must be in "string" format, cuz i am working later with string). Thank you very much guys, here is my code :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hangman
{
class MainClass
{
/// <summary>
/// Hra Oběšenec
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
Console.WriteLine("Vítejte ve hře Oběšenec!");
//List slov, které bude hráč hádat
string[] words = new string[5];
words[0] = "car";
words[1] = "school";
words[2] = "apple";
words[3] = "orange";
words[4] = "xamarin";
//Získávám délku slova (hádaného slova)
for (int X = 0; X < words.Length; X++)
{
string guessWord = words[X];
short lifes = 5;
short guessedLetters = 0;
char GuessingLetter;
char[] lettersOfWord = new char[guessWord.Length];
//
for (int I = 0; I < guessWord.Length; I++)
{
//Length of word is changing to *
lettersOfWord[I] = '*';
}
bool InGame = true;
//When this while is true, the game is still going, when it will be false, the game will end
while (InGame)
{
//Ochrana proti špatnému inputu
try
{
Console.WriteLine(lettersOfWord);
Console.WriteLine("Stiskněte klávesu. Životy:" + lifes);
ConsoleKeyInfo result_guess = Console.ReadKey(true);
string result = result_guess.KeyChar.ToString();
if (result.Length == 0)
{
continue;
}
//Hráč hádá slovo
GuessingLetter = result[0];
lifes--;
for (int I = 0; I < lettersOfWord.Length; I++)
{
if (lettersOfWord[I] == '*')
{
//Pokud hráč uhádne písmenko ve slově
if (guessWord[I] == GuessingLetter)
{
lettersOfWord[I] = GuessingLetter;
guessedLetters++;
lifes++;
Console.WriteLine("Správně!");
}
}
}
}
catch (Exception e)
{
Console.WriteLine("Nastala neočekávaná chyba!" + e);
}
//Pokud prohraje(promrhá všechny pokusy) hra skončí, avšak pokud slovo uhádne (a zůstane alespoň jeden život) vyhrál hru
if (lifes== 0 || guessedLetters == guessWord.Length)
{
//Konec hry
InGame = false;
if (lifes == 0)
{
Console.WriteLine("Smůla prohrál jsi!");
Console.ReadKey();
break;
}
else
{
//Vítězství nad levlem
Console.WriteLine("Uhodnul jsi celé slovo! Gratuluji!!");
}
}
}
}
}
}
}

Check if the keychar is a letter with the IsLetter method and keep asking for letters if it doesn't. Something like this:
private char GetLetter()
{
while (true)
{
Console.WriteLine("Please input a letter.");
var character = Console.ReadKey().KeyChar;
if (char.IsLetter(character))
return character;
}
}

Related

How do I remove the input halt to automate the input?

So basically the program does what it is supposed to do. The two patterns have to be split with an open line. But I did something wrong now the input wont go in smoothly. I have to press enter a couple of times. The Expected input is:
...........*........
....*.....*.........
.........*..*...*...
*..*..*......***....
..*.....*...........
.*..................
.......*.........*.*
....................
.....*............*.
..........
.*.**.*...
*....*.*.*
..........
..*.....*.
and Output should be
...................*
.................**.
..............***...
........******......
......**............
.....*..............
..***...............
....................
**..................
..........
......****
..****....
..........
**........
But mine looks like this
...........*........
....*.....*.........
.........*..*...*...
*..*..*......***....
..*.....*...........
.*..................
.......*.........*.*
....................
.....*............*.
...................*
.................**.
..............***...
........******......
......**............
.....*..............
..***...............
....................
**..................
..........
.*.**.*...
*....*.*.*
..........
..*.....*.
......****
..****....
..........
**........
I have to press enter a couple of times to get this.
My Code looks like this
using System;
using System.Runtime.CompilerServices;
using Microsoft.VisualBasic;
using System.Collections.Generic;
using System.Linq;
public class Program
{
static void defragDisk(Queue<string> diskLine) // Method that will move all the Starsto the right
{
int lnLength = 0;
int iIndex = 0;
int iStars = 0;
int iTotalStars = 0;
while (diskLine.Count > 0)
{
var line = diskLine.Dequeue();
lnLength = line.Length;
iIndex = lnLength - 1 - iTotalStars;
iStars = line.Count(x => x == '*');
iTotalStars += iStars;
var rangeFrom = iIndex - iStars + 1;
var availableIndexes = Enumerable.Range(rangeFrom, iStars).ToDictionary(x => x);
for (int i = 0; i < lnLength; i++)
{
if (availableIndexes.ContainsKey(i))
Console.Write("*");
else
Console.Write(".");
}
Console.Write("\n");
}
}
static void populateQueue(Queue<string> diskLine) // I am using a queue as the sizes can vary without indication
{
bool bCompleted = false;
while (!bCompleted)
{
var line = Console.ReadLine();
if (line == "")
{
bCompleted = true;
break;
}
else
{
diskLine.Enqueue(line);
}
}
}
public static void Main()
{
bool bCompleted = false;
Queue<string> diskLine = new Queue<string>();
while (!bCompleted)
{
populateQueue(diskLine);
defragDisk(diskLine);
diskLine.Clear();
if (Console.ReadLine() == "")
{
bCompleted = true;
break;
}
}
}
}

In what context does "ConsoleInput" miss? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
using System;
namespace suma_cifrelor_unui_nr
{
class Program
{
static void Main(string[] args)
{
int n;
int suma = 0;
Console.Write("Introdu numarul ");
Console.Write("\n");
n = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
while (n > 0)
{
suma = suma + n % 10;
n = n / 10;
}
Console.Write("Suma cifrelor este ==");
Console.Write(suma);
}
}
}
When I m trying to run this code the following error pops up :
"The name 'ConsoleInput' does not exist in the current context"
enter image description here
As expected ConsoleInput is a helper class so I did some google search,
And that's land me to convert code from c++ to c# and i found that words "with the 'ConsoleInput' helper class added by our converter", so try to check google before ask next time.
internal static class ConsoleInput
{
private static bool goodLastRead = false;
internal static bool LastReadWasGood
{
get
{
return goodLastRead;
}
}
internal static string ReadToWhiteSpace(bool skipLeadingWhiteSpace)
{
string input = "";
char nextChar;
while (char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
//accumulate leading white space if skipLeadingWhiteSpace is false:
if (!skipLeadingWhiteSpace)
input += nextChar;
}
//the first non white space character:
input += nextChar;
//accumulate characters until white space is reached:
while (!char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
input += nextChar;
}
goodLastRead = input.Length > 0;
return input;
}
internal static string ScanfRead(string unwantedSequence = null, int maxFieldLength = -1)
{
string input = "";
char nextChar;
if (unwantedSequence != null)
{
nextChar = '\0';
for (int charIndex = 0; charIndex < unwantedSequence.Length; charIndex++)
{
if (char.IsWhiteSpace(unwantedSequence[charIndex]))
{
//ignore all subsequent white space:
while (char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
}
}
else
{
//ensure each character matches the expected character in the sequence:
nextChar = (char)System.Console.Read();
if (nextChar != unwantedSequence[charIndex])
return null;
}
}
input = nextChar.ToString();
if (maxFieldLength == 1)
return input;
}
while (!char.IsWhiteSpace(nextChar = (char)System.Console.Read()))
{
input += nextChar;
if (maxFieldLength == input.Length)
return input;
}
return input;
}
}
using System;
namespace suma_cifrelor_unui_nr
{
internal static class ConsoleInput
{
static void Main(string[] args)
{
int n;
int suma = 0;
Console.Write("Introdu numarul ");
Console.Write("\n");
n = int.Parse(ConsoleInput.ReadToWhiteSpace(true));
while (n > 0)
{
suma = suma + n % 10;
n = n / 10;
}
Console.Write("Suma cifrelor este ==");
Console.Write(suma);
}
private static ReadOnlySpan<char> ReadToWhiteSpace(bool v)
{
throw new NotImplementedException();
}
}
}

My values are changing by changing the position of methods

I'm working on c# to make a program for checking vowels,consonants,characters,words and number of sentences using method for each)
. My program is working good but my
problem is changing the places of method where I applied them chance the values.
Here is the program
on method characters I use the method words (whick basically counts the spaces ) same for Consonants
the problem is I need to apply the methods on main accourding to the order I have created them "Words>Sentences>Vowels>Characters>COnsonants"
If I chnage the order I get the wrong answer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Task_Raza_Class
{
class Program
{
static void Main(string[] args)
{
string state;
Console.WriteLine("Enter an Statement / Sentance \nPress Enter to Continue..");
state = Console.ReadLine();
raza task = new raza();
// Words>Sentances>Vowels>Characters>COnsonents
Console.WriteLine("Words"+task.words(state));
Console.WriteLine("No of Sentances"+task.tances(state));
Console.WriteLine("Vowels"+task.vowels(state));
Console.WriteLine("Characters"+task.characters(state));
Console.WriteLine("Consonents"+task.consonents(state));
Console.ReadKey();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Task_Raza_Class
{
class raza
{
public int cw , cv , cc , cp , cchar ;
public raza()
{
cw = 1; cv = cc = cp = cchar = 0;
}
public int words(string state)
{
char[] s_arr = new char[200];
s_arr = state.ToCharArray();
for (int i = 0; i < s_arr.Length; i++)
{
if(s_arr[i]==' ')
{
cw++;
}
}
return (cw);
}
public int tances(string state)
{
char[] s_arr = new char[200];
s_arr = state.ToCharArray();
for (int i = 0; i < s_arr.Length; i++)
{
if (s_arr[i] == '.')
{
cp++;
}
}
return (cp);
}
public int vowels(string state)
{
char[] s_arr = new char[200];
s_arr = state.ToCharArray();
for (int i = 0; i < s_arr.Length; i++)
{
if (s_arr[i] == 'a' || s_arr[i] == 'A' || s_arr[i] == 'e' || s_arr[i] == 'E' || s_arr[i] == 'i' || s_arr[i] == 'I' || s_arr[i] == 'o' || s_arr[i] == 'O' || s_arr[i] == 'u' || s_arr[i] == 'U')
{
cv++;
}
}
return (cv);
}
public int characters(string state)
{
char[] s_arr = new char[200];
s_arr = state.ToCharArray();
cchar = s_arr.Lenght - words(state)-1
return (cchar);
}
public int consonents(string state)
{
char[] s_arr = new char[200];
s_arr = state.ToCharArray();
cc = characters(state)-vowels(state);
return (cc);
}
}
}
The problem is cchar and cv are member fields, whose values are maintained between calls. Because consonents calls characters and vowels, those two functions get called twice and on the 2nd time will have whatever value was left over from the first call. There's no need for any member fields in your raza class - they can all be local variables. Alternatively, you could design raza to accept the state parameter in the constructor, then call characters and consonents and change vowels to reuse the values from cchar and cv.
(BTW the correct English spelling is "consonants" and "sentences")

How to count the number of "correct" and "incorrect" responses

I'm new to coding and am creating a windows form application in C#. I was having difficulties figuring out how to track the number of correct and incorrect responses. When a button is clicked, if the response is correct a label says correct. I want a different label to count the amount of times it says correct and incorrect. Here's what I was thinking but didn't work.
int add = 0;
add = int.Parse(correct.Text);
if (label1.Text == "Correct")
{
correct.Text = add++;
}
else
incorrect.text = add++;
correct and incorrect are names of my label.
Here's my button click event, there are many alike.
private void G_Click(object sender, EventArgs e)
{
if (go.Visible == true)
{
go.Visible = false;
Random rnd = new Random();
int y = rnd.Next(1, 7);
if (y == 1)
{
eo.Visible = true;
}
if (y == 2)
{
ao.Visible = true;
}
if (y == 4)
{
dd.Visible = true;
}
if (y == 5)
{
go.Visible = true;
}
if (y == 6)
{
eeo.Visible = true;
}
timer1.Start();
label1.Text = "Correct";
}
else
{
label1.Text = "Incorrect";
}
private int correctCount = 0;
private int incorrectCount = 0;
if (label1.Text = "Correct";)
{
correctCount++;
correct.Text = correctCount.ToString();
}
else
{
incorrectCount++;
incorrect.Text = incorrectCount.ToString();
}
The immediate problem is that the type of the Text property is string, not int - you have to set it to text, not a number. Fortunately, you can just call ToString on an int to get a string representation. However, I'd suggest there are other things to change too.
I would strongly suggest that you keep separate counters as variables. While you could keep parsing your labels, it's simpler for them to be purely output. So you might have:
// Fields
private int correctCount = 0;
private int incorrectCount = 0;
...
// Wherever your code is
if (correctAnswer)
{
correctCount++;
correct.Text = correctCount.ToString();
}
else
{
incorrectCount++;
incorrect.Text = incorrectCount.ToString();
}
Note the correctAnswer condition here - we don't know what's setting the text of label1, but I'd suggest that that's the right place to also change the correct/incorrect counters, from the same condition. Again, treat label1 just as output, rather than as a feedback system.
class fields = variables that are declared outside of a method and directly inside a class
local variables = variables that are declared inside of a method
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace deleteMe
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int correctCount = 0; // field
private int incorrectCount = 0; // field
private void G_Click(object sender, EventArgs e)
{
if (go.Visible == true)
{
go.Visible = false;
Random rnd = new Random();
int y = rnd.Next(1, 7); // local variable
if (y == 1)
{
eo.Visible = true;
}
if (y == 2)
{
ao.Visible = true;
}
if (y == 4)
{
dd.Visible = true;
}
if (y == 5)
{
go.Visible = true;
}
if (y == 6)
{
eeo.Visible = true;
}
timer1.Start();
incorrect.Text = "Correct";
}
else
{
incorrect.Text = "Incorrect";
}
if (label1.Text = "Correct")
{
correctCount++;
correct.Text = correctCount.ToString();
}
else
{
incorrectCount++;
incorrect.Text = incorrectCount.ToString();
}
}
}
}
== equality. (for comparing 2 values)
= assign a value. (for initialize a variable or field)

Pick random word from list?

I´m having trouble picking a random word from a list in another file.
Actually I can´t even get it to choose any word. I´m not sure how to connect the 2 files so to say.
Hoping someone can help out, I´m a beginner so please explain as easy as possible:)
I have 2 files, one is called program.cs and the other is called WordList.cs
I´m gonna paste all my code but first the little snip that I´m having problem with. I just can´t figure out how to write the code correct.
Here is the little part which is called 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;
}
And here is all the code in 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);
}
}
}
And here is the code for 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);
}
}
I have made some changes to your code. The code works now but is far from perfect.
Your solution has two files Program.cs and Wordlist.cs, which looks like this
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);
}
}
}
Wordlist.cs
using System;
using System.Collections.Generic;
public class WordList : List<string>
{
}
Here is the very simple solution:
Populate your list just one time, or when ever you add any word, call this method. Code:
private void PopulateTheWordList()
{
Console.Write("\n\tAdd a word\n\n");
WordList.Add(Console.ReadLine());
}
Now just call this method to get random words:
private string PickWord()
{
Random ran = new Random();
return WordList[ran.Next(0, WordList.Count)];
}
If you need to create List of words in another class, then use keyword static:
static List<string> WordList = new List<string>();
Now you can call it by just writing the class name, like YourClassName.WordList
Try creating a Static Class and add a method for returning your List, you will then be able to access your wordlist.
example:
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);
}
}
You would then change your switch statement to look something like this.
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;
....
and your pickWord Method would look like this:
static string pickWord()
{
string returnword = "";
Random randomGen = new Random();
returnword = WordList.GetWords()[randomGen.Next(0, WordList.GetWords().Count() - 1)];
return returnword;
}
I modified your Wordlist class so that it can use a file to maintain your Words between uses of your program, just incase that is what was being asked of you.
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);
}
}
}

Categories

Resources