summaryrefslogtreecommitdiff
path: root/src/systems/undo.js
blob: 29f5bec1c8428d4a877d60bbbc6e355ed813b992 (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
game.system.Undo = (entitiesGrid) => {
  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]});
      }
    }
  }

  return { update, undo };
}