This is the card I'm working with and I'm very confused to why the dealer isn't hitting when instructed to. I've rearranged my code tried different methods but it still doesn't seem to be working. If someone can help me solve this C# script I'd be very thankful.
using System;
using System.Collections.Generic;
public class MainClass
{
public static int PlayerTotal;
public static int DealerTotal;
static Random random = new Random();
public static List<int> cards = new List<int>();
public static List<int> hand = new List<int>();
public static List<int> DealerHand = new List<int>();
public static bool GameOver = false;
public static void Main (string[] args)
{
// Players hand gets created
for (int i = 2; i <= 11; i++)
{
cards.Add(i);
}
for (int i = 0; i < 2; i++)
{
int index = random.Next(cards.Count);
hand.Add(cards[index]);
}
foreach (int a in hand)
{
Console.WriteLine("{0}", a);
PlayerTotal = PlayerTotal + a;
if(PlayerTotal == 22 || PlayerTotal == 21)
{
Console.WriteLine("You won!");
GameOver = true;
}
}
Console.WriteLine("Your hand total is " + PlayerTotal);
// Dealer hand being created
for(int i = 0; i < 2; i++)
{
int index = random.Next(cards.Count);
DealerHand.Add(cards[index]);
}
foreach(int a in DealerHand)
{
Console.WriteLine("{0}", a);
DealerTotal = DealerTotal + a;
if(DealerTotal == 22 || DealerTotal == 21)
{
Console.WriteLine("The dealer won!");
GameOver = true;
}
}
Console.WriteLine("The dealer hand total is " + DealerTotal);
// Player choice to hit or stay
while (PlayerTotal < 21 && GameOver == false)
{
Console.WriteLine("Do you want to hit or stand? h/s");
string choice = Console.ReadLine();
if (choice == "h")
{
PlayerHit();
}
else if (choice == "s")
{
Console.WriteLine("You stood");
}
}
while (DealerTotal < 21 && GameOver == false )
{
if(DealerTotal <= 16)
{
DealerHit();
}
else
{
Console.WriteLine("The dealer stood");
}
}
}
public static void PlayerHit()
{
for (int i = 0; i < 1; i++)
{
int index = random.Next(cards.Count);
int hitCard = cards[index];
hand.Add(hitCard);
PlayerTotal = PlayerTotal + hitCard;
Console.WriteLine("You got a " + hitCard);
Console.WriteLine("Your new total is " + PlayerTotal);
if(PlayerTotal > 21)
{
Console.WriteLine("You lost!");
GameOver = true;
}
else if (PlayerTotal == 21)
{
Console.WriteLine("You won!");
GameOver = true;
}
}
}
public static void DealerHit()
{
for (int i = 0; i < 1; i++)
{
int index = random.Next(cards.Count);
int DealerHitCard = cards[index];
DealerHand.Add(DealerHitCard);
DealerTotal = DealerTotal + DealerHitCard;
int DealerHitCardNew = DealerHitCard;
Console.WriteLine("The dealer got a " + DealerHitCardNew);
Console.WriteLine("The dealers total is now " + DealerTotal);
if (DealerTotal > 21)
{
Console.WriteLine("You Won!");
GameOver = true;
}
else if (DealerTotal == 21)
{
Console.WriteLine("You Lost!");
GameOver = true;
}
}
}
}
Any help would be very appreciated. My school has set us homework that we have to create a sort of application, and i thought this would be fun to make.
This line here:
while(PlayerTotal < 21 && GameOver == false) {
That will only be true if you bust or get 21. If you stand, you will never exit this loop. Add a break to the stand option:
} else if(choice == "s"){
Console.WriteLine("You stood");
break;
}
Unfortunately, you have the same issue in the following loop:
while(DealerTotal < 21 && GameOver == false ) {
Add a break to the correct block to exit the loop when the dealer stands. Finally, you will need to add winning/losing logic after both the player and the dealer have stood.
Related
The snake head 0 does not move anywhere when Console.ReadKey() happens.
Here is the full code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleSnakeGame_ConsoleApp
{
internal class Program
{
public bool gameOver = true;
public int width = 20;
public int height = 20;
//HEAD POS
public int x, y;
//FRUIT POS
public int fruitX, fruitY;
public int score;
//bir kere basınca oraya gitmeni sağlayacak enum
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
eDirection dir; //enum class gibi çalışıyor enum'dan dir isimli bir object yarattık
static void Main(string[] args)
{
Program oyun = new Program();
oyun.Setup();
oyun.Draw();
oyun.Input();
oyun.Logic();
Console.ReadLine();
}
//Setting Up the MAP
public void Setup()
{
gameOver = false;
string a = "!!!!! SİMPLE SNAKE GAME !!!!!";
Console.WriteLine(gameOver.ToString() + " " + a, "{0}" + "{1}");
dir = eDirection.STOP;
x = width / 2;
y = height / 2;
Random rnd = new Random();
fruitX = rnd.Next(1, 19);
fruitY = rnd.Next(1, 19);
score = 0;
}
void Draw()
{
for (int j = 0; j < height; j++)
{
for (int i = 0; i < width; i++)
{
if (i == y && j == x)
{
Console.Write("0");
}
else if (i == fruitY && j == fruitX)
{
Console.Write("F");
}
else if (j > 0 && j < height - 1 && i > 0 && i < width - 1)
{
Console.Write(" ");
}
else
{
Console.Write("#");
}
}
Console.WriteLine();
}
Console.WriteLine();
}
void Input()
{
ConsoleKey key;
// Key is available - read it
key = Console.ReadKey(true).Key;
if (key == ConsoleKey.A)
{
dir = eDirection.LEFT;
}
else if (key == ConsoleKey.D)
{
dir = eDirection.RIGHT;
}
else if (key == ConsoleKey.W)
{
dir = eDirection.UP;
}
else if (key == ConsoleKey.S)
{
dir = eDirection.DOWN;
}
else if (key == ConsoleKey.X)
{
gameOver=true;
}
}
void Logic()
{
switch (dir)
{
case eDirection.LEFT:
x--;
break;
case eDirection.RIGHT:
x++;
break;
case eDirection.UP:
y--;
break;
case eDirection.DOWN:
y++;
break;
default:
break;
}
}
}
}
I guess the problem is Console.ReadKey() function here:
void Input()
{
ConsoleKey key;
// Key is available - read it
key = Console.ReadKey(true).Key;
if (key == ConsoleKey.A)
{
dir = eDirection.LEFT;
}
else if (key == ConsoleKey.D)
{
dir = eDirection.RIGHT;
}
else if (key == ConsoleKey.W)
{
dir = eDirection.UP;
}
else if (key == ConsoleKey.S)
{
dir = eDirection.DOWN;
}
else if (key == ConsoleKey.X)
{
gameOver=true;
}
}
However I do not know what to replace Console.ReadKey() with and how to do it.
Here is the OUTPUT:
You are correct about Console.ReadKey() being the problem as it is blocking and will pause the game until a key is pressed.
You will need to do something like this:
if (Console.KeyAvailable)
{
ConsoleKeyInfo key = Console.ReadKey(true);
// process key here
}
This way you are reading from the console without blocking until a key is pressed.
I'm trying to work on an app/small game that is about trying to guess the same number between 1-10 same as the program and win, but after that round you are supposed to be able to play again! My problem is that the program generates the same number everytime. I have looked through other threads on here and none of them seem to help or at least I cannot understand them. How can I fix this?
static void Main(string[] args)
{
Random random = new Random();
bool play = true;
int playnum = random.Next(1, 11);
while (play)
{
Console.Write("\n\tGuess number between 1-10 ");
int numb;
bool success = Int32.TryParse(Console.ReadLine(), out numb);
if (success)
{
if (numb < playnum)
{
Console.WriteLine(playnum);
Console.WriteLine("\tinput number " + numb + " too small, try again.");
}
if (numb > playnum)
{
Console.WriteLine(playnum);
Console.WriteLine("\tinput number " + numb + " too big, try again.");
}
if (numb == playnum)
{
Console.WriteLine(playnum);
Console.WriteLine("\tcongrats!");
bool LoopBreaker = true;
do
{
Console.WriteLine("continue or finish?");
string input = Console.ReadLine();
char CharFromTryPass = ' ';
bool TryparsResult = char.TryParse(input, out CharFromTryPass);
bool IsValidChar = (CharFromTryPass != 'A' && CharFromTryPass != 'F');
if (IsValidChar)
{
Console.WriteLine(" please write A or F!");
}
else if (TryparsResult)
{
if (CharFromTryPass == 'A')
{
Console.WriteLine("see you!");
play = false;
LoopBreaker = false;
}
if (CharFromTryPass == 'F')
{
play = true;
LoopBreaker = false;
}
}
} while (LoopBreaker);
Your code is a bit messy, you should brake it down to smaller methods. But basically you just need to generate a new number after the person guesses the correct one. So add this after the "congrats!" line.
playnum = random.Next(1, 11);
.
static void Main(string[] args)
{
Random random = new Random();
bool play = true;
int playnum = random.Next(1, 11);
while (play)
{
Console.Write("\n\tGuess number between 1-10 ");
int numb;
bool success = Int32.TryParse(Console.ReadLine(), out numb);
if (success)
{
if (numb < playnum)
{
Console.WriteLine(playnum);
Console.WriteLine("\tinput number " + numb + " too small, try again.");
}
if (numb > playnum)
{
Console.WriteLine(playnum);
Console.WriteLine("\tinput number " + numb + " too big, try again.");
}
if (numb == playnum)
{
Console.WriteLine(playnum);
Console.WriteLine("\tcongrats!");
playnum = random.Next(1, 11);
bool LoopBreaker = true;
do
{
Console.WriteLine("continue or finish?");
string input = Console.ReadLine();
char CharFromTryPass = ' ';
bool TryparsResult = char.TryParse(input, out CharFromTryPass);
bool IsValidChar = (CharFromTryPass != 'A' && CharFromTryPass != 'F');
if (IsValidChar)
{
Console.WriteLine(" please write A or F!");
}
else if (TryparsResult)
{
if (CharFromTryPass == 'A')
{
Console.WriteLine("see you!");
play = false;
LoopBreaker = false;
}
if (CharFromTryPass == 'F')
{
play = true;
LoopBreaker = false;
}
}
} while (LoopBreaker);
}
}
}
}
You cannot generate a new number because you call the random number only once in your code.
Put your int playnum = random.Next(1, 11); inside of your loop and it should be fine. As Nyssa already said, you may should use your debugger to understand what your code is doing wrong.
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!
{
static int[] location = { 0, 0 };
static int player = 0;
static void runGame()
{
int start = Convert.ToInt32(Console.ReadLine());
if (start == 1)
{
location1();
}
else if (start == 2)
{
location2();
}
else if (start == 3)
{
location3();
}
else if (start == 4)
{
location4();
}
}
static void swapPlayer()
{
if (player == 1)
{
player = 0;
}
else
{
player = 1;
}
}
static void location1()
{
Console.WriteLine(" Player " + (player + 1) + " , you are in the kitchen you can go to either \n1: Living room \n2: Bathroom ");
int input = int.Parse(Console.ReadLine());
if (input == 1) {
location[player] = 2;
start = 2;
swapPlayer();
location2();
}
else if (input == 2) {
location[player] = 3;
start = 3;
swapPlayer();
location3();
}
}
static void location2()
{
Console.WriteLine(" Player " + (player + 1) + " you are in the living room you can go to either \n1: Kitchen\n2: Bedroom ");
int input = int.Parse(Console.ReadLine());
if (input == 1) {
location[player] = 1;
start = 1;
swapPlayer();
location1();
}
else if (input == 2) {
location[player] = 4;
start = 4;
swapPlayer();
location4();
}
}
static void location3()
{
Console.WriteLine(" Player " + (player + 1) + " you are in the bathroom you can go to either \n1: Kitchen \n2: Bedroom ");
int input = int.Parse(Console.ReadLine());
if (input == 1)
{
location[player] = 1;
start = 1;
swapPlayer();
location1();
}
else if (input == 2)
{
location[player] = 4;
start = 4;
swapPlayer();
location4();
}
}
static void location4() {
Console.WriteLine(" Player " + (player + 1) + ", you are in the kitchen you can go to either \n1: Living room \n2: Bathroom ");
int input = int.Parse(Console.ReadLine());
if (input == 1)
{
location[player] = 1;
start = 1;
swapPlayer();
location2();
}
else if (input == 2)
{
location[player] = 4;
start = 4;
swapPlayer();
location3();
}
}
static void Main(string[] args)
{
Console.WriteLine("welcome , find the ghost and navigate through the house");
Console.Write("You are in the main hall way you can go to any of these rooms");
Console.Write(" kitchen, living room, bath room , bedroom");
Console.WriteLine("choose a room number 1 , 4 from the list ");
int start = Convert.ToInt32(Console.ReadLine());
bool play = true;
while (play== true)
{
runGame();
}
}
}
Here is the code behind a simple 2 player text adventure I am making , I was wondering where I have used the variable start in the runGame procedure how can i access that outside of the procedure , or is that not possible in which case do you have another solution on how I can get around this.
You can't, and that's the point of local variables: the world outside shouldn't care about their value (or even their existence)
If you want to access the vatiable from multiple methods, you'll have to elevate it to a (in this case static) class member:
static int[] location = { 0, 0 };
static int player = 0;
static int start;
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! ;)