2021-Save Game

From TRCCompSci - AQA Computer Science
Revision as of 10:12, 4 September 2020 by Admin (talk | contribs) (Game Save File)
Jump to: navigation, search

Game Save File

Player One,0,5,5,2
Player Two,0,5,5,2
6
#,#,~,~, , , ,~, , , , , ,#,#,#,~,~
1,Baron,0
2,Baron,1
1,LESS,3
1,LESS,15
2,LESS,2
1,Serf,17
2,LESS,13

The first 2 lines are the player 1 and player 2 data

The third line is the grid size

The fourth line is each tile (notice the space between the comma, space is for a field)

From this point, each line is a piece. This should be the player, followed by the type of piece and finally the hex number.

Issue

The program is able to load a save game file, however it is not possible to save a game.

Solution

We need to create a new method in the program class for save game. The basic structure of the method is:

        public static void SaveGame(Player p1, Player p2, HexGrid g)
        {
            Console.Write("Enter the name of the file to save: ");
            string fileName = Console.ReadLine();
            try
            {
                Console.WriteLine("File saved");
            }
            catch
            {
                Console.WriteLine("File not saved");
            }
        }

The SaveGame method above accepts parameters for Player1, Player2, and the grid. The code above will ask the user to enter a filename to use for the game save. I have included a try & catch because writing to files will often cause issues, so it is good error handling.

StreamWriter

Now, inside the try block but before the 'Console.WriteLine()' add the following to create and open the file:

using (StreamWriter myStream = new StreamWriter(fileName))
{
}

Player Data

Now inside the { } of the using statement add this:

string playerData = p1.GetName() + ";" + p1.GetVPs() + ";" + p1.GetFuel() + ";" + p1.GetLumber() + ";" + p1.GetPiecesInSupply();
myStream.WriteLine(playerData);

This will create a string of the data from Player1, the stream will have a 'WriteLine' which is used to write to the file.

Repeat the code above for Player2 (obviously change p1 to p2).