-
Notifications
You must be signed in to change notification settings - Fork 79
/
Brain.js
110 lines (86 loc) · 2.86 KB
/
Brain.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
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
99
100
101
102
103
104
105
106
107
108
109
110
class AIAction {
constructor(isJump, holdTime, xDirection) {
this.isJump = isJump;
this.holdTime = holdTime;//number between 0 and 1
this.xDirection = xDirection;
}
clone() {
return new AIAction(this.isJump, this.holdTime, this.xDirection);
}
mutate() {
this.holdTime += random(-0.3,0.3);
this.holdTime = constrain(this.holdTime,0.1,1);
}
}
// let jumpChance = 0; //the chance that a random action is a jump
let jumpChance = 0.5; //the chance that a random action is a jump
let chanceOfFullJump = 0.2;
// let chanceOfFullJump = 0.2;
class Brain {
constructor(size, randomiseInstructions = true) {
this.instructions = [];
this.currentInstructionNumber = 0;
if (randomiseInstructions)
this.randomize(size);
this.parentReachedBestLevelAtActionNo = 0;
}
randomize(size) {
for (let i = 0; i < size; i++) {
this.instructions[i] = this.getRandomAction();
}
}
getRandomAction() {
let isJump = false;
if (random() > jumpChance) {
isJump = true;
}
let holdTime = random(0.1, 1);
if(random()<chanceOfFullJump){
holdTime = 1;
}
let directions = [-1, -1, -1, 0, 1, 1, 1]
let xDirection = random(directions)
return new AIAction(isJump, holdTime, xDirection)
}
getNextAction() {
if(this.currentInstructionNumber >= this.instructions.length){
return null;
}
this.currentInstructionNumber += 1;
return this.instructions[this.currentInstructionNumber - 1];
}
clone() {
let clone = new Brain(this.size, false);
clone.instructions = [];
for (let i = 0; i < this.instructions.length; i++) {
clone.instructions.push(this.instructions[i].clone())
}
return clone;
}
mutate() {
let mutationRate = 0.1;
let chanceOfNewInstruction = 0.02;
for (let i = this.parentReachedBestLevelAtActionNo; i < this.instructions.length; i++) {
if (random() < chanceOfNewInstruction) {
this.instructions[i] = this.getRandomAction()
} else if (random() < mutationRate) {
this.instructions[i].mutate();
}
}
}
mutateActionNumber(actionNumber){
// let mutationRate = 0.1;
actionNumber -=1; // this is done because im a bad programmer
let chanceOfNewInstruction = 0.2;
if (random() < chanceOfNewInstruction) {
this.instructions[actionNumber] = this.getRandomAction()
} else{
this.instructions[actionNumber].mutate();
}
}
increaseMoves(increaseMovesBy){
for(var i = 0 ; i< increaseMovesBy ;i++){
this.instructions.push(this.getRandomAction());
}
}
}