losing streak loop in hangman C# - c#

I'm trying to make a Hangman game in C#. It has a 5 tries limit, then the user will get a "you lose" message. If the user gets a letter wrong, it was supposed to get them a "wrong letter -- try again"
class Program
{
static void Main(string[] args)
{
string word;
int correct = 0;
int errors = 0;
Console.WriteLine("Enter a word");
word = Console.ReadLine();
char[] letters = word.ToCharArray();
char[] hanged = word.ToCharArray();
char digits;
for (int i = 0; i < word.Length; i++)
{
if (letters[i] == ' ')
{
hanged[i] = ' ';
}
else
{
hanged[i] = '_';
}
}
Console.Clear();
do
{
Console.Write(" ________\n" +
"| |\n" +
"| |\n" +
"|\n" +
"|\n" +
"|\n" +
"|\n" +
"|\n" +
"|\n\n");
Console.SetCursorPosition(2, Console.CursorTop - 2);
for (int i = 0; i < word.Length; i++)
{
Console.Write(hanged[i] + " ");
}
Console.WriteLine("\n\n\nEnter a letter");
digits = Convert.ToChar(Console.Read());
for (int i = 0; i < word.Length; i++)
{
if (digits == hanged[i])
{
Console.WriteLine("\nletter already in there -- press enter");
Console.ReadKey();
}
else if (digits == letters[i])
{
hanged[i] = digits;
correct++;
}
else if (digits != letters[i])
{
Console.WriteLine("\nwrong letter -- try again");
errors++;
Console.ReadKey();
}
if (errors == 5)
{
Console.WriteLine("\nYou lose");
Console.ReadKey();
break;
} else if (correct == word.Length)
{
Console.WriteLine("\nYou win");
Console.ReadKey();
break;
}
}
Console.Clear();
} while (correct < word.Length);
Console.ReadKey();
}
}
However, my program is stuck in a loop when counting the losses. The code thats messing it up is this section
else if (digits != letters[i])
{
Console.WriteLine("\nwrong letter -- try again");
errors++;
Console.ReadKey();
}
When I delete this section and run the code, in case of a wrong letter it just runs over it infinitely and the player will get infinite chances to try when they were supposed to have only 5 chances. How can I fix this?

The problem is that the 2nd loop for (int i = 0; i < word.Length; i++) that is responsible for finding a letter should not perform other logic in there. E.g., if the user types a letter matching the third position, then this will count 2 errors before counting one correct letter and also do extra console input and output.
I suggest using Array.IndexOf to get the index of a letter. This returns -1 if it is not found. Also, I found that the different kinds of Console.ReadXY can interfere with each other. E.g. calling Console.Read() and pressing a letter plus Enter makes the next Console.ReadLine() just return without waiting for user input.
My attempt (content of static void Main(string[] args)):
string word;
int correct = 0;
int errors = 0;
Console.WriteLine("Enter a word");
word = Console.ReadLine();
char[] letters = word.ToCharArray();
char[] hanged = word.ToCharArray();
char digits;
for (int i = 0; i < word.Length; i++) {
if (letters[i] == ' ') {
hanged[i] = ' ';
} else {
hanged[i] = '_';
}
}
Console.Clear();
do {
Console.Write(" ________\n" +
"| |\n" +
"| |\n" +
"|\n" +
"|\n" +
"|\n" +
"|\n" +
"|\n" +
"|\n\n");
Console.SetCursorPosition(2, Console.CursorTop - 2);
for (int i = 0; i < word.Length; i++) {
Console.Write(hanged[i] + " ");
}
Console.Write("\n\n\nEnter a letter: ");
ConsoleKeyInfo key = Console.ReadKey();
digits = key.KeyChar;
int hangedIndex = Array.IndexOf(hanged, digits);
int lettersIndex = Array.IndexOf(letters, digits);
if (hangedIndex >= 0) {
Console.WriteLine("\nletter already in there -- press enter");
Console.ReadLine();
} else if (lettersIndex >= 0) {
hanged[lettersIndex] = digits;
correct++;
} else {
Console.Write("\nwrong letter -- try again (press enter) ");
Console.ReadLine();
errors++;
}
if (errors == 5) {
Console.WriteLine("\nYou lose");
break;
} else if (correct == word.Length) {
Console.WriteLine("\nYou win");
break;
}
Console.Clear();
} while (correct < word.Length);
Console.ReadKey();

Related

C# Console - User inputs X numbers and gets stored in array

I tried to have a console app that takes 5 numbers and fills an array with it but The issue with this code is that, it only accepts 4 numbers and fills the last index with null, how could I fix that?
string[] numbers = new string[4];
Console.WriteLine("Hi, Enter 5 numbers!");
ConsoleKeyInfo key;
for (int i = 0; i < numbers.Length; i++)
{
string _val = "";
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace)
{
double val = 0;
bool _x = double.TryParse(key.KeyChar.ToString(), out val);
if (_x)
{
_val += key.KeyChar;
Console.Write(key.KeyChar);
}
}
else
{
if (key.Key == ConsoleKey.Backspace && _val.Length > 0)
{
_val = _val.Substring(0, (_val.Length - 1));
Console.Write("\b \b");
}
}
}
while (key.Key != ConsoleKey.Enter);
Console.WriteLine();
numbers[i] = _val;
}
Console.WriteLine();
for(int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(i + " : " + numbers[i]);
}
Console.WriteLine(numbers.Length);
Console.ReadKey();
}
In the code string[] numbers = new string[4]; means numbers array size is 4 and array starts with 0 index. Hence last index is not null. Change the string[4] to string[5]. Hope this will solve your problem.

TryParse Handling in Loop

I'm using TryParse to check if user enters integer or not in a loop and if user enters any character or non integer value user will receive invalid message and loop goes to next iteration.
I want user to re-enter input to same iteration.
int[] number = new int[5];
int newSum = 0;
int outValue;
Console.Write("Enter Five Integer Digits: \n");
for (int i = 0; i <= number.Length - 1; i++)
{
Console.Write("Number {0}: ", i);
bool Parse = Int32.TryParse(Console.ReadLine(), out outValue);
if (Parse)
{
number[i] = outValue;
}
else
{
Console.WriteLine("You Have Entered InValid Format: ");
}
newSum += number[i];
}
Console.WriteLine("Sun of Numbers :{0}", newSum);
I expected the output to be
Number 2: h
You Have Entered InValid Format:
Number 2:
But the actual output is
Number 2: h
You Have Entered InValid Format:
Number 3:
I'd rewrite you loop in following way:
for (int i = 0; i <= number.Length - 1; i++)
{
Console.Write("Number {0}: ", i);
bool Parse = Int32.TryParse(Console.ReadLine(), out outValue);
if (Parse)
{
// if parsing is successfull, then add to array and to sum :)
number[i] = outValue;
newSum += number[i];
}
else
{
Console.WriteLine("You Have Entered InValid Format: ");
// just decrement iterator to repeat this iteration
i--;
}
}
for (int i = 0; i < number.Length; i++)
{
Console.Write("Number {0}: ", i);
bool Parse = Int32.TryParse(Console.ReadLine(), out outValue);
if (Parse)
{
number[i] = outValue;
newSum += number[i];
}
else
{
i--;
Console.WriteLine("You Have Entered InValid Format: ");
}
}
I'm not a fan of changing the value of the index inside a for-next loop (code smell!).
An alternative is:
var i=0;
while (i < 5)
{
Console.Write("Number {0}: ", i);
bool Parse = Int32.TryParse(Console.ReadLine(), out outValue);
if (Parse)
{
number[i] = outValue;
newSum += number[i];
i++;
}
else
{
Console.WriteLine("You Have Entered InValid Format: ");
}
}
It would be worth checking for some form of "escape" character as the while loop will not exit until 5 acceptable values are entered.

Outside Bounds of Array When Reading From File

I'm new to C# - I've got a 'Treasure Hunt' game here - it hides a 't' in a box, then the user inputs coordinates - if they get 't' it says they've won, if not then a 'm' is displayed.
I'm trying to setup save games linked to the name a user enters. It writes the save game to a txt file and stores it - that much works. But when I try to load the game I keep getting an error 'Index was outside the bounds of the array'.
static string username = "";
static string saveGame = "";
public const int BoardSize = 10;
static void Main(string[] args)
{
char[,] Board = new char[10, 10];
Console.WriteLine("Would you like to:");
Console.WriteLine("1. Start New Game");
Console.WriteLine("2. Load Game");
Console.WriteLine("9 Quit.");
int mainMenuChoice = 0;
mainMenuChoice = int.Parse(Console.ReadLine());
if (mainMenuChoice == 1)
{
Console.WriteLine("What is your name?");
username = Console.ReadLine();
}
else if (mainMenuChoice == 2)
{
Console.WriteLine("What was your username?");
username = Console.ReadLine();
saveGame = username + ".txt";
LoadGame(saveGame, ref Board);
}
else if (mainMenuChoice == 9)
{
Console.WriteLine("Closing in 3 seconds.");
Thread.Sleep(3000);
Environment.Exit(0);
}
Random randomOneX = new Random();
randomOneX = new Random(randomOneX.Next(0, 10));
int randomX = randomOneX.Next(0, BoardSize);
randomOneX = new Random(randomOneX.Next(0, 10));
int randomY = randomOneX.Next(0, BoardSize);
//Console.Write(randomX);
//Console.Write(randomY);
for (int i = 0; i < Board.GetUpperBound(0); i++)
{
for (int j = 0; j < Board.GetUpperBound(1); j++)
{
Board[i, j] = ' ';
}
}
Board[randomX, randomY] = 'x';
PrintBoard(Board);
int Row = 0;
int Column = 0;
bool wonGame = false;
Console.WriteLine();
Console.WriteLine("I've hidden a 't' in a map - you're job is to find the coordinates that have the 't' in.");
Console.WriteLine();
do
{
Console.Write("Please enter a Row: ");
bool validRow = false;
do
{
try
{
Row = int.Parse(Console.ReadLine());
validRow = true;
if (Row >= 10 || Row < 0)
{
Console.WriteLine("Please pick a number between 0-9: ");
validRow = false;
}
}
catch (Exception)
{
Console.WriteLine("Ooops, you've entered something that simply cannot be, please retry.");
}
} while (validRow == false);
Console.Write("Now enter a column: ");
bool validColumn = false;
do
{
try
{
Column = int.Parse(Console.ReadLine());
validColumn = true;
if (Column >= 10 || Column < 0)
{
Console.WriteLine("Please pick a number between 0-9: ");
validColumn = false;
}
}
catch (Exception)
{
Console.WriteLine("Ooops, you've entered something that simply cannot be, please retry.");
}
} while (validColumn == false);
if (Board[Row, Column] != 'x')
{
Board[Row, Column] = 'm';
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.Clear();
Console.WriteLine("You've missed the target! Feel free to retry.");
Console.ForegroundColor = ConsoleColor.Gray;
wonGame = false;
PrintBoard(Board);
SaveGame(username, ref Board);
}
else
{
Board[Row, Column] = 't';
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("You've won!");
Console.ForegroundColor = ConsoleColor.Gray;
wonGame = true;
}
} while (wonGame == false);
PrintBoard(Board);
Console.ReadLine();
}
private static void PrintBoard(char[,] Board)
{
Console.WriteLine();
Console.WriteLine("The map looks like this: ");
Console.WriteLine();
Console.Write(" ");
for (int Column = 0; Column < BoardSize; Column++)
{
Console.Write(" " + Column + " ");
}
Console.WriteLine();
for (int Row = 0; Row < BoardSize; Row++)
{
Console.Write(Row + " ");
for (int Column = 0; Column < BoardSize; Column++)
{
if (Board[Row, Column] == '-')
{
Console.Write(" ");
}
else if (Board[Row, Column] == 'x')
{
Console.Write(" ");
}
else
{
Console.Write(Board[Row, Column]);
}
if (Column != BoardSize)
{
Console.Write(" | ");
}
}
Console.WriteLine();
}
}
private static void SaveGame(string username, ref char [,] inBoard)
{
StreamWriter sGame = null;
string saveFilePath = username + ".txt";
try
{
sGame = new StreamWriter(saveFilePath);
}
catch (Exception)
{
Console.WriteLine("Ooops there seems to be an error with saving your game. Check the log for details.");
}
for (int i = 0; i < inBoard.GetUpperBound(0); i++)
{
for (int j = 0; j < inBoard.GetUpperBound(1); j++)
{
sGame.Write(inBoard[i, j]);
}
sGame.WriteLine("");
}
sGame.Close();
}
private static void LoadGame(string GameFile, ref char[,] Board)
{
StreamReader saveGameReader = null;
string Line = "";
try
{
saveGameReader = new StreamReader(GameFile);
}
catch (Exception e)
{
StreamWriter errorMessage = new StreamWriter("ErrorLog.txt", true);
errorMessage.WriteLine(DateTime.Now + "Error: " + e.ToString());
errorMessage.Close();
Debug.WriteLine(e.ToString());
Console.WriteLine("There was an error loading game, check log for info. (Press Enter to exit.)");
Console.ReadLine();
Environment.Exit(0);
}
char[,] loadedBoard = Board;
for (int Row = 0; Row < BoardSize; Row++)
{
Line = saveGameReader.ReadLine();
for (int Column = 0; Column < BoardSize; Column++)
{
loadedBoard[Row, Column] = Line[Column];
}
}
Board = loadedBoard;
saveGameReader.Close();
}
}
}
The link to a notepad screenshot is : https://imgur.com/a/hobuv
The GetUpperBound returns, as MSDN says
Gets the index of the last element of the specified dimension in the
array.
So you are getting 9 everywhere you use that method. To fix your code you need to change your loops in the saving and initialization of the Board array with <= as exit condition from the loops
for (int i = 0; i <= Board.GetUpperBound(0); i++)
{
for (int j = 0; j <= Board.GetUpperBound(1); j++)
{
Board[i, j] = ' ';
}
}
Your save has 9 rows but your board size was defined as 10
If your values in the file are like below
m m m m m m m m X m m m
m m m m m X m m X m m m
m m m X m m m m X m m m
Then you can try with this approach
int i = 0;
// Read the file and work it line by line.
string[] lines = File.ReadAllLines(gameFile);
foreach(string line in lines)
{
string[] columns = line.Split(' ');
for(int j = 0; j < columns.Length; j++)
{
loadedBoarder[i, j] = columns[j];
}
i++;
}
#captainjamie : Thanks for correcting my code.

c# dice game implementation

I'm stuck on how I can implement the code so when it compiles to one counter it displays one counter not 'counters' as a plural for only one counter. I need help on how I can implement that piece of code in to my code that I have given below.
namespace ReferralDG
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Even Minus Odd Game: ");
Random rand = new Random();
bool PlayAgain = false;
do
{
int numberOfDice = 0;
int totalOfDiceRolled = 0;
while (numberOfDice > 10 || numberOfDice < 3)
{
Console.WriteLine("How many dice do you wish to play with? (Between 3 and 10?)");
numberOfDice = Convert.ToInt32(Console.ReadLine());
if (numberOfDice > 10 || numberOfDice < 3)
{
Console.WriteLine("Please enter the correct number
}
}
Console.Write("Dice rolls: ");
int evenTotal = 0;
int oddTotal = 0;
for (int i = 0; i < numberOfDice; i++)
{
int diceRoll = rand.Next(1, 7);
if (diceRoll % 2 == 0)
{
evenTotal += diceRoll;
}
else
{
oddTotal += diceRoll;
}
totalOfDiceRolled += diceRoll;
Console.Write(diceRoll + " ");
}
int counters = evenTotal - oddTotal;
Console.WriteLine();
if (counters > 0)
{
Console.WriteLine("You take " + counters + " counters.");
}
else if (counters < 0)
{
Console.WriteLine("You give " + Math.Abs(counters) + " counters.");
}
else if (evenTotal == oddTotal)
{
Console.WriteLine("Even total is equal to odd total");
}
else
{
Console.WriteLine("No counters this game");
}
Console.WriteLine("Would you like to play again? (Y/N): ");
string playAgain = Console.ReadLine().ToUpper();
if (playAgain == "Y")
{
PlayAgain = true;
}
else
{
PlayAgain = false;
}
} while (PlayAgain);
}
}
}
you could use the if shorthand statement ? valueIfTrue : valueIfFalse; to set the right string values. and put everything in a function like that
private static void printCounters(int counters,bool take) {
counters = Math.Abs(counters);
string msg1 = take ? "You take " : "You give ";
string msg2 = counters == 1 ? " counter." : " counters.";
Console.WriteLine( msg1 + counters + msg2);
}
this has the advantage that you can easily call printCounters(counters,true) if you take and printCounters(counters,give) if you give
You can just add additional if's to your block.
if (counters > 1) {
Console.WriteLine("You take " + counters + " counters.");
}
else if (counters > 0) // or if you rather counters == 1
{
Console.WriteLine("You take " + counters + " counter.");
}
else if (counters < -1)
{
Console.WriteLine("You give " + Math.Abs(counters) + " counters.");
}
else if (counters < 0)
{
Console.WriteLine("You give " + Math.Abs(counters) + " counter.");
}
else if (evenTotal == oddTotal)
{
Console.WriteLine("Even total is equal to odd total");
}
else
{
Console.WriteLine("No counters this game");
}
Another "simpler" solution is to just output it as counter(s)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
namespace ReferralDG
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Even Minus Odd Game: ");
Random rand = new Random();
bool PlayAgain = false;
do
{
int numberOfDice = 0;
int totalOfDiceRolled = 0;
while (numberOfDice > 10 || numberOfDice < 3)
{
Console.WriteLine("How many dice do you wish to play with? (Between 3 and 10?)");
numberOfDice = Convert.ToInt32(Console.ReadLine());
if (numberOfDice > 10 || numberOfDice < 3)
{
Console.WriteLine("Please enter the correct number");
}
}
Console.Write("Dice rolls: ");
int evenTotal = 0;
int oddTotal = 0;
for (int i = 0; i < numberOfDice; i++)
{
int diceRoll = rand.Next(1, 7);
if (diceRoll % 2 == 0)
{
evenTotal += diceRoll;
}
else
{
oddTotal += diceRoll;
}
totalOfDiceRolled += diceRoll;
Console.Write(diceRoll + " ");
}
int counters = evenTotal - oddTotal;
Console.WriteLine();
if (counters > 1)
{
Console.WriteLine("You take " + counters + " counters.");
}
else if (counters > 0) // or if you rather counters == 1
{
Console.WriteLine("You take " + counters + " counter.");
}
else if (counters < -1)
{
Console.WriteLine("You give " + Math.Abs(counters) + " counters.");
}
else if (counters < 0)
{
Console.WriteLine("You give " + Math.Abs(counters) + " counter.");
}
else if (evenTotal == oddTotal)
{
Console.WriteLine("Even total is equal to odd total");
}
else
{
Console.WriteLine("No counters this game");
}
Console.WriteLine("Would you like to play again? (Y/N): ");
string playAgain = Console.ReadLine().ToUpper();
if (playAgain == "Y")
{
PlayAgain = true;
}
else
{
PlayAgain = false;
}
} while (PlayAgain);
}
}
}
}
Hello and welcome to StackOverflow Sam!
So when you write the counters to the screen, you want it to write singular if their is a single counter, and plural if there are more than 1? I also assume we want this to work no matter if the counter is positive or negative.
Instead of adding a couple more branches to your if statement, we could use string.Format() and an Inline If statement.
In this case, it would look something like this:
// Console.WriteLine("You take " + counters + " counters.");
Console.WriteLine(string.Format("You take {0} counter{1}.", counters, Math.Abs(counters) == 1 ? "" : "s"));
This is really just a way of writing multiple "else ifs", as you still have added a branching statement. My way, it is in-line instead of taking up more space vertically.
If you wanted to get even more fancy, you could use an IIF to set the "give" or "take" as well:
if (counters != 0)
{
Console.WriteLine(string.Format("You {0} {1} counter{2}.",
counters > 0 ? "take" : "give",
counters,
Math.Abs(counters) == 1 ? "" : "s"
));
}
else if (evenTotal == oddTotal)
{
Console.WriteLine("Even total is equal to odd total");
}
else
{
Console.WriteLine("No counters this game");
}
Read up on the links, see what works best for you!

Hangman in C# Looping Issue

So i got The following Code Here... I have to provide 5 User provided words, randomize on the 5 and give any one of them up for a guess, the tries = word length + 2. The main problem i Am having is looping the entire check to fill in the 2nd, 3rd guess etc. The 1st guess is fine. How would i go about looping and keeping the characters which were guessed right while still keeping the ones that were not guessed as a "_" character.
Example - Word was "Heaven" - User Enters "e" - Produces - _ e _ _ e _ No Spaces.
The tries would then be equal to 6(Word Length) + 2 = 8 Tries
int tries = 0;
Random rand = new Random();
int randomword = rand.Next(1, 5);
string word = "";
Console.WriteLine("Please Enter 5 Words into the System");
Console.WriteLine();
for (int i = 0; i < 5; i++)
{
words.Add(Console.ReadLine());
Console.Clear();
}
Console.WriteLine("For Display Purposes. Here are Your 5 Words");
Console.WriteLine("===========================================");
Console.WriteLine();
foreach (var item in words)
{
Console.WriteLine(item);
}
Console.WriteLine();
Console.WriteLine("Now Guess The word given Below");
Console.WriteLine();
switch (randomword)
{
case 1:
//Gets the List index 0 - 1st word in the list
word = words[0];
tries = word.Length;
break;
case 2:
word = words[1];
tries = word.Length;
break;
case 3:
word = words[2];
tries = word.Length;
break;
case 4:
word = words[3];
tries = word.Length;
break;
case 5:
word = words[4];
tries = word.Length;
break;
default:
break;
}
//Default + addition to the Length
tries += 2;
Console.WriteLine();
Console.WriteLine("You Have {0} + tries",tries );
//Works for the 1st Guess
do
{
char guess = char.Parse(Console.ReadLine());
if (word.Contains(guess))
{
foreach (char item in word)
{
if (item == guess)
{
Console.Write(item);
}
else
{
Console.Write("_");
}
}
}
Console.WriteLine();
}
//If my word contains A "_" i will keep looping
while (word.Contains("_"));
Console.ReadKey();
Your main problem is that you're only keeping track of the current guess, not all the previous ones. You can use a HashSet to keep track of your previous guesses. So define a variable HashSet<char> guessedLetters before your do loop, and then as the 2nd line in your loop after you parse "guess" do guessedLetters.Add(guess). Then substitute if(item==guess) with if(guessedLetters.Contains(item)). Viola, only three lines code change!
Finally your exit condition can be while (word.Any(c=>!guessedChars.Contains(c)) && --tries != 0);.
How about:
static void Main(string[] args)
{
string[] words = new string[] { "Apple", "Banana", "Pear", "Pineapple", "Melon"};
Random random = new Random();
string wordToGuess = words[random.Next(5)].ToLower();
char[] currentLetters = new char[wordToGuess.Length];
for (int i = 0; i < currentLetters.Length; i++) currentLetters[i] = '_';
int numTries = currentLetters.Length + 1;
bool hasWon = false;
do
{
string input = Console.ReadLine().ToLower();
if (input.Length == 1) //guess a letter
{
char inputChar = input[0];
for (int i = 0; i < currentLetters.Length; i++)
{
if (wordToGuess[i] == inputChar)
{
currentLetters[i] = inputChar;
}
}
if (!currentLetters.Contains('_'))
{
hasWon = true;
}
else
{
Console.WriteLine(new string(currentLetters));
}
}
else
{
if (input == wordToGuess)
{
hasWon = true;
}
else
{
Console.WriteLine("Incorrect!");
Console.WriteLine(new string(currentLetters));
}
}
numTries--;
} while (new string(currentLetters) != wordToGuess && numTries > 0 && !hasWon);
if (hasWon)
{
Console.WriteLine("Congratulations, you guessed correctly.");
}
else
{
Console.WriteLine("Too bad! Out of tries");
}
}
you need to store the guessing result and check that for your loop (change your do while loop to as below):
string resultword = word;
do
{
char guess = char.Parse(Console.ReadLine());
if (word.Contains(guess))
{
resultword = resultword.Replace(guess, ' ');
for (int i = 0; i < resultword.Count(); i++)
{
if (resultword[i] == ' ')
{
Console.Write(word[i]);
}
else
{
Console.Write("_");
}
}
}
Console.WriteLine();
}
while (tries-- != 0 && resultword.Trim() != string.Empty);
How about, using your existing code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
internal class Program
{
private static void Main(string[] args)
{
List<string> words = new List<string>();
int tries = 0;
Random rand = new Random();
var currentLetters = new List<char>();
int randomword = rand.Next(1, 5);
string word = "";
Console.WriteLine("Please Enter 5 Words into the System");
Console.WriteLine();
for (int i = 0; i < 5; i++)
{
words.Add(Console.ReadLine());
Console.Clear();
}
Console.WriteLine("For Display Purposes. Here are Your 5 Words");
Console.WriteLine("===========================================");
Console.WriteLine();
foreach (var item in words)
{
Console.WriteLine(item);
}
Console.WriteLine();
Console.WriteLine("Now Guess The word given Below");
Console.WriteLine();
switch (randomword)
{
case 1:
//Gets the List index 0 - 1st word in the list
word = words[0];
tries = word.Length;
break;
case 2:
word = words[1];
tries = word.Length;
break;
case 3:
word = words[2];
tries = word.Length;
break;
case 4:
word = words[3];
tries = word.Length;
break;
case 5:
word = words[4];
tries = word.Length;
break;
default:
break;
}
//Default + addition to the Length
tries += 2;
Console.WriteLine();
Console.WriteLine("You Have {0} + tries", tries);
//Works for the 1st Guess
do
{
char guess = char.Parse(Console.ReadLine());
if (!currentLetters.Contains(guess))
{
currentLetters.Add(guess);
foreach (var l in word.ToCharArray().Intersect(currentLetters).ToArray())
{
word = word.Replace(l, '_');
}
}
Console.WriteLine(word);
} //If my word contains A "_" i will keep looping
while (word.Contains("_"));
Console.ReadKey();
}
}
}
Working example:
List<string> words = new List<string>();
int tries = 0;
Random rand = new Random();
int randomword = rand.Next(1, 5);
string word = "";
Console.WriteLine("Please Enter 5 Words into the System");
Console.WriteLine();
for (int i = 0; i < 5; i++)
{
words.Add(Console.ReadLine());
Console.Clear();
}
Console.WriteLine("For Display Purposes. Here are Your 5 Words");
Console.WriteLine("===========================================");
Console.WriteLine();
foreach (var item in words)
{
Console.WriteLine(item);
}
Console.WriteLine();
Console.WriteLine("Now Guess The word given Below");
Console.WriteLine();
switch (randomword)
{
case 1:
//Gets the List index 0 - 1st word in the list
word = words[0];
tries = word.Length;
break;
case 2:
word = words[1];
tries = word.Length;
break;
case 3:
word = words[2];
tries = word.Length;
break;
case 4:
word = words[3];
tries = word.Length;
break;
case 5:
word = words[4];
tries = word.Length;
break;
default:
break;
}
//Default + addition to the Length
tries += 2;
Console.WriteLine();
Console.WriteLine("You Have {0} + tries", tries);
List<char> guesses = new List<char>();
string guessedWord = "";
for(int i=0;i<word.Length;i++)
{
guessedWord += "_";
}
//Works for the 1st Guess
do
{
char guess = char.Parse(Console.ReadLine());
if (word.Contains(guess))
{
guesses.Add(guess);
}
foreach (char storedGuess in guesses)
{
if(word.Contains(storedGuess))
{
int index = word.IndexOf(storedGuess);
while(index > -1)
{
StringBuilder sb = new StringBuilder(guessedWord);
sb[index] = storedGuess;
guessedWord = sb.ToString();
index = word.IndexOf(storedGuess, index+1);
}
}
}
Console.WriteLine(guessedWord);
}
while (guessedWord.Contains("_"));
Console.ReadKey();
You mention the number of tries, but you never use it in the code after it is used. Presumably, you want to do the following:
Pick a random word (in your case, you are picking one of the five words supplied by the user)
Set the number of guesses (tries?) equal to the length of the word plus 2. If they guess a letter that is present, then it is free. If the letter is not present, then they lose one of their guesses.
Before each guess, display the word with all the unguessed letters replaced by "_".
When the user guesses a letter that is present, replace the "_" in the displayed word by the letter.
Here is some sample code that should work (untested):
string displayword = String.Copy(word);
for (int j = 0; j < displayword.length; j++) displayword[j]='_';
do {
// Display the word so far.
Console.WriteLine("Word is {0}", displayword);
// Get a guess from the user
char guess = char.Parse(Console.ReadLine());
if (word.Contains(guess)) {
for (j=0; j<word.length; j++) {
if (word[j] == guess) displayword[j]=guess;
}
} else {
// Decrease the tries.
tries--;
}
} while (displayword.Contains("_") && (tries > 0));
You need to distinguish the input word from the result so-far. Initialize the result with underscores, and then add the letters to the result as people guess them. It's a little easier if you make result a char array instead of a string.
var result = new string('_', word.Length).ToCharArray();
do
{
char guess = char.Parse(Console.ReadLine());
for (var i = 0; i < word.Length; ++i)
{
if(word[i] == guess)
{
result[i] = guess;
}
}
Console.WriteLine(new string(result));
}
//If my word contains A "_" i will keep looping
while (result.Contains('_') && --tries != 0);

Categories

Resources