示例#1
0
        // Saves the game by removing the player's data from the old file and adding the player back to the file
        public static void SaveGame(Player player, Difficulty diff)
        {
            // Format of each playerDataString: NAME|ID|SCORE|WIN|LOSS|PLAYS|DIFF

            string        oldFile    = File.ReadAllText(GameFile);                                                        // Read the game file
            List <string> allPlayers = oldFile.Split(",").ToList();                                                       // List all of the players

            allPlayers.RemoveAll(x => x.Equals(""));                                                                      // Get rid of any blank cells from the split method

            allPlayers.Remove(allPlayers.Where(x => x.Contains(player.ID)).First());                                      // Remove the specific player from the file based on ID.  Removes old player info.

            allPlayers.Add($"{player.Name}|{player.ID}|{player.Score}|{player.Win}|{player.Loss}|{player.Plays}|{diff}"); // Add the player back to the file

            StringBuilder newFile = new StringBuilder();

            // Put the , delimeter back
            for (int i = 0; i < allPlayers.Count; i++)
            {
                allPlayers[i] += ",";
                newFile.Append(allPlayers[i]);
            }

            File.WriteAllText(GameFile, newFile.ToString());

            Fancy.Write("\n=== Data saved ===\n", 100, color: ConsoleColor.Green);
        }
        // If the user's input is valid, determine if the number is too high or too low.
        public void HighOrLow(int guess)
        {
            // If the guess is in bounds, take a guess away.
            if (guess >= MinGuess && guess <= MaxGuess)
            {
                Player.Guesses--;

                if (guess == CorrectNumber)
                {
                    Fancy.Write(
                        "\n  *******************\n" +
                        "        You Win!\n" +
                        "  *******************\n", 5, color: ConsoleColor.Magenta);
                    Player.Won = true;
                }
                else if (guess > CorrectNumber)
                {
                    Fancy.Write("\tToo High", "\n", 60, pause: 250, afterPause: 0);
                }
                else if (guess < CorrectNumber)
                {
                    Fancy.Write("\tToo Low", "\n", 60, pause: 250, afterPause: 0);
                }
            }
            else
            {
                Fancy.Write($"\tOut of bounds!  Your guess should be between {MinGuess} and {MaxGuess}\n");
            }
        }
 // Checks the user input against a bunch of if statements and redirects to the method that is needed
 public void EvaluateGuess(string guess, out bool invalidGuess)
 {
     if (guess == "rules")
     {
         invalidGuess = false;
         throw new NotImplementedException();
     }
     else if (guess == "settings")
     {
         invalidGuess = false;
         throw new NotImplementedException();
     }
     else                // The guess is a number
     {
         try
         {
             HighOrLow(Convert.ToInt32(guess));
             invalidGuess = false;
         }
         catch (FormatException)
         {
             Fancy.Write("\tYou need to guess a number...\n", 30, afterPause: 250, color: ConsoleColor.Yellow);
             invalidGuess = true;
         }
     }
 }
        // This method fulfills step 2 and step 3 of the assignment on Page 218.
        // Writes the user input to file and then prints the text back from the file.
        public static void BackUpAssignment(int difficulty)
        {
            // This little bit satifies the assignment (I think)
            Fancy.Write("\n\nFor the sake of the assignment, Writing your number to a file...  ", 40, afterPause: 750);
            File.WriteAllText(GameIO.AssignmentFile, difficulty.ToString());
            Fancy.Write("Done\n", $"Printing the contents of the file below:\n{File.ReadAllText(GameIO.AssignmentFile)}", 20, 25, pause: 250, afterPause: 250);

            Fancy.Write("\n\nNow...", " time to put way too much work into this assignment!\n\n", pause: 500, afterPause: 500);
        }
        public void Play()
        {
            // Reset Variables
            Player.Guesses = 7;
            Player.Won     = false;

            // Add difficulty multiplier later
            CorrectNumber = rand.Next(MinGuess, MaxGuess);
            Console.WriteLine(CorrectNumber);

            // As long as the player has guesses, guess.
            while (Player.Guesses > 0 && !Player.Won)
            {
                // Determine if the guess is actually valid.
                bool invalidGuess = true;
                while (invalidGuess)
                {
                    Fancy.Write($"\t({Player.Guesses} left) Guess a number: ");
                    string guess = Fancy.ReadLine(ConsoleColor.Green).ToLower();
                    EvaluateGuess(guess, out invalidGuess);
                }
            }

            if (Player.Won)
            {
                Fancy.Write("\nWell done!  ", afterPause: 500);

                Player.Won = true;
                Player.Win++;
                Player.Plays++;

                int scoreGained = (Player.Guesses + 1) * (int)Diff;
                Fancy.Write("You got " + scoreGained + " points!  Here are your stats:\n", color: ConsoleColor.Green);
                Player.Score += scoreGained;
            }
            else
            {
                Fancy.Write("\nYou lost.  It happens to the best of us....\n", afterPause: 750);

                Player.Won = false;
                Player.Loss++;
                Player.Plays++;
            }

            Player.ShowAll();

            GameIO.SaveGame(Player, Diff);            // Save the game.

            Fancy.Write("\nDo you want to play again? (y or n) ");
            string answer = Fancy.ReadLine(ConsoleColor.Cyan);

            if (answer != "y")
            {
                Player.IsPlaying = false;
            }
        }
 // Show all of the information associated with the player.
 public void ShowAll()
 {
     Fancy.Write(String.Format("\n" +
                               "==================================\n" +
                               $"\tName:         {Name}\n" +
                               $"\tScore:        {Score}\n" +
                               $"\tWins:         {Win}\n" +
                               $"\tLosses:       {Loss}\n" +
                               $"\tGames Played: {Plays}\n" +
                               $"\tWin Rate:     {((double) Win / Plays) * 100:F2}%\n" +
                               $"\tLoss Rate:    {((double) Loss / Plays) * 100:F2}%\n" +
                               "==================================\n", 5));
 }
        static void Main(string[] args)
        {
            Fancy.Write("This program uses classes to ", "divide", " a number by 2.\n", pause: 500, afterPause: 500);

            DivBy2 div = new DivBy2();

            bool loop = true;

            while (loop)
            {
                // Get the number to be divided by 2
                int  number    = 0;
                bool badNumber = true;
                while (badNumber)
                {
                    Fancy.Write("Enter an integer:  ");
                    try
                    {
                        number    = Convert.ToInt32(Console.ReadLine());
                        badNumber = false;
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("Enter an INTEGER, please...\n");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Unknown exception: {0}", e.GetType());
                    }
                }

                Fancy.Write(String.Format("\n\tYour number divided by Two: {0} / 2 = ", number));
                div.Divide(number);

                Fancy.Write("This is how many times we could divide " + number + " Before we are less than 2: ");

                // Getting the out parameter
                int divisions = 0;
                div.Divide(number, out divisions);

                Fancy.Write(divisions + "\n", 100, afterPause: 250);

                // Go again?
                Fancy.Write("\nDo you want to enter a new number? (y or n) ", 5);
                string loopChoice = Console.ReadLine();
                if (loopChoice != "y")
                {
                    loop = false;
                }
            }
        }
        // Peice of code that returns the difficulty that the player chooses.
        public static int AskForDifficulty()
        {
            try
            {
                int difficulty = Convert.ToInt32(Fancy.ReadLine(ConsoleColor.Red));
                if (difficulty <= 0 || difficulty >= 5)
                {
                    throw new FormatException();
                }

                Fancy.Write("Going with " + SetDifficulty(difficulty) + " difficulty");
                return(difficulty);
            }
            catch (FormatException)
            {
                int difficulty = 2;
                Fancy.Write("That is not a valid difficulty.  I'll just set you at " + SetDifficulty(difficulty) + "\n", afterPause: 500);
                return(difficulty);
            }
        }
 public void Divide(int num)
 {
     Fancy.Write(num / 2 + "\n\n", afterPause: 1200);
 }
        static void Main(string[] args)
        {
            // Get the player's name
            Fancy.Write("Welcome to Guess a Game.", "  What is your name: ", 15, 30, pause: 500);
            string playerName = Console.ReadLine();

            string[] playerDataArray;       // Will store the information from saved game file.

            Player player;

            // If there is already a text file, find the player's information
            int        difficulty;          // The number representation of the difficulty
            Difficulty difficultyName;      // The actual difficulty

            // Determine if this player is new or has played before.  If the player is a returning player, get the player's data from the game file.
            bool newPlayer;

            if (File.Exists(GameIO.GameFile))
            {
                playerDataArray = GameIO.GetPlayerData(playerName, out newPlayer);                                // Get the data relating to that player from the game file.
            }
            else
            {
                playerDataArray = null;
                newPlayer       = true;
            }

            // If the player is not new load their information from the game file.
            if (!newPlayer)
            {
                Fancy.Write("Welcome back, " + playerDataArray[0], 50, afterPause: 500, color: ConsoleColor.Magenta);
                try
                {
                    Fancy.Write($"\nYour previous Difficulty: {playerDataArray[6]} | Choose Game Difficulty (1-4): ", 20);

                    // If the player has a save game, instantiate the information.
                    player = new Player(
                        name:       playerDataArray[0],
                        id:         playerDataArray[1],
                        totalScore: Convert.ToInt64(playerDataArray[2]),
                        win:        Convert.ToInt32(playerDataArray[3]),
                        loss:       Convert.ToInt32(playerDataArray[4]),
                        plays:      Convert.ToInt32(playerDataArray[5]));
                }
                catch (IndexOutOfRangeException)
                {
                    Fancy.Write(
                        ".  You closed the program prematurely: no saved data.\n" +
                        "To save your game history, be sure to exit the program as intended.\n", afterPause: 500, color: ConsoleColor.Yellow);
                    Fancy.Write("Choose Game Difficulty: ", 20);
                    player = new Player(playerName);
                }
                catch (Exception ex)
                {
                    Fancy.Write($"\n\n\tI don't know what went wrong!!\n\t{ex.GetType()}\n\t{ex.Message}\n\n");
                    player = new Player(playerName);
                }

                difficulty     = AskForDifficulty();
                difficultyName = SetDifficulty(difficulty);
            }
            else                // No text file? make one with the player's information.
            {
                player = new Player(playerName);

                Fancy.Write("What difficulty do you want to play? (1, 2, 3, 4): ", 20);
                difficulty     = AskForDifficulty();
                difficultyName = SetDifficulty(difficulty);

                GameIO.AddPlayerToFile(player, difficultyName);

                Tutorial();
            }

            BackUpAssignment(difficulty);

            GuessANumber game = new GuessANumber(player, difficultyName);

            // Game Loop, stops when the player doesn't want to play anymore.
            while (player.IsPlaying)
            {
                game.Play();
            }

            Fancy.Write("\n\nThanks for playing!", 75, color: ConsoleColor.Green);
            Console.Read();
        }
 // Just some text that shows the tutorial.
 public static void Tutorial()
 {
     Fancy.Write("\n\n\tThe objective of this game is to guess the number I am thinking of.\n\t", 35, afterPause: 1000);
     // Fancy.Write("You can change the difficulty to increase your score for winning.\n\t", 35, afterPause: 750);
     // Fancy.Write("To do so, type 'settings' whenever you are prompted to type a number.\n", 35, afterPause: 750);
 }