summaryrefslogtreecommitdiff
path: root/src/simulation/game.js
blob: f0c4815014ba48c288187f82b83f6b743e5c4c78 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
'use strict';


import { random_choice, apply } from '../util.js';
import { senses } from './senses.js';
import { actions } from './actions.js';
import { lattice_rules } from './lattice_rules.js';
import { validity } from './validity.js';


function is_wall(size, x, y) {
  return (
    x === 0 || x === size-1 ||
    y === 0 || y === size-1
  );
}
function is_corner(size, x, y) {
  const subsize = Math.floor(size/3);
  return (
    (x < subsize || x >= 2*subsize) &&
    (y < subsize || y >= 2*subsize)
  );
}
function get_team(size, x, y) {
  const subsize = Math.floor(size/3);
  if (y < subsize) {
    return 0;
  } else if (x >= 2*subsize) {
    return 1;
  } else if (y >= 2*subsize) {
    return 2;
  } else if (x < subsize) {
    return 3;
  } else {
    return undefined;
  }
}

export function setup_board(size) {
  const lattice = [...Array(size)]
    .map(() => [...Array(size)])
    .map((row, y) => row.map((_, x) => {
      if (is_wall(size, x, y)) {
        return { type: 'immutable', flags: {} };
      } else if (is_corner(size, x, y)) {
        return { type: 'immutable', flags: {} };
      } else {
        const team = get_team(size, x, y);
        return { type: 'empty', flags: { team } };
      }
    }));
  return lattice;
}


export function create_world(size, teams) {
  const lattice = setup_board(size);

  const agents = teams.reduce(
    (agents, team, team_num) => {
      const team_cells = lattice.map((row, y) => row.map((cell, x) => [x, y, cell])).flat()
        // only check cells with the right team
        .filter(([x, y, cell]) => cell.type === 'empty' && cell.flags.team === team_num)
      return agents.concat(team.reduce(
        (acc, agent) => {
          const available_cells = team_cells.filter(([x, y, cell]) => acc.reduce(
            (occupied, a) => occupied && ((a.x !== x) || (a.y !== y)),
            true
          ))
          const [x, y, ..._] = random_choice(available_cells);
          const orientation = random_choice([ 'n', 'e', 's', 'w' ]);
          return [...acc, {...agent, x, y, flags: { ...agent.flags, orientation } }];
        },
        []
      ));
    },
    []
  ).flat();

  return { lattice, lattice_rules, agents, actions, senses, validity };
};


// team structure:
// {
//   agents
//   genome
// }


//export function create_team(size, genome_size, n_internal) {
//  const n_input = senses.reduce((acc, sense) => acc + sense.size, 0);
//  const n_output = senses.reduce((acc, sense) => acc + sense.size, 0);
//  const genome = apply(
//    s => mut_genome_insert(
//    ),
//  );
//}