Completed
Push — master ( 3d2e4b...6ed0aa )
by Andres
43s
created

angular.service(ꞌsavegameꞌ)   C

Complexity

Conditions 8
Paths 36

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 8
c 3
b 0
f 0
nc 36
dl 0
loc 27
rs 5.3846
nop 0
1
/* globals versionCompare, atob, btoa */
2
/**
3
 savegame
4
 Service that handles save/load related functions.
5
6
 @namespace Services
7
 */
8
'use strict';
9
10
angular
11
  .module('game')
12
  .service('savegame', ['$state',
13
    'state',
14
    'data',
15
    function ($state, state, data) {
16
      this.initSave = function () {
17
        state.player = {};
18
        this.versionControl();
19
        state.init();
20
        $state.go('matter');
21
      };
22
23
      this.save = function () {
24
        localStorage.setItem('player', JSON.stringify(state.player));
25
      };
26
27
      this.load = function () {
28
        try {
29
          let storedPlayer = localStorage.getItem('player');
30
          if (!storedPlayer) {
31
            this.initSave();
32
          } else {
33
            state.player = JSON.parse(storedPlayer);
34
            this.versionControl();
35
          }
36
        } catch (err) {
37
          alert('Error loading savegame, reset forced.');
38
          this.initSave();
39
        }
40
      };
41
42
      this.versionControl = function () {
43
        // delete saves older than this version
44
        if (state.player.version && versionCompare(state.player.version, '2.1.0') < 0) {
45
          state.player = {};
46
        }
47
        // we merge the properties of the player with the start player to
48
        // avoid undefined errors with new properties
49
        state.player = angular.merge({}, data.start_player, state.player);
50
        // append an id if it doesn't exist
51
        if (!state.player.id) {
52
          state.player.id = Math.random().toString().substring(3);
53
        }
54
55
        // old saves may have outdated reactions, which crash the game
56
        for(let react in state.player.reactions){
57
          if(typeof data.reactions[react] === 'undefined'){
58
            delete state.player.reactions[react];
59
          }
60
        }
61
62
        // old saves may have outdated resources, which crash the game
63
        for(let resource in state.player.resources){
64
          if(typeof data.resources[resource] === 'undefined'){
65
            delete state.player.resources[resource];
66
          }
67
        }
68
      };
69
    }
70
  ]);
71