C# Need inputs in different lines - c#

I am trying to create a program that is will take letters as input only and not duplicated. I am getting error when i put one letter in an input.
This is what i need to do, I need to get the user input in each line (like a enter, b enter, etc), if there is a duplication value i need a error message and continues with the input, and if there is incorrect value i get another error stating such. I cannot use LINQ, Hashset, nor list, it has to be arrays.
static void Main(string[] args)
{
char[] Array = new char[5];
Console.WriteLine("Please Enter 5 Letters B/W a through j only: ");
string letters = "abcdefghij";
char[] read = Console.ReadLine().ToLower().ToCharArray();
//loop through array
for (int i = 0; i < 5; i++)
{
if (letters.Contains(read[i]) && !Array.Contains(read[i]))
{
Array[i] = read[i];
}
else
{
Console.WriteLine("You have entered an incorrect value");
}
}
Console.WriteLine("You have Entered the following Inputs: ");
for (int i = 0; i < Array.Length; i++)
{
Console.WriteLine(Array[i]);
}
Console.ReadKey();
}

I think this more or less does what you want:
var max = 5;
var array = new char[max];
var letters = "abcdefghij";
var count = 0;
while (count < 5)
{
Console.WriteLine("Please Enter {0} Letters B/W a through j only: ", max);
var key = Console.ReadKey();
var read = key.KeyChar
if (!letters.Contains(read))
{
Console.WriteLine("You have entered an incorrect value");
continue;
}
var found = false;
for (int i = 0; i < count; i++)
{
if (array[i] == read)
{
found = true;
}
}
if (found)
{
Console.WriteLine("You have entered an duplicate value");
continue;
}
array[count++] = read;
}
Console.WriteLine("You have Entered the following Inputs: ");
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine(array[i]);
}
Console.ReadKey();

If you want the user to enter the values individually then you would need to request each character in a loop.
Something like:
static void Main(string[] args)
{
const string validValues = "abcdefghij";
var enteredCharacters = new char[5];
for (int i = 0; i < enteredCharacters.Length; i++)
{
Console.WriteLine("Please enter a unique character between a and j");
var input = Console.ReadLine();
if (input.Length == 0)
{
Console.WriteLine("You did not enter a value.");
return;
}
if (input.Length > 1)
{
Console.WriteLine("You have entered more than 1 character");
return;
}
var character = input[0];
if (!validValues.Contains(character))
{
Console.WriteLine("You have entered an invalid character");
return;
}
if (enteredValues.Contains(character))
{
Console.WriteLine("You have already entered this character");
return;
}
enteredCharacters[i] = character;
}
// process numbers.
}

this is you problem
for (int i = 0; i < 5; i++)
this is your fix:
static void Main(string[] args)
{
char[] Array = new char[5];
Console.WriteLine("Please Enter 5 Letters B/W a through j only: ");
string letters = "abcdefghij";
char[] read = Console.ReadLine().ToLower().ToCharArray();
//loop through array
for (int i = 0; i < read.Length; i++)
{
if (letters.Contains(read[i]) && !Array.Contains(read[i]))
{
Array[i] = read[i];
}
else
{
Console.WriteLine("You have entered an incorrect value");
}
}
Console.WriteLine("You have Entered the following Inputs: ");
for (int i = 0; i < Array.Length; i++)
{
Console.WriteLine(Array[i]);
}
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.

why is the output in lottery code isn't working?

I'm supposed to make a code in c# (microsoft visual studio 2017) that lets the user input six numbers, and then compare them to an array of six randomly generated numbers(with no duplicates).
If the user has one match, he's supposed to get a message saying he had one match, and different messages for two or three matches, and so on.
This is what I got so far:
static bool isValueInArray(int value, int[] a)
{
for (int i = 0; i < a.Length; i++)
{
if (a[i] == value)
{
return true;
}
}
return false;
}
static void Main(string[] args)
{
int min = 0;
int max = 6;
Random randnum = new Random();//random number generator
int[] numbers = new int[6];// generates six numbers
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = randnum.Next(min, max);//sets the numbers between 0 to 6
if(isValueInArray( i, numbers))
{
numbers[i] = randnum.Next(min, max);
}
}
try
{
Console.WriteLine("Hello and Welcome to our little game of lottery! lets see just how much luck you got!"); // greetings and instructions
Console.WriteLine("You'll now get to choose 6 different numbers between 0 to 6 to play with.");
Console.WriteLine("Go ahead and type them in.");
int[] lottery = new int[6];
for (int i = 0; i < lottery.Length; i++)
{
lottery[i] = int.Parse(Console.ReadLine()); // array to catch six numbers input
if (lottery[i] > 6)//checking if the numbers fit between 0 and 6
{
Console.WriteLine("whoops! the number you enetered isn't in range! please try again ^^");
break;
}
int x = 6;
for (int a = 0; a < lottery.Length; a++)
{
for (int b = 0; b < numbers.Length; b++)
{
if (lottery[a] == numbers[b])
{
a++;
x--;
if (x == 6)
{
Console.WriteLine("six match");
break;
}
else if (x == 5)
{
Console.WriteLine("five match");
break;
}
else if (x == 4)
{
Console.WriteLine("four match");
break;
}
else if (x == 3)
{
Console.WriteLine("three match");
break;
}
else if (x == 2)
{
Console.WriteLine("two match");
break;
}
else if (x == 1)
{
Console.WriteLine("one match");
break;
}
}
}
}
}
}
catch (FormatException)// checking if the input is in char format
{
Console.WriteLine("only numbers please!");
}
}
My problem is with the output. The program seems to go over all of the "else if" options and print all of them, instead of picking and printing just one of them.
You have everything mixed together. Write out the steps:
Generate numbers
Get input from user
Count number of matches
Print results
Each step should be performed separately.
// These should be the min/max lottery numbers
int min = 1;
int max = 100;
int numberOfLotteryNumbers = 6;
// Renamed for clarity
int[] lotteryNumbers = new int[numberOfLotteryNumbers];
int[] userNumbers = new int[numberOfLotteryNumbers];
// Step 1 - generate numbers
for (int i = 0; i < lotteryNumbers.Length; i++) {
int randomNumber;
do {
randomNumber = randnum.Next(min, max);
} while (isValueInArray(randomNumber, lotteryNumbers));
lotteryNumbers[i] = randomNumber;
}
// Step 2 - get numbers from user
for (int i = 0; i < lottery.Length; i++) {
int userInput;
do {
userInput = int.Parse(Console.ReadLine());
} while (userInput < min || userInput > max || isValueInArray(userInput, userNumbers));
userNumbers[i] = userInput;
}
// Step 3 - calc matches
int matches = 0;
for (int i = 0; i < userNumbers.Length; i++) {
if (isValueInArray(userNumbers[i], lotteryNumbers) {
matches += 1;
}
}
// Step 4 - print results
Console.WriteLine("There are {0} matches.", matches);
You may have to rearrange the code blocks in a way to get user input first, calculate the number of matches first, then display results as following code:
Note: Your approach to guarantee unique numbers in the randomly generated number ain't going to work as you expect to, you are passing "i" where you may want to pass "numbers[i]" instead to the isValueInArray" function. Let aside the idea that you will always end with values 0-5 in the array since you want 6 numbers.
int min = 0;
int max = 6;
Random randnum = new Random();//random number generator
int[] numbers = new int[6];// generates six numbers
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = randnum.Next(min, max);//sets the numbers between 0 to 6
if (isValueInArray(i, numbers))
{
numbers[i] = randnum.Next(min, max);
}
}
try
{
Console.WriteLine("Hello and Welcome to our little game of lottery! lets see just how much luck you got!"); // greetings and instructions
Console.WriteLine("You'll now get to choose 6 different numbers between 0 to 6 to play with.");
Console.WriteLine("Go ahead and type them in.");
int[] lottery = new int[6];
int x = 0;
//read user numbers
for (int i = 0; i < lottery.Length; i++)
{
lottery[i] = int.Parse(Console.ReadLine()); // array to catch six numbers input
while (lottery[i] > 6)//checking if the numbers fit between 0 and 6
{
Console.WriteLine("whoops! the number you enetered isn't in range! please try again ^^");
lottery[i] = int.Parse(Console.ReadLine()); // array to catch six numbers input
}
}
//count number of matches
for (int a = 0; a < lottery.Length; a++)
{
for (int b = 0; b < numbers.Length; b++)
{
if (lottery[a] == numbers[b])
{
//a++;
x++;
break;
}
}
}
//display results
if (x == 6)
{
Console.WriteLine("six matches");
}
else if (x == 5)
{
Console.WriteLine("five matches");
}
else if (x == 4)
{
Console.WriteLine("four matches");
}
else if (x == 3)
{
Console.WriteLine("three matches");
}
else if (x == 2)
{
Console.WriteLine("two matches");
}
else if (x == 1)
{
Console.WriteLine("one match");
}
}
catch (FormatException)// checking if the input is in char format
{
Console.WriteLine("only numbers please!");
}
Console.Read();
}
You can use a counter to achieve your goal. Just increment counter value on match:
int counter = 0;
for (int i = 0; i < lottery.Length; i++)
{
// ..
if (x == number)
{
counter++;
break;
}
// ..
}
Console.WriteLine("You have " + counter + " matches");

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# mastermind game

In the Main method, in the for loop, if you copy/paste/run whole program in visual, you'll see that i'm trying to end the game. First "if", if the user hasn't guessed; then attempts decrements by one and keeps guessing. The second "else if", if the user has guessed the PCArray, than the game ends and message shows. those work.
But, the first "else if", if the user has exhausted his attempts to guess, and hasn't guessed PCArray, than it should say "oh no, you couldn't guess..." Why is this not working.
I just want it to work so that if:
- user hasn't guessed but still has attempts, attempts decrements by 1 until 0.
- user has guessed the correct number, it says congrats.
- attempts are 0 and user still hasn't guessed number, then show "oh no..." message.
class Program
{
static void Main(string[] args)
{
string name;
Console.WriteLine("**************Let's play Master-Mined**************");
Console.WriteLine();
Console.Write("Please enter your name: ");
name = Console.ReadLine();
Console.WriteLine("Welcome {0}. Have fun!! ", name);
int numberCount = 0;
int difficultyLevel = 0;
int digitNumber = GetRandomNumberCount(numberCount);
Console.Write(digitNumber + " it is. Let's play.");
Console.WriteLine();
int[] PCArray = GenerateRandomNumbers(digitNumber);
Console.WriteLine("A " + digitNumber + "-digit number has been chosen. Each possible digit may be the number 1, 2, 3 or 4.");
Console.WriteLine(" ******");
int difficulty = GetGameDifficulty(difficultyLevel);
int attempts = difficulty * digitNumber;
Console.WriteLine("Enter your guess ({0} guesses remaining)", attempts);
int remaining = attempts;
for (int i = 0; i < attempts; i++)
{
int[] userArray = GetUserGuess(digitNumber);
int hits = CountHits(PCArray, userArray, attempts);
if ((hits != PCArray.Length) && (attempts > 0))
{
remaining--;
Console.WriteLine("Enter your guess ({0} guesses remaining)", remaining);
}
else if ((attempts < 1))
{
Console.WriteLine("Oh no {0}! You couldn't guess the right number.", name);
Console.WriteLine("The correct number is: ");
for (int j = 0; j < PCArray.Length; j++)
{
Console.Write(PCArray[j] + " ");
}
Console.WriteLine("Would you like to play again (Y/N)? ");
}
else if (hits == PCArray.Length)
{
attempts = 0;
Console.WriteLine("You win {0}!", name);
Console.WriteLine("The correct number is:");
for (int j = 0; j < PCArray.Length; j++)
{
Console.Write(PCArray[j] + " ");
}
}
}
Console.ReadLine();
}
public static int GetRandomNumberCount(int numberCount)
{
int number = 0;
do
{
try
{
Console.Write("How many numbers would you like to use in playing the game (4-10)? ");
number = int.Parse(Console.ReadLine());
Console.WriteLine();
}
catch
{
Console.WriteLine("You must pick a number between 4 and 10. Choose again.");
Console.WriteLine();
}
} while ((number < 4) || (number > 10));
return number;
}
public static int GetGameDifficulty(int difficultyLevel)
{
int difficulty = 0;
do
{
try
{
Console.Write("Choose a difficulty level (1=hard, 2=medium, 3=easy): ");
difficulty = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine(" Incorrect entry: Please re-enter.");
}
} while ((difficulty < 1) || (difficulty > 3));
return difficulty;
}
public static int[] GenerateRandomNumbers(int PCSize)
{
int eachNumber;
int[] randomNumber = new int[PCSize];
Random rnd = new Random();
for (int i = 0; i < randomNumber.Length; i++)
{
eachNumber = rnd.Next(1, 5);
randomNumber[i] = eachNumber;
Console.Write(eachNumber);
}
Console.WriteLine();
return randomNumber;
}
public static int[] GetUserGuess(int userSize)
{
int number = 0;
int[] userGuess = new int[userSize];
for (int i = 0; i < userGuess.Length; i++)
{
Console.Write("Digit {0}: ", (i + 1));
number = int.Parse(Console.ReadLine());
userGuess[i] = number;
//Console.Write(number);
}
Console.WriteLine();
Console.Write("Your guess: ");
for (int i = 0; i < userGuess.Length; i++)
{
Console.Write(userGuess[i] + " ");
}
Console.WriteLine();
return userGuess;
}
public static int CountHits(int[] PCArray, int[] userArray, int attempts)
{
int hit = 0;
int miss = 0;
int hits = 0;
for (int i = 0; i < PCArray.Length; i++)
{
if (PCArray[i] == userArray[i])
{
hit = hit + 1;
hits = hit;
}
else
{
miss = miss + 1;
}
}
Console.WriteLine("Results: {0} Hit(s), {1} Miss(es)", hit, miss);
return hits;
}
}
First of all, you should rethink your code, because the flow control is scattered throughout your code. For example, you don't need both attempts and remaining, they control the same thing.
Using two variables to control the same thing is what is causing your problem. The first two ifs in your for should be like this:
if (hits != PCArray.Length && remaining > 1)
and
else if (remaining == 1)
Note I removed the unnecessary parenthesis. With these changes, your application works, although the code is not too pretty.
A simple way of enhancing your code is to first check for the right result, and if it's not, then decrease the attempts variable and finally check for its value. That's why with your code as it is, the if should compare to 1 instead of 0.
The hits variable in your CountHits method is totally unnecessary; you should just return hit. Actually the miss variable can be avoided too, you can calculate it. Also remember to use the ++ operator.
But as I said first, the important thing is not to make it work but to organize your code properly. Later I will post my version.
My version, it's not the most beautiful thing in the world but I didn't want to change much of your code structure:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("************** Let's play Master-Mind **************\n");
string name = GetPlayerName();
do
{
Play(name);
Console.Write("\nWould you like to play again (Y/N)? ");
}
while (Console.ReadLine().ToUpper() == "Y");
}
private static void Play(string name)
{
int numberCount = GetRandomNumberCount();
Console.Write(numberCount + " it is. Let's play.");
Console.WriteLine();
int[] PCArray = GenerateRandomNumbers(numberCount);
Console.WriteLine("A {0}-digit number has been chosen. Each possible digit may be the number 1 to 4.\n", numberCount);
int difficulty = GetGameDifficulty();
bool won = false;
for (int allowedAttempts = difficulty * numberCount; allowedAttempts > 0 && !won; allowedAttempts--)
{
Console.WriteLine("\nEnter your guess ({0} guesses remaining)", allowedAttempts);
int[] userArray = GetUserGuess(numberCount);
if (CountHits(PCArray, userArray) == numberCount)
won = true;
}
if (won)
Console.WriteLine("You win, {0}!", name);
else
Console.WriteLine("Oh no, {0}! You couldn't guess the right number.", name);
Console.Write("The correct number is: ");
for (int j = 0; j < numberCount; j++)
Console.Write(PCArray[j] + " ");
Console.WriteLine();
}
private static string GetPlayerName()
{
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Welcome, {0}. Have fun!!\n", name);
return name;
}
public static int GetRandomNumberCount()
{
int number;
Console.Write("How many numbers would you like to use in playing the game (4-10)? ");
while (!int.TryParse(Console.ReadLine(), out number) || number < 4 || number > 10)
Console.WriteLine("You must pick a number between 4 and 10. Choose again.");
return number;
}
public static int GetGameDifficulty()
{
int difficulty = 0;
Console.Write("Choose a difficulty level (1=hard, 2=medium, 3=easy): ");
while (!int.TryParse(Console.ReadLine(), out difficulty) || difficulty < 1 || difficulty > 3)
Console.WriteLine("Incorrect entry: Please re-enter.");
return difficulty;
}
public static int[] GenerateRandomNumbers(int PCSize)
{
int eachNumber;
int[] randomNumber = new int[PCSize];
Random rnd = new Random();
Console.Write("PC number: ");
for (int i = 0; i < PCSize; i++)
{
eachNumber = rnd.Next(1, 5);
randomNumber[i] = eachNumber;
Console.Write(eachNumber);
}
Console.WriteLine();
return randomNumber;
}
public static int[] GetUserGuess(int userSize)
{
int number = 0;
int[] userGuess = new int[userSize];
for (int i = 0; i < userSize; i++)
{
Console.Write("Digit {0}: ", (i + 1));
while (!int.TryParse(Console.ReadLine(), out number) || number < 1 || number > 4)
Console.WriteLine("Invalid number!");
userGuess[i] = number;
}
Console.WriteLine();
Console.Write("Your guess: ");
for (int i = 0; i < userSize; i++)
{
Console.Write(userGuess[i] + " ");
}
Console.WriteLine();
return userGuess;
}
public static int CountHits(int[] PCArray, int[] userArray)
{
int hits = 0;
for (int i = 0; i < PCArray.Length; i++)
{
if (PCArray[i] == userArray[i])
hits++;
}
Console.WriteLine("Results: {0} Hit(s), {1} Miss(es)", hits, PCArray.Length - hits);
return hits;
}
}
It does a few more validations and it even actually lets you play again! ;)

drawing a simple hangman design linked to my incorrect guesses in c#

I wish to display a simple hangman design using characters from the keyboard based on the incorrect answers that a user inputs. These incorrect answers will draw a new piece to the hangman each time although i am unsure how to do this. I have made my program function to cycle through 10 guesses before displaying the right answer and looping back to a new word.
The question i am asking is i do not know how to make a visual representation of a hangman in c# and how to link this to my existing code to only draw specific parts of the hangman based on the incorrect guesses. How do i do this?
The code is below.
namespace ConsoleApplication9
{
class Program
{
static string RandomWord()
{
Random rnd = new Random();
int response = rnd.Next(1, 4);
string randWord = "";
switch (response)
{
case 1:
randWord = "dog";
break;
case 2:
randWord = "robot";
break;
case 3:
randWord = "fish";
break;
case 4:
randWord = "continue";
break;
}
return randWord;
}
static void Main(string[] args)
{
string value = "";
int count = 0;
int gameLoop = 0;
string inData;
Console.WriteLine("Welcome to Hangman here is the first word");
do
{
count = 0;
value = RandomWord();
char[] newValue = new char[value.Length];
for (int i = 0; i < newValue.Length; i++)
{
newValue[i] = '_';
}
for (int i = 0; i < newValue.Length; i++)
{
Console.Write(newValue[i] + " ");
}
do
{
count++;
Console.Write("\n\nPlease enter your guess : ");
char input = (Console.ReadLine().ToCharArray()[0]);
for (int i = 0; i < value.Length; i++)
{
if (value[i] == input)
{
newValue[i] = input;
}
}
for (int x = 0; x < newValue.Length; x++)
{
Console.Write(newValue[x] + " ");
}
string s = (value);
string t = new string(newValue);
int c = string.Compare(s, t);
if (c == 0)
{
count = 10;
Console.WriteLine("\n\nCongratulations you guessed the word {0}", value);
}
} while (count < 10);
string Wrong = (value);
string Wrong2 = new string(newValue);
int gameOver = string.Compare(Wrong, Wrong2);
if (gameOver != 0)
{
Console.WriteLine("\n\nGame Over! the correct word was {0}", value);
}
Console.WriteLine("Would you like to go again? if so press 1 or 0 to exit");
inData = Console.ReadLine();
gameLoop = Convert.ToInt32(inData);
}
while (gameLoop == 1);
}
}
}
I am not quite sure how you plan to draw the hangman using ASCII art, but you could create a string array containing the 10 "pictures" as strings and then showing the corresponding one when appropriate.
You can create an array like so:
var pictures = new[]{":-)", ":-|", ":-(", "x.x", etc. };
and then
count++;
// display it here
Console.WriteLine(pictures[count]);
Console.Write("\n\nPlease enter your guess : ");

Categories

Resources