简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM