Today I learned a thing.

So, the typical method for implementing save games for web-based games is to store data in a cookie (or, more realistically, localStorage). This is pretty easy, especially with localStorage, with only one hitch - the data needs to be a string.

To solve this we use serialisation. The JSON.stringify() method takes an object and its properties and turns it into a string. This is pretty neat, and you can use JSON.parse() to reconstruct the object from the string later. Great stuff! It works really well.

However. There are two things which stop you being able to serialise, and I've realised after implementing my basic data structure for CivClicker 2 that I've done both of them.

The first is self-reference. If a part of the object references some other part of the object as a shortcut (which is how I initially implemented how cities and units were selected) then the stringify() method gives up and goes home. This is relatively simple to solve - just don't try to serialise those bits.

The second is a bit more insidious. Due to the nature of javascript encapsulation, the stringify() method can't serialise an object's methods. It will serialise the object, but will just ignore them. What I ended up with were units that couldn't move() or draw() or basically anything else, because I made the mistake of adding those methods to a Unit() constructor that all units were created from.

The next step is to work out the best way to get around this issue. LIkely I will do it by only storing the object-relevant data and passing the object into a moveUnit() function or equivalent, but there's a possibility that I might handle it by re-adding the methods once the data has been reserialised.

If you're a newbie javascript developer reading this, don't fall into the trap I did - if you have data structures you will want to serialise, don't add methods to the objects. Just keep your data in one place and handle everything else separately.