My apologies for asking yet another question, but I am struggling to get the desired output for my hangman program. When the user finds a correct letter, I would like it to display a space between letters and underscores; I can only get it to output a space after a letter and not between as desired. Also, when the secretword is guessed and the user wins, I would like the secret word to be output with spaces between the letters (eg. M A R I O). I have tried using +" " in various places, but still struggling to get the desired output. Any help would be greatly appreciated.
My code is as follows...
static void Main()
{
Console.Title = ("Hangman Game");
string[] secretWords = {
"mario", /*"sonic", "thelegendofzelda", "donkeykong", "luigi",
"peach", "link", "laracroft", "bowser", "kratos",
"playstation", "nintendo", "tetris", "grandtheftauto",
"finalfantasy", "thelastofus", "ghostoftsushima", "horizonzerodawn",
"halo", "forza", "crashbandicoot", "worldofwarcraft", "callofduty",
"fortnite", "animalcrossing", "doom", "metalgearsolid", "minecraft",
"residentevil", "pacman", "spaceinvaders", "asteroids",
"streetfighter", "mortalkombat", "supermariokart", "pokemon",
"bioshock", "tombraider"*/
};
Random R = new Random();
string secretword = secretWords[R.Next(secretWords.Length)];
List<string> letterGuessed = new List<string>();
int live = 5;
Console.WriteLine("Welcome To Hangman!");
Console.WriteLine("Enter a letter to guess for a {0} Letter Word", secretword.Length);
Console.WriteLine("You Have {0} Lives remaining \n", live);
Isletter(secretword, letterGuessed);
while (live > 0)
{
string input = Console.ReadLine();
if (letterGuessed.Contains(input))
{
Console.WriteLine("You Entered Letter [{0}] Already", input);
Console.WriteLine("Try a Different Letter \n");
continue;
}
letterGuessed.Add(input);
if (IsWord(secretword, letterGuessed))
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(secretword);
Console.WriteLine("Congratulations!");
break;
}
else if (secretword.Contains(input))
{
Console.WriteLine("Good Entry\n");
string letters = Isletter(secretword, letterGuessed);
Console.Write(letters);
Console.WriteLine("\n");
}
else
{
Console.WriteLine("That Letter Is Not In My Word");
live -= 1;
Console.WriteLine("You Have {0} Lives Remaining", live);
}
Console.WriteLine();
if (live == 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Game Over! \nMy Secret Word is [ {0} ]", secretword);
break;
}
}
Console.ReadKey();
}
static bool IsWord(string secretword, List<string> letterGuessed)
{
bool word = false;
for (int i = 0; i < secretword.Length; i++)
{
string c = Convert.ToString(secretword[i]);
if (letterGuessed.Contains(c))
{
word = true;
}
else
{
return word = false;
}
}
return word;
}
static string Isletter(string secretword, List<string> letterGuessed)
{
string correctletters = "";
for (int i = 0; i < secretword.Length; i++)
{
string c = Convert.ToString(secretword[i]);
if (letterGuessed.Contains(c))
{
correctletters += c;
}
else
{
correctletters += "_ ";
}
}
return correctletters;
}
}
}
Console.WriteLine(string.Join(" ", secretword.ToUpper().ToCharArray()));
worked as expected. Many thanks #41686d6564
Related
{
bool stayInLoop = true;
while(stayInLoop)
{
Console.WriteLine("Enter Yor Number");
var PlusA = Console.ReadLine();
Console.WriteLine("Enter Yor Number");
var PlusB = Console.ReadLine();
if(PlusA == ';')
{
stayInLoop = false;
break;
}
else if(PlusB == ';')
{
stayInLoop = false;
break;
}
else
{
Console.WriteLine("Answer =");
Console.WriteLine(PlusA + PlusB);
}
}
}
I want to make a plus calculator, I want to let the user type more then 2 numbers, keep asking for PlusC, PlusD, until they type the symbol ; .
For example the user numbers in PlusA PlusB PlusC and in PlusD, he/she type ; so it should print PlusA + PlusB + PlusC
If he type a number in PlusD, it should ask for PlusE, until he/she type ;, it should sum up all the number before
And I want to auto the process, The program will ask for PlusA to PlusZ itself instead of int it my own, how to do that? (I know I am not saying it clearly, coz i can't find better words)
You want to add numbers until the user enters ;. You should use loops for that. Here's the complete solution that uses a for loop:
switch(exp)
{
case "+":
{
var sum = 0;
for(;;)
{
Console.WriteLine("Enter Yor Number");
var line = Console.ReadLine();
if (line == ";") break;
sum += Convert.ToInt32(line);
}
Console.WriteLine(sum);
break;
}
}
Here we repeat the part inside the loop over and over, accumulating entered numbers into sum variable until the user enters ; - that's when we end the loop with break.
Use a while loop:
switch(exp)
{
case "+":
int sum = 0;
string input = "";
do
{
Console.WriteLine("Enter your number:");
input = Console.ReadLine();
if (input != ";")
sum += int.Parse(input);
} while (input != ";");
Console.WriteLine("Answer =" + sum);
break;
}
You are having problems because you should iterate the code until your exit/end condition is met using the while statement.
switch(exp)
{
case "+":
int mySum = 0;
string userInput = "";
while(userInput != ";")
{
Console.WriteLine("Enter number to add (';' to end the sum):");
userInput = Console.ReadLine();
if (userInput != ";")
{
// Would be interesting checking if entered really is an integer, for example Int32.TyParse()
mySum = mySum + Convert.ToInt32(userInput);
}
}
Console.WriteLine("Answer =" + mySum.ToString());
break;
}
Thankyou for your reply, but is there any way to auto the process, The program will ask for PlusA to PlusZ itself instead of int it my own
bool stayInLoop = true;
while(stayInLoop)
Console.WriteLine("Enter Yor Number");
var PlusA = Console.ReadLine();
Console.WriteLine("Enter Yor Number");
var PlusB = Console.ReadLine();
if(PlusA == ';')
{
stayInLoop = false;
break;
}
else if(PlusB == ';')
{
stayInLoop = false;
break;
}
else
{
Console.WriteLine("Answer =");
Console.WriteLine(PlusA + PlusB);
}
}
and when I run this, it run out 'error CS0019' and 'error CS0139'
What you're looking for is a while() loop.
example:
bool stayInLoop = true;
while(stayInLoop) // basically means (stayInLoop == true)
{
var text = Console.ReadLine();
if(text == ';')
{
stayInLoop = false;
break; // break will stop the loop, but you can also change the variable to false to break the loop.
}
}
I am trying to make a simple program where the user tries to guess numbers between 1 and 25 until they guess the right one. I am trying to make the input received as an integer so that I can use greater than and less than signs. When I use the command I found on another answer in this forum, it says that there is an error. What am I doing wrong?
int score = 0;
int add = 1;
while (add == 1)
{
Console.WriteLine("Guess A Number Between 1 and 25");
string input = int.Parse(Console.ReadLine());
score += add;
if (input == 18)
{
Console.WriteLine("You Did It!");
Console.WriteLine("Your Score was " + score);
break;
}
else if (input > 25)
{
Console.WriteLine("Error.");
}
else
{
Console.WriteLine("Try Again. Score: " + score);
}
}
Store their response from ReadLine() as a String, then use int.TryParse() to attempt to convert that String to an Integer. The code below is written to show you all the possible states that could occur using if else blocks. I've also used a bool to indicate when the game should end instead of using a break statement:
static void Main(string[] args)
{
int number;
string input;
bool guessed = false;
int score = 0;
while (!guessed)
{
Console.Write("Guess A Number Between 1 and 25: ");
input = Console.ReadLine();
if (int.TryParse(input, out number))
{
if(number>=1 && number<=25)
{
score++;
if (number == 18)
{
guessed = true;
Console.WriteLine("You Did It!");
Console.WriteLine("Your Score was " + score);
}
else
{
Console.WriteLine("Try Again. Score: " + score);
}
}
else
{
Console.WriteLine("Number must be between 1 and 25!");
}
}
else
{
Console.WriteLine("That's not a number!");
}
Console.WriteLine();
}
Console.Write("Press Enter to Quit.");
Console.ReadLine();
}
I am working on a simple code that asks for the name, age, and gender of at most 5 patients. After each patient, it should ask to input another patient or return to main menu. Once 5 have been input into an array, there should be a prompt to the user that the array is full.
My problem is the code asks for name,age and gender 5 times upfront, and does not give any indication the array is full. How would I change the code to reflect that and still save the inputs? (Code below).
class MainClass
{
enum Gender { female, male }
struct Record
{
public string _Name;
public int _Age;
public Gender _Gender;
}
public static void Main(string[] args)
{
//title
Console.Write("\t\t\t\t\tPatient Records\n");
string selection = "";
Record[] patients = new Record[5];
GetRecords(patients);
Console.Write("a. Add\n d.Display\ns. Stats\nq. Quit");
Console.Write("Your selection: ");
selection = Console.ReadLine();
switch (selection)
{
case "a":
GetRecords(patients);
break;
case "d":
break;
case "s":
Stats(patients);
break;
case "q":
//CUtility.Pause();
break;
}
}
static void GetRecords(Record[] patient_rec)
{
for (int i = 0; i < patient_rec.Length; i++)
{
Console.Write("Enter your age: ");
int.TryParse(Console.ReadLine(), out patient_rec[i]._Age);
Console.Write("Enter your name: ");
patient_rec[i]._Name = Console.ReadLine();
Console.Write("Enter your gender (female or male): ");
Gender.TryParse(Console.ReadLine(), out patient_rec[i]._Gender);
}
}
static void Stats(Record[]patient_rec)
{
}
}
I would suggest trying to make your code a little easier to read - and more robust.
Try this:
static void GetRecords(Record[] patient_rec)
{
for (int i = 0; i < patient_rec.Length; i++)
{
Console.WriteLine("Record {0} of {1} entry", i + 1, patient_rec.Length);
patient_rec[i] = new Record()
{
_Age = AskInteger("Enter your age: "),
_Name = AskString("Enter your name: "),
_Gender = AskGender("Enter your gender (female or male): "),
};
string ask = "";
while (string.IsNullOrEmpty(ask) || (ask.ToLower()[0] != 'y' && ask.ToLower()[0] != 'n'))
{
Console.WriteLine("Continue? yes or no (then hit enter)");
ask = Console.ReadLine();
}
if (ask.ToLower()[0] == 'y')
{
continue;
}
break;
}
Console.WriteLine("Thank you. Input completed.");
}
To make this work you need these three input functions:
private static int AskInteger(string message)
{
int result;
Console.WriteLine(message);
string input = Console.ReadLine();
while (!int.TryParse(input, out result))
{
Console.WriteLine("Invalid input.");
Console.WriteLine(message);
input = Console.ReadLine();
}
return result;
}
private static string AskString(string message)
{
Console.WriteLine(message);
string input = Console.ReadLine();
while (string.IsNullOrWhiteSpace(input))
{
Console.WriteLine("Invalid input.");
Console.WriteLine(message);
input = Console.ReadLine();
}
return input;
}
private static Gender AskGender(string message)
{
Gender result;
Console.WriteLine(message);
string input = Console.ReadLine();
while (!Gender.TryParse(input, out result))
{
Console.WriteLine("Invalid input.");
Console.WriteLine(message);
input = Console.ReadLine();
}
return result;
}
Your loop is only set to go to the size of the array, so logically you could show a message after the loop (this will get hit when the loop finishes).
If you were controlling your array access in a while loop then just compare your indexer i to the length of the array (patient_rec.Length), if it equals or exceeds the length then show the message.
I would do it in a simpler way:
enum Gender { female, male }
struct Record
{
public string _Name;
public int _Age;
public Gender _Gender;
}
static void Main(string[] args)
{
//title
Console.Write("\t\t\t\t\tPatient Records\n");
IList<Record> patients = GetRecords(5);
SchedulePatients(patients);
}
static void SchedulePatients(IList<Record> patients)
{
Console.Write("a. Add\n d.Display\ns. Stats\nq. Quit");
Console.Write("Your selection: ");
string selection = Console.ReadLine();
switch (selection)
{
case "a":
patients.Add(GetRecord());
SchedulePatients(patients);
break;
case "d":
break;
case "s":
Stats(patients);
break;
case "q":
//CUtility.Pause();
break;
}
}
static IList<Record> GetRecords(int amount)
{
IList<Record> patients = new List<Record>();
for (int i = 0; i < amount; i++)
{
patients.Add(GetRecord());
}
return patients;
}
static Record GetRecord()
{
Record patient = new Record();
Console.Write("Enter your age: ");
int.TryParse(Console.ReadLine(), out patient._Age);
Console.Write("Enter your name: ");
patient._Name = Console.ReadLine();
Console.Write("Enter your gender (female or male): ");
Enum.TryParse(Console.ReadLine(), out patient._Gender);
return patient;
}
static void Stats(IList<Record> patients)
{
foreach (var patient in patients)
{
Console.WriteLine(string.Concat("Name: ", patient._Name, " Age: ", patient._Age, " Gender: ", patient._Gender));
}
Console.ReadLine();
}
}
If you would like to meet the requirements with the smallest change possible, you just need to add the bit about prompting the user.
static void GetRecords(Record[] patient_rec)
{
for (int i = 0; i < patient_rec.Length; i++)
{
Console.Write("Enter your age: ");
int.TryParse(Console.ReadLine(), out patient_rec[i]._Age);
Console.Write("Enter your name: ");
patient_rec[i]._Name = Console.ReadLine();
Console.Write("Enter your gender (female or male): ");
Gender.TryParse(Console.ReadLine(), out patient_rec[i]._Gender);
Console.Write("Enter another (Y/N)? ");
var s = Console.ReadLine();
if (s.ToUpper() != "Y") return;
}
Console.WriteLine("You've entered the maximum number of records.");
}
This is a simple begginer program with setter and getter concept
now i have to make it to first enter user name and password to get welcomed
and IF I ENTER WRONG INFO IT SHOULD DISPLAY INVALID AND 5 TRIES LEFT THEN if i again enter wrong info it should display 4 tries left and so on and finally when all tries are over it should hang the program or lock the screen or so
using System;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
}
else
{
Console.Clear();
Console.WriteLine("Invalid");
Console.WriteLine("\n \n \n To try again enter y");
int n = 5;
string yes = Console.ReadLine();
if (yes == "y")
{
while (n >= 1)
{
Console.Write(n + " Tries left");
goto label1;
n = --n;
}
}
}
Console.ReadKey();
}
}
class demo
{
private string name, pass;
public void setName(string name)
{
this.name = name;
}
public string getName()
{
return name;
}
public void setPass(string pass)
{
this.pass = pass;
}
public string getPass()
{
return pass;
}
}
}
Please suggest a simple begginers code to make the loop work and make the count down
A while loop should suffice. Using a boolean to detect successful password entry.
When entered, it will break out of the loop.
invalid attempts will decrement the AttemptsLeft int.
Note: I haven't tried this in Visual Studio, the logic should be sound, but I recommend debugging and stepping through it to test if it meets your criteria.
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
bool SuccessfulPassword = false;
int AttemptsLeft = 5;
while(!SuccessfulPassword && AttemptsLeft > 0){
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
SuccessfulPassword = true;
}
}
else
{
AttemptsLeft--;
Console.Clear();
Console.WriteLine("Invalid");
Console.WriteLine("\n \n \n To try again enter y");
int n = 5;
string yes = Console.ReadLine();
if (yes == "y")
{
Console.Write(AttemptsLeft + " Tries left");
}
}
Console.ReadKey();
}
}
try this updated main method:
static void Main(string[] args)
{
demo obj = new demo();
int n = 5;
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
//Console.Clear();
label1:
Console.WriteLine("\n");
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit" && obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
else
{
//Console.Clear();
if (n < 1)
{
//Add ur screenlock n hang prog code
Console.Clear();
Console.WriteLine("ScreenLock");
}
else
{
Console.WriteLine("\n Invalid");
Console.WriteLine("\n To try again enter y");
string yes = Console.ReadLine();
Console.WriteLine("\n");
if (yes == "y")
{
while (n >= 1)
{
Console.Write(n + " Tries left");
n = --n;
goto label1;
}
}
}
}
Console.ReadKey();
}
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
boolean successful = false;
int32 tries = 5;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Do
{
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
successful = true;
}
}
if (!successful)
{
tries--;
Console.Clear();
Console.WriteLine("Invalid");
if (tries > 1)
{
Console.WriteLine("Have " + tries + " attempts left");
}
ElseIf (tries == 1)
{
Console.WriteLine("Have only one more attempt left");
}
Else
{
Console.WriteLine("Maximum number of tries exceed");
Console.WriteLine("Goodbye");
}
}
} While(!successful && Tries > 0);
}
}
Everytime you get the wrong input, you remaking your count int n = 5;
so everytime you have 5 tries left.
What you can do is to declare your count outside of the static void Main(string args[]) method
just like:
int n =5;
static void Main(string args[])
{
}
you problems are the following nested if-contitions
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
}
else
{
\\...
}
If the username is correct and the pass not, it wont enter the else branch.
a better solution to ask for input until it is valid id a do ... while loop
Following example has a lot of improvements over yours.
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
int maxTries;
int tries = maxTries = 5;
do
{
if (tries != maxTries)//second and more
{
Console.Clear();
Console.WriteLine("Invalid");
Console.Write("\n\t" + tries + " Tries left");
Console.WriteLine("\n\n\n\tTry again? (y/n)");
string input;
do
{
input = Console.ReadLine();
} while (input != "y" && input != "n");
if (input == "n")
{
return; // exit the program
}
}
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
tries--;
} while (obj.getName() != "niit" || obj.getPass() != "1234");
Console.WriteLine("Wellcome");
}
PS: Classes should start with a capital letter.
goto is a relict of old times, it will mess with your programm structure and make things more complicated than they are. The only propper use i know is for fallthrough in switches, which also is needed only in rare cases.
A madeup one would be:
string vehicleType = "car";
switch(vehicleType)
{
case "truck":
Console.WriteLine("two wheeles and");
goto case "car";
case "car":
Console.WriteLine("two wheeles and");
goto case "motor cycle";
case "motor cycle":
Console.WriteLine("two wheeles");
break;
case "boat":
Console.WriteLine("no wheeles");
break;
}
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);
}
}
}