2020 - Save a running simulation

From TRCCompSci - AQA Computer Science
Revision as of 12:18, 16 December 2019 by Admin (talk | contribs) (Created page with "=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...")
(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:

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