C# mastermind game - c#

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! ;)

Related

Input from user to array and Display in Console in C#

I am a Beginner in C# and I was wondering what I got wrong with this code.
I want the user to input the amount of numbers
Then an array with that amount gets created
Then finally I want to display all the numbers in the array.
The Code:
using System;
using System.Threading;
using System.Collections.Generic;
namespace Console_Project_alpha
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the amount of numbers: ");
int amount = Convert.ToInt32(Console.ReadLine());
int[] numbers = new int[amount];
string nth = "";
for( int i = 1; i <= amount ; i++)
{
if(i == 1)
{
nth = i + "st";
}
else if( i == 2)
{
nth = i + "nd";
}
else if( i == 3)
{
nth = i + "rd";
}else{
nth = i + "th";
}
Console.Write("\nEnter " + nth + " Number:");
int num = Convert.ToInt32(Console.ReadLine());
for(int j = 0; j <= numbers.Length; j++)
{
numbers[j] = num;
}
}
System.Console.WriteLine(numbers);
}
}
}
Any help is highly appreciated. Thanks in advance
In your code you all time overwriting the same value to all index in
array.
If you want to display values from array in console just iterate after array
Properly worked example based on your code:
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the amount of numbers: ");
int amount = Convert.ToInt32(Console.ReadLine());
int[] numbers = new int[amount];
string nth = "";
int index = 0;
for (int i = 1; i <= amount; i++)
{
if (i == 1)
{
nth = i + "st";
}
else if (i == 2)
{
nth = i + "nd";
}
else if (i == 3)
{
nth = i + "rd";
}
else
{
nth = i + "th";
}
Console.Write("\nEnter " + nth + " Number:");
int num = Convert.ToInt32(Console.ReadLine());
numbers[index] = num;
index++;
}
for (int i = 0; i <= numbers.Length - 1; i++)
{
Console.WriteLine(numbers[i]);
}
Console.ReadLine();
}
}

Why Input string was not in a correct format and exception was unhandled

I am getting an error while taking array input from the user.
static void Main(string[] args)
{
int[] arrSum = new int[] { };
Console.WriteLine("Enter the array Size:\t");
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the array elements of {0} as Array Size:\n",n);
for (int i = 0; i < n; i++)
{
arrSum[i] = int.TryParse(Console.ReadLine(), out arrSum[]);
}
Console.WriteLine("Enter the number whose sum you want to find:\n");
int j = Convert.ToInt32(Console.ReadLine());
ArraySum(arrSum,n,j);
}
public static int ArraySum(int[] arr, int key, int n)
{
for (int i = 0; i < arr.Length; i++)
{
int first = arr[i];
for (int k = i+1; k < arr.Length; k++)
{
int second = arr[k];
while (first + second == key)
{
Console.WriteLine("The numbers whose sum is {0}" + key + "are:\n" + first + second);
}
if (first + second != key)
{
return -1;
}
else
{
return 1;
}
}
}
return 0;
}
To take array size and elements and the number whose sum we need to compare among the given array elements from the user as input and return the possible pairs whose sum is equal to the given number.
I am not sure if I met the same problem as you, but I modified your code as following. At first I created a safe console readline method for integer that there is no exception thrown if an invalid integer is entered:
private static int GetIntFromInput()
{
while (true)
{
string value = Console.ReadLine();
if (!int.TryParse(value, out int parsedInt))
{
Console.WriteLine("Invalid integer! Retry or Ctrl+C to abort program...");
continue;
}
return parsedInt;
}
}
Then I modified your first method as following:
static void Main(string[] args)
{
Console.WriteLine("Enter the array Size:\t");
int n = GetIntFromInput();
if (n <= 0)
{
Console.WriteLine("Array has to be at least of size 1...");
return;
}
Console.WriteLine("Enter the array elements of {0} as Array Size:\n", n);
var arrSum = new int[n];
for (int i = 0; i < n; i++)
{
int newInt = GetIntFromInput();
arrSum[i] = newInt;
}
Console.WriteLine("Enter the number whose sum you want to find:\n");
int j = Convert.ToInt32(Console.ReadLine());
ArraySum(arrSum, n, j);
}
With this my tests had been successful. Please note, that I did not replace the last Convert.ToInt32 for j.
As a note, please always verify user input as far as possible for not throwing exceptions. If anytime you will check anything not correctly it will crash sometime for sure...
have a great day!
I just have modified your array input code lines, pretty much straight forward. You can use int.TryParse as well just in case you wish to have a check
Console.WriteLine("Enter the array Size:\t");
int n = Convert.ToInt32(Console.ReadLine());
int[] arrSum = new int[n];
Console.WriteLine("Enter the array elements of {0} as Array Size:\n",n);
for(int i = 0;i<n;i++){
arrSum[i]= Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Enter the number whose sum you want to find:\n");
int j = Convert.ToInt32(Console.ReadLine());
ArraySum(arrSum,n,j);

do/while and if/else problems

I have to put in an extra "test score" to get an answer.
(i.e i have to enter six 5' to get 25)
I can't get the do/while & if statements to loop if there is more than one number outside the "while" range. I haven't been coding for very long, a couple weeks so try and break down the answers. Thanks for the help!
Here is my code
Console.Write("Enter the number of tests: ");
int n = int.Parse(Console.ReadLine());
int[] scores = new int[n];
Console.WriteLine("----------------------------------------");
Console.WriteLine("Please enter the test scores");
int i;
do
{
i = Convert.ToInt32(Console.ReadLine());
if (i < 0)
{
Console.WriteLine("Please enter a value greater than 0");
}
if (i > 100)
{
Console.WriteLine("Please enter a value less than 100");
}
} while (i < 0 || i > 100);
for (i = 0; i < n; i++)
{
scores[i] = int.Parse(Console.ReadLine());
}
int sum = 0;
foreach (int d in scores)
{
sum += d;
}
Console.WriteLine("The sum of all the scores is {0}",sum);
Console.ReadLine();
Put the do block that does the input validation inside the for loop:
Console.Write("Enter the number of tests: ");
int n = int.Parse(Console.ReadLine());
int[] scores = new int[n];
Console.WriteLine("----------------------------------------");
Console.WriteLine("Please enter the test scores");
for (int i = 0; i < n; i++)
{
int input = -1;
do
{
input = Convert.ToInt32(Console.ReadLine());
if (input < 0)
{
Console.WriteLine("Please enter a value greater than 0");
}
else if (input > 100)
{
Console.WriteLine("Please enter a value less than 100");
}
} while (input < 0 || input > 100);
scores[i] = input;
}
int sum = 0;
foreach (int d in scores)
{
sum += d;
}
Console.WriteLine("The sum of all the scores is {0}", sum);
Console.ReadLine();
n is the number of tests, meaning the amount of scores counter i should be the same as the amount of tests. Also prefer Convert.ToInt32 to int.Parse since it throws exceptions in case it isn't able to make the conversion.
Console.Write("Enter the number of tests: ");
int n = Convert.ToInt32(Console.ReadLine());
int sum = 0, i = 0, score = 0;
int[] scores = new int[n];
Console.WriteLine("----------------------------------------");
do {
Console.WriteLine("Please enter the test score #" + (i + 1));
score = Convert.ToInt32(Console.ReadLine());
if (score < 0) {
Console.WriteLine("Please enter a value greater or equal to 0");
}
else if (score > 100)
{
Console.WriteLine("Please enter a value less or equal to 100");
}
else {
scores[i] = score;
i++;
}
} while (i < n);
foreach (int d in scores) {
sum += d;
}
Console.WriteLine("The sum of all the scores is {0}", sum);
Console.ReadLine();
Just for the potential learning opportunity, and and not as a direct answer to your question, here is the way I would do this exercise:
Console.Write("Enter the number of tests: ");
int n = int.Parse(Console.ReadLine());
Console.WriteLine("----------------------------------------");
Console.WriteLine("Please enter the test scores");
int AskForInteger()
{
while (true)
{
if (int.TryParse(Console.ReadLine(), out int i) && i >= 0 && i <= 100)
{
return i;
}
Console.WriteLine("Please enter a value between 0 and 100 inclusive");
}
}
int[] scores =
Enumerable
.Range(0, n)
.Select(x => AskForInteger())
.ToArray();
Console.WriteLine("The sum of all the scores is {0}", scores.Sum());
Console.ReadLine();
There are two options:
a. Start at 1 rather than 0 --> for (i = 1; i < n; i++)
b. Lower the value of n by 1 --> for (i = 1; i < n-1; i++)
Good luck

Getting an error about variable not existing in current context

I have written out a program that declares an array of 10 integers, takes input from the user and puts them in the array and then accepts out parameters for the highest value, lowest value, sum of all values, and the average.
The main method displays all the stats. I don't know why, but I get the error
k does not exist in the current context - line 51 column 5
when I have previously declared it before that given line. Any help would be appreciated.
using System;
namespace IntegerStatistics
{
class Program
{
static void Main()
{
Console.Clear();
// Declaring variables
int[] userArray = FillArray();
int ArrayHighest = 0;
int ArrayLowest = 0;
int ArraySum = 0;
int ArrayAverage = 0;
Calculations(userArray, out ArrayHighest, out ArrayLowest, out ArraySum, out ArrayAverage);
Console.WriteLine("The lowest value in the array is {0}, while the highest is {1}.", ArrayLowest, ArrayHighest);
Console.WriteLine("The array has a sum of {0} and averages out to {1}.", ArraySum, ArrayAverage);
Console.ReadLine();
}
private static int[] FillArray()
{
int[] intArray = new int[10];
int numbersEntered = 0;
int intTemp = 0;
string strTemp = "";
for(int k = 0; k < 10; ++k)
{
Console.WriteLine("Enter a whole number or 999 to quit: ");
strTemp = Console.ReadLine();
while(!int.TryParse(strTemp, out intTemp))
{
Console.WriteLine("Input was not in the correct format");
Console.Write("Please enter a valid number: ");
strTemp = Console.ReadLine();
}
}
if(intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
{
k = 10;
}
Array.Resize(ref intArray, numbersEntered);
return intArray;
}
private static void Calculations(int[] intArray, out int Highest, out int Lowest, out int intSum, out int average)
{
intSum = 0;
Array.Sort(intArray);
Lowest = intArray[0];
Array.Reverse(intArray);
Highest = intArray[0];
Array.Reverse(intArray);
for(int k = 0; k < intArray.Length; ++k)
{
intSum += intArray[k];
}
average = intSum / intArray.Length;
}
}
}
The line I'm specifically having issues with is:
if (intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
{
k = 10;
}
I think you meant to place the if-else block inside the for-loop.
Since you want to check if the input number is 999 for each iteration, you could write your for-loop like this:
for(int k = 0; k < 10; ++k)
{
Console.WriteLine("Enter a whole number or 999 to quit: ");
strTemp = Console.ReadLine();
while(!int.TryParse(strTemp, out intTemp))
{
Console.WriteLine("Input was not in the correct format");
Console.Write("Please enter a valid number: ");
strTemp = Console.ReadLine();
}
if(intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
{
k = 10;
}
}
The loop variable k goes out of scope when the code leaves the for loop. So, you can use variable k only within the loop.
So, you need to move your if-else inside your for loop. Change your FillArray() method to
private static int[] FillArray()
{
int[] intArray = new int[10];
int numbersEntered = 0;
int intTemp = 0;
string strTemp = "";
for (int k = 0; k < 10; ++k)
{
Console.WriteLine("Enter a whole number or 999 to quit: ");
strTemp = Console.ReadLine();
while (!int.TryParse(strTemp, out intTemp))
{
Console.WriteLine("Input was not in the correct format");
Console.Write("Please enter a valid number: ");
strTemp = Console.ReadLine();
}
if (intTemp != 999)
{
intArray[k] = intTemp;
++numbersEntered;
}
else
break;
}
Array.Resize(ref intArray, numbersEntered);
return intArray;
}
Also, I'd suggest changing ArrayAverage to double type. e.g. 2, 3 => average 2.5
double ArrayAverage = 0; //average need not be whole number
Additionally, with Linq you can shorten your Calculations method as
//using System.Linq;
private static void Calculations(int[] intArray, out int Highest, out int Lowest, out int intSum, out double average)
{
Lowest = intArray.Min();
Highest = intArray.Max();
intSum = intArray.Sum();
average = intArray.Average();
}

Get highest number from inputs

I need a programm, where I can type in numbers and in the end it gives me the highest number.
Why doesn't it work like that? What do I need to change?
public class Program
{
public static void Main()
{
double[] input = new double[12];
for (int i = 1; i <= 12; i++)
{
Console.Write(" Type in {0} number:", i);
input = [Convert.ToInt32(Console.ReadLine())];
}
Console.WriteLine("The highest number is {0}", input.Max(element => Math.Abs(element)));
Console.ReadKey();
}
}
You need to make it so its converting to double and also setting to each individual element
input[i] = Convert.ToDouble(Console.ReadLine());
and then change this because arrray starts at 0
for (int i = 0; i <= 11; i++)
As #Ashad Shanto said you must use Convert.ToDouble and you must use input[i] instead of input. So your code should look like:
public class Program
{
public static void Main()
{
double[] input = new double[12];
for (int i = 0; i < 12; i++)
{
Console.Write(" Type in {0} number:", i);
input[i] = [Convert.ToDouble(Console.ReadLine())];
}
Console.WriteLine("The highest number is {0}", input.Max(element => Math.Abs(element)));
Console.ReadKey();
}
}
Is the requirement to have a Double or Int? Anyways, you can just simple store the highest number each time a new number is entered by doing a simple comparison.
public static void Main()
{
var currentNumber = 0;
for (var i = 1; i <= 12; i++)
{
Console.Write(" Type in {0} number: ", i);
var number = Console.ReadLine();
int result;
if (int.TryParse(number, out result))
{
if (currentNumber < result)
{
currentNumber = result;
}
}
}
Console.WriteLine("The highest number is {0}", currentNumber);
Console.ReadKey();
}
As #artokai mentioned you don't need to store all entered numbers.
Try the following:
double heighest = Double.MinValue;
for (int i = 0; i < 12; i++)
{
Console.Write(" Type in {0} number:", i);
double input = (Convert.ToDouble(Console.ReadLine());
if (input > heighest)
heighest = input
}
Console.WriteLine("The highest number is {0}", highest);

Categories

Resources