summaryrefslogtreecommitdiff
path: root/src/world/agent.js
blob: dbfdf5da397ca55539a1f8727ef10611f0d498c1 (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
49
50
51
52
53
54
55
56
'use strict';

import { sense_read } from './sense.js';
import { proposal_merge } from './proposal.js';


export function agent_decide(world, agent, senses, actions) {
  const inputs = senses.map(s => sense_read(world, agent, s)).flat();
  const [result, state] = agent.net.compute(inputs, agent.state);
  console.log(agent, result);

  const new_agent = { ...agent, state };
  const [proposals, _] = actions.reduce(
    ([proposals, result], action) => {
      const head = result.slice(0, action.size);
      const tail = result.slice(action.size);

      const props = action
        .propose(world, new_agent, head)
        .reduce(
          (acc, proposal) => proposal_merge(acc, proposal),
          proposals
        );

      return [props, tail];
    },
    [[], result]
  );

  return [new_agent, proposals];
}


function change_apply(agent, ch) {
  const { x, y, flags } = ch;
  return {
    ...agent, 
    x: (x || agent.x), y: (y || agent.y),
    flags: { ...agent.flags, ...flags },
  };
}


export function agent_apply(agent, proposals) {
  return proposals
    .filter(p => p.agent_changes)
    .reduce(
      (acc, p) => p.agent_changes
        .filter(ch => ch.agent_id === agent.id)
        .reduce(
          (acc_, ch) => change_apply(acc_, ch),
          acc
        ),
        agent
      );
}