-
Notifications
You must be signed in to change notification settings - Fork 0
/
PlayerAI.js
70 lines (50 loc) · 1.88 KB
/
PlayerAI.js
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
class PlayerAI {
constructor(game, options = {}) {
const {any} = options;
this.game = game;
this.network = new NeuralNetwork(5 * 4 + 1, 32, 4);
this.network.activationFunction = new ActivationFunction(softmax, dsoftmax);
this.network.learningRate = 0.2;
this.game.on("init", e => {
this.player = this.game.map.getPlayer();
});
}
generateInputLayer() {
/*
[
distanceToExit,
up, left, down, right
]
*/
const mappings = [undefined, Exit, Arrow, Wall, Monster];
const input = [];
const distanceToExit = 1 - this.game.map.search(this.player.position, Exit).path.length / this.game.map.search(this.game.map.spawn, Exit).path.length;
input.push(distanceToExit);
// console.log(distanceToExit);
for(const direction of DIRECTIONS) {
const object = this.game.map.getObject(this.player.position.copy().add(direction));
input.push(...mappings.map(e => !object && !e || e && object instanceof e ? 1 : 0));
}
// for(const direction of DIRECTIONS) {
// const object = this.game.map.getObject(this.player.position.copy().add(direction));
// input.push(mappings.findIndex(e => !object && !e || e && object instanceof e) / mappings.length);
// }
return input;
}
predictMovement() {
const input = this.generateInputLayer();
const output = this.network.predict(input);
// console.log(output);
return DIRECTIONS[output.indexOf(Math.max(...output))];
}
mutate(network) {
this.network = network.copy();
this.network.mutate(val => val + randomGaussian(-this.network.learningRate, this.network.learningRate));
}
calculateFitness() {
let fitness = 1 - this.game.map.search(this.player.position, Exit).path.length / this.game.map.search(this.game.map.spawn, Exit).path.length;
if(this.died) fitness -= fitness * 0.4;
if(fitness < 0) fitness = 0;
return fitness;
}
}