summaryrefslogtreecommitdiff
path: root/src/simulation/game.js
diff options
context:
space:
mode:
Diffstat (limited to 'src/simulation/game.js')
-rw-r--r--src/simulation/game.js45
1 files changed, 40 insertions, 5 deletions
diff --git a/src/simulation/game.js b/src/simulation/game.js
index ac6b2fd..7a3119d 100644
--- a/src/simulation/game.js
+++ b/src/simulation/game.js
@@ -1,7 +1,7 @@
'use strict';
-import { random_choice, apply } from '../util.js';
+import { random_choice, apply, shuffle } from '../util.js';
import { senses } from './senses.js';
import { actions } from './actions.js';
import { lattice_rules } from './lattice_rules.js';
@@ -21,7 +21,7 @@ function is_corner(size, x, y) {
(y < subsize || y >= 2*subsize)
);
}
-function get_team(size, x, y) {
+export function get_team(size, x, y) {
const subsize = Math.floor(size/3);
if (y < subsize) {
return 0;
@@ -95,7 +95,7 @@ export function create_agent(genome, n_internal) {
return {
id: agent_id++, // !!!! side effect !!!!
net: parse_genome,
- state: [...Array(n_internal)].map(_ => (2*Math.random()) - 1),
+ state: [...Array(n_internal)].map(_ => (2*Math.random()) - 1),
}
}
@@ -106,11 +106,11 @@ const MAX_MUTATIONS = 15;
export function create_team(size, genome_size, n_internal) {
- const [..._, genome] = apply(
+ const genome = apply(
s => mut_genome_insert(s, 4, Math.random(), Math.random(), Math.random()),
genome_size,
[N_INPUT, n_internal, N_OUTPUT, []],
- );
+ ).slice(-1)[0];
const agents = [...Array(size)].map(_ => create_agent(genome, n_internal));
return { agents, genome, score: 0 };
@@ -148,4 +148,39 @@ export function child_team(team, keep=Math.floor(team.size/2)) {
export function create_game(teams, team_indices) {
+ const world = create_world(999, team_indices.map(i => teams[i].agents));
+ return { world, team_indices, time: 0 };
+}
+
+
+export function step_game(game) {
+ return {
+ ...game,
+ world: world_update(world, postprocess),
+ time: game.time + 1,
+ };
+}
+
+
+function score(lattice, team_num) {
+ const size = lattice.length;
+
+ // count number of flags in the team's area
+ return lattice
+ .map((row, y) => row.map((cell, x) => [x, y, cell]))
+ .flat()
+ .filter(([x, y, cell]) => get_team(size, x, y) === team_num && cell.type === 'flag')
+ .length;
+}
+
+export function finish_game(teams, game) {
+ const scores = [0, 1, 2, 3].map(t => score(game.world.lattice, t));
+ return game.team_indices.reduce(
+ (acc, idx, i) => {
+ const team = teams[idx];
+ acc.splice(idx, 1, {...team, score: team.score + scores[i]});
+ return acc;
+ },
+ teams,
+ );
}