-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenetic-algorithm.js
More file actions
271 lines (224 loc) · 8.22 KB
/
genetic-algorithm.js
File metadata and controls
271 lines (224 loc) · 8.22 KB
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
function GeneticAlgorithm(runnerInstance) {
function AiPlayer(brain, indexOfPlayer) {
this.index = indexOfPlayer;
this.gamePlayer = runnerInstance.players[indexOfPlayer];
this.brain = brain;
this.isPressingJump = false;
this.isPressingDuck = false;
this.crashed = false;
this.jumpCount = 0;
this.duckCount = 0;
this.processJumpPressState = function (pressingJump) {
if (pressingJump) {
if (!this.isPressingJump) {
this.gamePlayer.onJumpKeyDown();
this.isPressingJump = true;
if (!this.isPressingDuck)
this.jumpCount++;
}
}
else {
if (this.isPressingJump) {
this.gamePlayer.onJumpKeyUp();
this.isPressingJump = false;
}
}
}
this.processDuckPressState = function (pressingDuck) {
if (pressingDuck) {
if (!this.isPressingDuck) {
this.gamePlayer.onDuckKeyDown();
this.isPressingDuck = true;
this.duckCount++;
}
}
else {
if (this.isPressingDuck) {
this.gamePlayer.onDuckKeyUp();
this.isPressingDuck = false;
}
}
}
}
const numberOfPlayersPerGeneration = 50;
const Neat = neataptic.Neat;
const Architect = neataptic.Architect;
const inputCount = 8;
const outputCount = 2;
const neat = new Neat(
inputCount,
outputCount,
null,
{
//mutation: methods.mutation.ALL,
popsize: numberOfPlayersPerGeneration,
mutationRate: 0.3,
elitism: 5,
network: new Architect.Random(
inputCount,
inputCount + outputCount,
outputCount
)
}
);
neat.generation = 1;
const aiPlayers = [];
const tableContainer = document.getElementById("table-container");
const generationNumberLabel = document.getElementById("generation-number-label");
function initTraining() {
addPlayersToGame();
startGeneration();
initGame();
}
function updateHTMLVisualization() {
generationNumberLabel.innerHTML = neat.generation;
tableContainer.innerHTML = getTableString();
}
function getTableString() {
function getOriginalScore(currentScore, jumpInfluence, duckInfluence) {
return currentScore - (jumpInfluence + duckInfluence);
}
function getYesOrNoStringFromBoolean(boolean) {
return boolean ? "Yes" : "No";
}
let tableHTML = "<table>";
tableHTML += "<tr>";
tableHTML += "<th>Index</th>";
tableHTML += "<th>Alive</th>";
tableHTML += "<th>Game Score</th>";
tableHTML += "<th>Bonus Score</th>";
tableHTML += "<th>Pressing Jump</th>";
tableHTML += "<th>Pressing Duck</th>";
tableHTML += "<th>Jump Count</th>";
tableHTML += "<th>Duck Count</th>";
tableHTML += "</tr>";
aiPlayers.forEach((aiPlayer, index) => {
const currentScore = aiPlayer.brain.score;
const jumpInfluence = getJumpInfluenceInScore(aiPlayer.jumpCount);
const duckInfluence = getJumpInfluenceInScore(aiPlayer.duckCount);
const changeInScore = jumpInfluence + duckInfluence;
const originalScore = currentScore - changeInScore;
const tableRowClass = aiPlayer.crashed ? "crashed" : "alive";
tableHTML += "<tr class=\"" + tableRowClass + "\">";
tableHTML += "<td>" + index + "</td>";
tableHTML += "<td>" + getYesOrNoStringFromBoolean(!aiPlayer.crashed) + "</td>";
tableHTML += "<td>" + Math.round(originalScore/100) + " </td>";
tableHTML += "<td>" + Math.round(changeInScore/10) + " </td>";
tableHTML += "<td>" + getYesOrNoStringFromBoolean(aiPlayer.isPressingJump) + "</td>";
tableHTML += "<td>" + getYesOrNoStringFromBoolean(aiPlayer.isPressingDuck) + "</td>";
tableHTML += "<td>" + aiPlayer.jumpCount + "</td>";
tableHTML += "<td>" + aiPlayer.duckCount + "</td>";
tableHTML += "</tr>";
});
tableHTML += "</table>";
return tableHTML;
}
function initGame() {
subscribeUpdateFunction();
startGame();
}
function subscribeUpdateFunction() {
runnerInstance.subscribe(onEachUpdate);
}
function addPlayersToGame() {
for (let i = 0; i < numberOfPlayersPerGeneration; ++i) {
runnerInstance.addPlayer();
}
}
function startGame() {
runnerInstance.playIntro();
}
function onEachUpdate(gameState) {
if (gameState.allPlayersCrashed) {
endGeneration();
return;
}
aiPlayers.forEach((aiPlayer) => {
processState(aiPlayer, gameState);
});
updateHTMLVisualization();
}
function processState(aiPlayer, gameState) {
const playerState = gameState.players[aiPlayer.index];
updateScore(aiPlayer, playerState.score);
aiPlayer.crashed = playerState.crashed;
if (playerState.crashed)
return;
const neuralNetworkInputs = getNeuralNetworkInputs(playerState, gameState);
movePlayer(aiPlayer, neuralNetworkInputs);
}
function updateScore(aiPlayer, gameScore) {
const jumpInfluence = getJumpInfluenceInScore(aiPlayer.jumpCount);
const duckInfluence = getDuckInfluenceInScore(aiPlayer.duckCount);
aiPlayer.brain.score = gameScore + jumpInfluence + duckInfluence;
}
function getJumpInfluenceInScore(jumpCount) {
return /*jumpCount * 10*/0;
}
function getDuckInfluenceInScore(duckCount) {
return /*duckCount * 20*/0;
}
function getNeuralNetworkInputs(playerState, gameState) {
return [
playerState.xPos,
playerState.yPos,
playerState.jumpVelocity,
gameState.velocity,
gameState.closestObstacle.yPos,
gameState.closestObstacle.xPos,
gameState.closestObstacle.width,
gameState.closestObstacle.height
];
}
function movePlayer(aiPlayer, neuralNetworkInputs) {
// activate the neural network (aka "where the magic happens")
const playerBrain = aiPlayer.brain;
const outputs = playerBrain.activate(neuralNetworkInputs).map(o => Math.round(o));
const jumpPressed = Math.round(outputs[0]);
const duckPressed = Math.round(outputs[1]);
aiPlayer.processJumpPressState(jumpPressed);
aiPlayer.processDuckPressState(duckPressed);
}
function startGeneration() {
const generationNumber = neat.generation;
console.log("Generation: " + generationNumber);
if (aiPlayers.length == 0) {
neat.population.forEach((brain, index) => {
aiPlayers.push(new AiPlayer(brain, index));
});
}
else {
neat.population.forEach((brain, index) => {
aiPlayers[index] = new AiPlayer(brain, index);
});
}
aiPlayers.forEach((aiPlayer) => {
aiPlayer.brain.score = 0;
});
}
function endGeneration () {
neat.sort();
/*this.onEndGeneration({
generation: this.neat.generation,
max: this.neat.getFittest().score,
avg: Math.round(this.neat.getAverage()),
min: this.neat.population[this.neat.popsize - 1].score
})*/
const newGeneration = [];
for (let i = 0; i < neat.elitism; i++) {
newGeneration.push(neat.population[i]);
}
for (let i = 0; i < neat.popsize - neat.elitism; i++) {
newGeneration.push(neat.getOffspring())
}
neat.population = newGeneration;
neat.mutate();
neat.generation++;
startGeneration();
restartGame();
}
function restartGame() {
runnerInstance.restart();
}
initTraining();
}