/// <summary>
        /// A method to serialize the game repository
        /// </summary>
        /// <param name="filename">A string representation of the output file name</param>
        /// <param name="savedGameRepository">The saved game repository</param>
        public void SerializeRepository(string fileName, SavedGameRepository savedGameRepository)
        {
            string filePath = ObtainPathToDatFile(fileName);

            using (Stream stream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                using (DeflateStream compressedStream = new DeflateStream(stream, CompressionMode.Compress))
                {
                    BinaryFormatter bFormatter = new BinaryFormatter();
                    bFormatter.Serialize(compressedStream, savedGameRepository);
                }
            }
        }
        /// <summary>
        /// A method to deserialize the game repository
        /// </summary>
        /// <param name="filename">A string representation of the input file name</param>
        /// <returns>A SavedGameRepository object</returns>
        public SavedGameRepository DeserializeRepository(string fileName)
        {
            SavedGameRepository savedGameRepository = new SavedGameRepository();

            string filePath = ObtainPathToDatFile(fileName);

            using (Stream stream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                using (DeflateStream decompressStream = new DeflateStream(stream, CompressionMode.Decompress))
                {
                    BinaryFormatter bFormatter = new BinaryFormatter();
                    if (stream.Length > 0)
                    {
                        savedGameRepository = (SavedGameRepository)bFormatter.Deserialize(decompressStream);
                    }
                }
            }

            return(savedGameRepository);
        }
Exemple #3
0
        /// <summary>
        /// This method runs the game logic
        /// </summary>
        public void Run()
        {
            // Create an instance of the DisplayScreens class
            DisplayScreens screens = new DisplayScreens();

            // Create an instance of the SavedGameRepository
            SavedGameRepository savedGameRepository = new SavedGameRepository();

            // Create an instance of the serializer to pull and save the list of games
            Serializer serializer = new Serializer();

            // Download the saved games into the repository
            savedGameRepository = serializer.DeserializeRepository("SavedGames.dat");

            // Run the splash screen
            screens.SplashScreen();

            Console.Clear();

            // This boolean determines if the main loop continues
            bool continueGame = true;

            // This string records the user's command
            string command = "";

            do
            {
                // Display the main menu
                screens.MainMenuScreen();

                // Wait for the user's command
                command = Console.ReadLine();

                // Ensure case insensitivity
                command = command.ToUpper();

                // Remove starting and trailing empty spaces
                command = command.Trim();

                #region New or Load Command
                if (command == "1" || command == "NEW" || command == "2" || command == "LOAD")
                {
                    // Create the list of saved games for passing to the play method
                    List <SudokuConsoleGame> savedGames = new List <SudokuConsoleGame>();
                    savedGames = savedGameRepository.SavedGames;

                    Console.Clear();

                    // The users game
                    SudokuConsoleGame game = new SudokuConsoleGame();

                    if (command == "1" || command == "NEW")
                    {
                        string userName;
                        SudokuConsoleGame.Difficulty difficulty = new SudokuConsoleGame.Difficulty();

                        screens.CreateNewGameScreen(out userName, out difficulty);
                        Console.Clear();

                        // Create the game
                        game = new SudokuConsoleGame(userName, difficulty);
                    }
                    else if (command == "2" || command == "LOAD")
                    {
                        screens.LoadGameScreen(savedGameRepository, ref game);
                        Console.Clear();
                    }

                    if (game != null)
                    {
                        game.Play(ref savedGames);
                    }
                    Console.Clear();
                }
                #endregion

                #region Delete Command
                else if (command == "3" || command == "DELETE")
                {
                    Console.Clear();
                    screens.DeleteGameScreen(savedGameRepository);
                    Console.Clear();
                }
                #endregion

                #region Lead Command
                else if (command == "4" || command == "LEAD")
                {
                    Console.Clear();
                    screens.LeaderboardScreen(savedGameRepository);
                    Console.Clear();
                }
                #endregion

                #region Instruct Command
                else if (command == "5" || command == "INSTRUCT")
                {
                    Console.Clear();
                    screens.InstructionScreen();
                    Console.Clear();
                }
                #endregion

                #region Exit Command
                else if (command == "6" || command == "EXIT")
                {
                    Console.WriteLine("\n\t\t         Thanks for playing!\n\n\t\t         (Press Enter to Exit)");
                    Console.ReadLine();
                    continueGame = false;
                }
                #endregion

                else
                {
                    // If the user fails to enter a valid command
                    Console.WriteLine("\n\t\t         Please enter a valid command.\n\n\t\t         (Press Enter to Continue)");
                    Console.ReadLine();
                    Console.Clear();
                }
            }while (continueGame == true);
        }
Exemple #4
0
        /// <summary>
        /// This method runs the game
        /// </summary>
        /// <param name="savedGames">Intakes the List of SudokuConsoleGames</param>
        public void Play(ref List <SudokuConsoleGame> savedGames)
        {
            #region Play Fields
            // Determines if the user keeps playing
            bool _continue = true;

            // This field stores the user's command
            string _command;
            #endregion

            // Instantiate a screen instance
            DisplayScreens screen = new DisplayScreens();

            // Instantiate a game stopwatch, this is used to calculate the score
            Stopwatch gameStopWatch = new Stopwatch();

            // Start the stopwatch
            gameStopWatch.Start();

            #region The Game Loop
            // The game loop
            do
            {
                // Load the game screen
                screen.GameScreen(ElementList, ElementSB);

                // Intake the users command
                _command = Console.ReadLine();

                // Convert user command to uppercase so its case insensitive
                _command = _command.ToUpper();

                // Remove starting and trailing empty spaces
                _command = _command.Trim();

                #region Enter or Delete Command
                // These commands allow the user to enter and delete a value
                // The code to select the x and y coordinate is the same for each value
                // The initial choice from the user determines if this is an update or delete
                if (_command.Equals("1") || _command.Equals("ENTER") || _command.Equals("2") || _command.Equals("DELETE")) // If user command equals 1 or ENTER
                {
                    // bool to test if the x coordinate is valid
                    bool _continueX = true;
                    do
                    {
                        Console.Write("\n\tEnter the X Coordinate> ");
                        string _xValue = Console.ReadLine();
                        if (_xValue.TryParse())
                        {
                            int _xInt = Convert.ToInt32(_xValue);

                            if (_xInt > 0 && _xInt < 10)
                            {
                                bool _continueY = true;
                                do
                                {
                                    Console.Write("\n\tEnter the Y Coordinate> ");
                                    string _yValue = Console.ReadLine();

                                    if (_yValue.TryParse())
                                    {
                                        int _yInt = Convert.ToInt32(_yValue);

                                        if (_yInt > 0 && _yInt < 10)
                                        {
                                            // The indexer to change the string
                                            int indexer;

                                            // The indexer to access the element from the element string
                                            int indexer2;

                                            // The x value will be transformed to a
                                            int a = 0;

                                            // The y value will be transformed to b
                                            int b = 0;

                                            // The b2 value is required to index the element
                                            int b2 = 0;

                                            // Transform x into a
                                            for (int i = 1; i < _xInt; i++)
                                            {
                                                a = a + 2;
                                            }

                                            // Transform y int b
                                            for (int i = 1; i < _yInt; i++)
                                            {
                                                b = b + 18;
                                            }

                                            // Transform y int b2
                                            for (int i = 1; i < _yInt; i++)
                                            {
                                                b2 = b2 + 9;
                                            }

                                            // Add a and b to ascertain the indexer
                                            indexer = a + b;

                                            // Add _xInt and b2 to ascertain indexer2
                                            indexer2 = _xInt + b2 - 1;

                                            if (ElementList[indexer2].DisplayHint == false)
                                            {
                                                bool _userEntryInvalid = true;

                                                do
                                                {
                                                    if (_command.Equals("1") || _command.Equals("ENTER"))
                                                    {
                                                        Console.Write("\n\tEnter a number from 1 through 9> ");
                                                        string _userEntry = Console.ReadLine();

                                                        if (_userEntry.TryParse())
                                                        {
                                                            int _userInt = Convert.ToInt32(_userEntry);

                                                            if (_userInt > 0 && _userInt < 10)
                                                            {
                                                                ElementSB.Remove(indexer, 1);
                                                                ElementSB.Insert(indexer, _userEntry);
                                                                Console.Clear();
                                                                _continueX        = false;
                                                                _continueY        = false;
                                                                _userEntryInvalid = false;
                                                            }
                                                            else
                                                            {
                                                                InvalidCoordinate();
                                                            }
                                                        }
                                                        else
                                                        {
                                                            InvalidCoordinate();
                                                        }
                                                    }
                                                    else
                                                    {
                                                        ElementSB.Remove(indexer, 1);
                                                        ElementSB.Insert(indexer, "_");
                                                        Console.Clear();
                                                        _continueX        = false;
                                                        _continueY        = false;
                                                        _userEntryInvalid = false;
                                                    }
                                                }while (_userEntryInvalid);
                                            }
                                            else
                                            {
                                                Console.WriteLine("\n\tThis value is a hint provided by the system and cannot be changed.");
                                                Console.WriteLine("\tPlease try again.\n\n\t\t         (Press Enter to Continue)");
                                                Console.ReadLine();
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            InvalidCoordinate();
                                        }
                                    }
                                }while (_continueY == true);
                            }
                            else
                            {
                                InvalidCoordinate();
                            }
                        }
                        else
                        {
                            InvalidCommand();
                        }
                    }while (_continueX == true);
                }
                #endregion

                #region Reset Command
                // This command allows the user to reset the board
                else if (_command.Equals("3") || _command.Equals("RESET")) // If user command equals 3 or RESET
                {
                    ClearSolution(ElementSB, ElementList);
                    Console.Clear();
                }
                #endregion

                #region Check Command
                // This command allows the user to check his answer
                else if (_command.Equals("4") || _command.Equals("CHECK")) // If user command equals 4 or CHECK
                {
                    // Stop the gameStopWatch
                    gameStopWatch.Stop();

                    // Save the elapsed seconds to ticks
                    Ticks = Ticks + gameStopWatch.Elapsed.Seconds;

                    // Reset the gameStopWatch
                    gameStopWatch.Reset();

                    // Determine if the user wins!
                    if (SolutionString.Equals(ElementSB.ToString()))
                    {
                        // Calculate the score
                        Score = CalculateSolution();

                        // Save the score
                        if (savedGames.Contains(this))
                        {
                            // If the game was previously in the list, remove the old reference
                            savedGames.Remove(this);
                        }

                        // Add the game to the list and sort by DateCreated property
                        savedGames.Add(this);
                        //savedGames.Sort();

                        // Create the saved game repository
                        SavedGameRepository savedGameRepository = new SavedGameRepository();

                        // Set the saved game repository list equal to savedGames
                        savedGameRepository.SavedGames = savedGames;

                        // Save the game
                        Serializer serialize = new Serializer();
                        serialize.SerializeRepository("SavedGames.dat", savedGameRepository);

                        Console.Clear();
                        screen.VictoryScreen(this);
                        _continue = false;
                    }
                    else
                    {
                        // If the difficulty level is easy or medium the game provides hints
                        if (GameDifficulty == Difficulty.EASY || GameDifficulty == Difficulty.MEDIUM)
                        {
                            // If the solution is not correct the keeps the correct responses from the user
                            Console.WriteLine("\n\tClose but no cigar!\n\n\t\t         (Press Enter to Continue)");
                            Console.ReadLine();
                            Console.WriteLine("\tHere, I'll help you out and show you were you're right.\n\n\t\t         (Press Enter to Continue)");
                            Console.ReadLine();

                            if (GameDifficulty == Difficulty.EASY)
                            {
                                // Turns the claimant's solution to a string
                                string _assistanceString = ElementSB.ToString();

                                // Turns the solution to a char array
                                char[] _solutionArray = SolutionString.ToCharArray();

                                // Turns the user's solution to a char array
                                char[] _assistanceArray = _assistanceString.ToCharArray();

                                // If the value in the user's char array is incorrect its converted to "_"
                                for (int i = 0; i < _assistanceString.Length; i++)
                                {
                                    if (_solutionArray[i] != _assistanceArray[i])
                                    {
                                        _assistanceArray[i] = '_';
                                    }
                                }

                                // Clears the user's response
                                ElementSB.Clear();

                                // Refills the element string builder with the corrected array
                                foreach (char a in _assistanceArray)
                                {
                                    ElementSB.Append(a);
                                }

                                // Add 100 Demerits
                                Demerits = Demerits + 200;

                                Console.Clear();
                            }
                            else if (GameDifficulty == Difficulty.MEDIUM)
                            {
                                int _correctAnswers = 0;

                                for (int i = 0; i < SudokuSolution.Count; i++)
                                {
                                    int j = i * 2;

                                    if (ElementSB.ToString().TryParse())
                                    {
                                        if (Convert.ToInt32(ElementSB.ToString().ElementAt(j)) == SudokuSolution.ElementAt(i))
                                        {
                                            ++_correctAnswers;
                                        }
                                    }
                                }

                                Console.WriteLine("\n\t{0} of your answers are correct.\n\n\tPlease try again.\n\n\t\t         (Press Enter to Continue");

                                // Add 10 Demerits
                                Demerits = Demerits + 100;

                                Console.Clear();
                            }
                        }

                        // If the difficulty level is hard the game does not provide hints
                        else if (GameDifficulty == Difficulty.HARD)
                        {
                            Console.WriteLine("\n\tClose but no cigar!\n\tTry again!\n\n\t\t         (Press Enter to Continue)");
                            Console.ReadLine();

                            Console.Clear();
                        }

                        // Restart the gameStopWatch
                        gameStopWatch.Start();
                    }
                }
                #endregion

                #region Save Command
                // This command allows the user to save the game
                else if (_command.Equals("5") || _command.Equals("SAVE")) // If user command equals 5 or SAVE
                {
                    // Stop the gameStopWatch
                    gameStopWatch.Stop();

                    // Save the elapsed seconds to ticks
                    Ticks = Ticks + gameStopWatch.Elapsed.Seconds;

                    // Reset the gameStopWatch
                    gameStopWatch.Reset();

                    if (savedGames.Contains(this))
                    {
                        // If the game was previously in the list, remove the old reference
                        savedGames.Remove(this);
                    }

                    // Add the game to the list and sort by DateCreated property
                    savedGames.Add(this);
                    //savedGames.Sort();

                    // Create the saved game repository
                    SavedGameRepository savedGameRepository = new SavedGameRepository();

                    // Set the saved game repository list equal to savedGames
                    savedGameRepository.SavedGames = savedGames;

                    // Save the game
                    Serializer serialize = new Serializer();
                    serialize.SerializeRepository("SavedGames.dat", savedGameRepository);

                    Console.WriteLine("\n\tYour game has been saved.\n\n\t\t         (Press Enter to Continue)");
                    Console.ReadLine();
                    Console.Clear();

                    // Restart the gameStopWatch
                    gameStopWatch.Start();
                }
                #endregion

                #region Exit Command
                // This command allows the user to return to the main menu
                else if (_command.Equals("6") || _command.Equals("EXIT")) // If user command equals 6 of EXIT
                {
                    string exitGame = string.Empty;

                    Console.Write("\n\tPlease note that unsaved changes will be lost.\n\n\tDo you wish to return to the main menu?\n\n\tYes/No> ");

                    exitGame = Console.ReadLine();

                    // Ensure response is not case sensitive
                    exitGame = exitGame.ToUpper();

                    // Remove starting and trailing empty spaces
                    exitGame = exitGame.Trim();

                    if (exitGame.Equals("YES") || exitGame.Equals("Y"))
                    {
                        Console.WriteLine("\n\tReturning to main menu.\n\n\t\t   (Press Enter to Return to Main Menu)");
                        Console.ReadLine();
                        _continue = false;
                    }
                    else
                    {
                        Console.Clear();
                    }
                }
                #endregion

                else
                {
                    // If the user fails to enter a valid command
                    Console.WriteLine("\n\tPlease enter a valid command.\n\n\t\t         (Press Enter to Continue)");
                    Console.ReadLine();
                    Console.Clear();
                }
            }while (_continue == true);
            #endregion
        }