summaryrefslogtreecommitdiff
path: root/src/world/cell.js
blob: 6e013c6b0ec5550d4e70d1dfe3e871b943f518cd (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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
'use strict';

export function cells_update(cells, update_rules) {
  return cells
    .map((row, y) => row.map((cell, x) => [x, y, cell.type]))
    .flat()
    .reduce((acc, [x, y, type]) => [...acc, update_rules[type](cells, x, y)], [])
    .filter(x => x !== undefined)
}


export function cells_valid(cells, proposal) {
  if (!proposal.world_updates) { return true; }
  return proposal.world_updates.reduce(
    (acc, update) => {
      const valid = 
        (update.x >= 0 && update.x < cells[0].length) &&
        (update.y >= 0 && update.y < cells.length) &&
        (cells[update.y][update.x].type == update.from)
        return valid && acc;
    },
    true
  );
}


export function cells_apply(cells, proposals) {
  return proposals.reduce(
    (acc, prop) => {
      const change = (prop.world_updates || []).reduce(
        (acc_, update) => {
          const cell = acc_[update.y][update.x];
          if (update.to) { cell.type = update.to; }
          if (update.flags) {
            cell.flags = cell.flags || {}
            for (let k of Object.keys(update.flags)) {
              cell.flags[k] = update.flags[k];
            }
          }
          return acc_
        },
        [...acc]
      );
      return change;
    },
    [...cells].map(row => row.map(cell => ({ ...cell, flags: {}, })))
  );
}