summaryrefslogtreecommitdiff
path: root/src/systems/undo.js
blob: 086d6b4bc7ea8f15524f1d7c3f4e9e3a0222f5e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
game.system.Undo = (entitiesGrid, logicSystem, gridSystem) => {
  const states = [];

  const update = (elapsedTime, entities, changedIds) => {
    if (changedIds.size) {
      const state = {};
      for (let id in entities) {
        if (entities[id].hasComponent("gridPosition")) {
          state[id] = JSON.parse(JSON.stringify(entities[id].components));
        }
      }
      states.push(state);
    }
    return new Set();
  };

  const undo = (entities) => {
    let state = states.slice(0, -1).pop();
    if (states.length > 1) {
      states.pop();
    }
    for (let id in state) {
      for (let componentName in state[id]) {
        entities[id].addComponent({name: componentName, ...state[id][componentName]});
      }
    }
    gridSystem.update(0, entities, new Set());
    logicSystem.parseRules(entities);
  };

  return { update, undo };
};