Save the Adventure — JavaScript

Record the hero in Mas Bayu's save book with localStorage and JSON: 12 levels of saving, loading, defaults and data migration.

What the levels ask

  1. Save the hero object to localStorage under the key "hero". Storage only accepts strings, so turn the object into JSON first.
  2. A "hero" save already exists. Write muat() (load) so it returns the hero OBJECT (not a string).
  3. Now both at once. The machine calls the "simpan" (save) function, RELOADS the cartridge (variables in memory are gone, storage stays), then muat() must return the same hero. The starter code already uses localStorage; all that's missing is the JSON conversion from levels 1 and 2.
  4. Storage is empty. muat() must return the default hero { nama: "Piksel", koin: 0, x: 0, y: 0 } when getItem gives null.
  5. The old save only has nama (name) and koin (coins). muat() must fill in the missing fields from DEFAULT: the result is { nama: "Piksel", koin: 12, x: 0, y: 0 }.
  6. tambahKoin(5) (add coins): read the hero from storage, add 5 to koin, and save the WHOLE hero again. No other field may go missing.
  7. simpanPengaturan(p) (save settings) stores the settings under the key "pengaturan" (JSON). The "hero" key must not change.
  8. hapusSimpanan() (delete save) removes only the "hero" key; "pengaturan" stays. Overwriting with "" is not deleting.
  9. Save in the v2 format: { versi: 2, data: hero } under the key "hero", so a future reader knows the format.
  10. Storage holds an old save (no version, just nama and koin). muat() must return the complete hero (defaults for missing fields) AND rewrite storage in the v2 format.
  11. Storage has several keys. daftarSlot() (list slots) returns an array of the key names that start with "slot:", sorted: ["slot:1", "slot:2"].
  12. The "hero" storage holds broken JSON. muat() must: try to parse inside try/catch → if that fails or gives null, use DEFAULT; accept both v1 and v2; fill in the defaults; rewrite as v2; return the hero. Then after a reload, muat() again must give the same hero from the new v2 save.