2020 - Save a running simulation

From TRCCompSci - AQA Computer Science
Revision as of 13:02, 16 December 2019 by Admin (talk | contribs) (Example)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Issue

There is currently no option to save the simulation.

Solution

We could use serialization to save the simulation, alternatively we could use a text or binary file to record the details of the simulation. The binary or text file could then be used to recreate the simulation to the point in which we saved.

Serialization would be better, because we could serialize it in one go and de-serialize it in one go.

Example

Add the following to the top of the skeleton program:

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

Now before every Class declaration in the skeleton code add this:

[Serializable]

Now we can create a new method for the 'Save' option, this should go into the 'Simulation' class:

        public void SaveSim(Simulation data)
        {
            Stream streamwrite = File.Create("mygame.bin");
            BinaryFormatter binarywrite = new BinaryFormatter();
            binarywrite.Serialize(streamwrite, data);
            streamwrite.Close();
        }

Now to load the simulation, we need to pass it the current simulation:

        public void LoadSim(Simulation data)
        {
            Stream streamread = File.OpenRead("mygame.bin");
            BinaryFormatter binaryread = new BinaryFormatter();
            data = (Simulation)binaryread.Deserialize(streamread);
            streamread.Close();
            simulationSettlement = data.simulationSettlement;
            noOfCompanies = data.noOfCompanies;
            fuelCostPerUnit = data.fuelCostPerUnit;
            baseCostForDelivery = data.baseCostForDelivery;
            companies = data.companies;
        }

Once the data is deserialized we need to use the values to change the current ones.

Finally in the 'Run' method we need to add the options to 'SaveSim' and 'LoadSim':

                        case "S":
                            SaveSim(this);
                            break;
                        case "L":
                            LoadSim(this);
                            break;

Finally add the options to the 'DisplayMenu' method:

Console.WriteLine("S. Save Simulation");
Console.WriteLine("L. Load Simulation");