-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
352 lines (308 loc) · 11 KB
/
index.html
File metadata and controls
352 lines (308 loc) · 11 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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Evolution Simulator</title>
</head>
<body align="center">
<script src="EvolutionPlayer.js"></script>
<!-- Main canvas -->
<canvas
id="can"
width="850"
height="500"
style="border: 1px solid black"
></canvas>
<!-- Fitness Chart -->
<div class="chart-container" style="display: inline-block; border: 1px solid black">
<canvas id="chartCan" width="500" height="500"></canvas>
</div>
<script src="drawChart.js"></script>
<br/>
<p id="tickcounter" style="font-size: 1.5em; display: inline;"></p>
<p style="font-size: 1.5em; display: inline;" id="gencounter"> | Gen 0 | Avg Fitness = -1 | Mutation Rate = -1 | Success Rate = -1</p>
<div id="startdiv">
<input onmousemove="changePlayerLable(this)" type="range" id="playerrange" min="1" max="500" value="100"/><label id="playerrangelable" style="font-size: 1.5em; display: inline;"> 100 Players</label>
<input type="button" onclick="startSim()" value="START">
<input type="button" onclick="addWall()" value="Add Wall">
<input type="text" placeholder="Genlen" value="240" id="genlen" size="1">
</div>
<div id="simControlGroup" style="visibility: hidden">
<span>KEEP </span><input type="checkbox" onchange="changeKeepState(this.checked)">
<input type="button" onclick="resetSim()" value="RESET" style="margin-top: 0.25vh;">
<input type="range" value="30" min="1" max="750" onchange="changeSpeed(this.value)"/>
<span id="speedLabel" style="font-size: 1.5em"> 30 FPS</span>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js"></script>
<script>
//define canvas info
var c = document.getElementById("can");
var ctx = c.getContext("2d");
var chart = new EvolutionChart(document.getElementById("chartCan"));
//define evolution info
var target = { x: 800, y: 250, s: 50 };
var players = [];
var pw = 30;
var ph = 9;
var mutationrate = 0.002;
var gencounter = 0;
var playernum = 50;
var walls = [{ x: 450, y: 125, w: 20, h: 250 }];
var ticks = 0;
var inter;
var keepState = false;
var genlen = 240;
var winstrength = 15;
///THROUGHOUT SIM FUNCTIONS
function draw() {
c.width = c.width;
for (var p = 0; p < players.length; p++) {
//update player
let player = players[p];
player.setAccX(player.DNA[ticks][0]);
player.setAccY(player.DNA[ticks][1]);
player.angRect(player.XYtoAng(player.Xspeed, player.Yspeed), 0.75);
player.update();
// canvas boudnry collision check
if (
player.x > c.width - 10 ||
player.x < 0 ||
player.y > c.height ||
player.y < 0
) {
player.crash = true;
}
//wall collision check
for (wall of walls) {
if (
player.x + pw > wall.x &&
player.x < wall.x + wall.w &&
player.y > wall.y &&
player.y < wall.y + wall.h
) {
player.crash = true;
}
}
//Target collision check
if (
player.x > target.x - target.s / 2 &&
player.x < target.x + target.s / 2 &&
player.y > target.y - target.s / 2 &&
player.y < target.y + target.s / 2
) {
player.gotToTarget = true;
}
}
//Draw the target
ctx.fillRect(
target["x"] - target["s"] / 2,
target["y"] - target["s"] / 2,
target["s"],
target["s"]
);
//draw walls
for (wall of walls) {
ctx.fillRect(wall.x, wall.y, wall.w, wall.h);
}
ticks++;
if (ticks == genlen) {
ticks = 0;
genepool = [];
var fit;
var fitnesses = 0;
var succsses = 0;
//create genepool
for (player of players) {
fit = calcfitness(player);
fitnesses += fit;
if (player.gotToTarget) succsses += 1;
for (var i = 0; i < fit * fit; i++) {
genepool.push(player);
}
}
players.length = 0; //resets player array
//create new gen
for (var i = 0; i < playernum; i++) {
var randindex = parseInt(Math.random() * genepool.length);
players.push(mutate(genepool.splice(randindex, 1)[0]));
}
genepool.length = 0; //resets genepool array
gencounter++;
fitnesses /= playernum;
succsses /= playernum;
succsses *= 100;
//changes mutation rate based on the avg fitness
if (succsses > 0) {
mutationrate *= 0.95;
} else if (fitnesses < 60 && gencounter >= 10 && !keepState) {
resetSim()
}
//make the fitness function have more bias for target hits if most targets are succeding
//this is to make close but not perfect creaturs die quickly, thus bringing the success rate to 100%
if (succsses > 50){
winstrength = 25;
}
//writes info to the screen
document.getElementById("gencounter").innerHTML =
" | Gen " +
gencounter +
" | Avg Fitness = " +
(Math.round((fitnesses+3) * 1000) / 1000) +
" | Mutation Rate = " +
(Math.round(mutationrate * 10000000) / 10000000) + "%" +
" | Success Rate = " + (Math.round(succsses * 1000) / 1000) + "%";
addInfoToChart(chart, fitnesses, succsses);
}
document.getElementById("tickcounter").innerHTML = ticks;
}
function calcfitness(player) {
var dist = player.recordDist;
var fit = map(dist, 1, 1000, 100, 1);
if (player.getToTarget) {
fit *= winstrength;
}
if (player.crash) {
fit /= 2;
}
return parseInt(fit);
}
function map(n, start1, stop1, start2, stop2) {
return ((n - start1) / (stop1 - start1)) * (stop2 - start2) + start2;
}
function mutate(player) {
let np = new EvolutionPlayer(
200,
250,
pw,
ph,
target["x"],
target["y"],
genlen
);
np.DNA = DNAcopy(player.DNA);
for (let i = 0; i < np.DNA.length; i++) {
if (Math.random() < mutationrate) {
np.DNA[i][0] = np.getRandom(0.5);
np.DNA[i][1] = np.getRandom(0.5);
}
}
return np;
}
function DNAcopy(dna) {
var ndna = [];
for (let i = 0; i < dna.length; i++) {
ndna.push(dna[i].slice());
}
return ndna;
}
function resetPlayers() {
players.length = 0;
for (var i = 0; i < playernum; i++) {
players.push(
new EvolutionPlayer(200, 250, pw, ph, target["x"], target["y"], genlen)
);
}
}
function addInfoToChart(ch, fitdata, sucdata){
ch.configInfo.data.labels.push(""+gencounter);
ch.configInfo.data.datasets[0].data.push(fitdata+3);
ch.configInfo.data.datasets[1].data.push(sucdata);
ch.chart.update();
//colors
if (fitdata < 50){
ch.configInfo.data.datasets[0].backgroundColor[0] = "rgba(255,0,0,0.2)";
ch.configInfo.data.datasets[0].borderColor[0] = "rgba(255,0,0,0.75)";
} else if (fitdata > 50 && fitdata < 85) {
ch.configInfo.data.datasets[0].backgroundColor[0] = "rgba(0,0,255,0.2)";
ch.configInfo.data.datasets[0].borderColor[0] = "rgba(0,0,0,255,0.75)";
} else if (fitdata > 85) {
ch.configInfo.data.datasets[0].backgroundColor[0] = "rgba(0,255,0,0.2)";
ch.configInfo.data.datasets[0].borderColor[0] = "rgba(0,255,0,0.75)";
}
}
//starts the sim
function startSim(){
inter = setInterval(draw, 1000 / 35);
playernum = parseInt(document.getElementById("playerrange").value);
genlen = parseInt(document.getElementById("genlen").value);
console.log(genlen);
//add players to list
for (var i = 0; i < playernum; i++) {
players.push(
new EvolutionPlayer(200, 250, pw, ph, target["x"], target["y"], genlen)
);
}
document.getElementById("startdiv").style = "visibility: hidden";
document.getElementById("simControlGroup").style = "visibility: visible";
c.onmousedown = null;
clearInterval(presimint);
startSim = null;
}
function changePlayerLable(el){
document.getElementById("playerrangelable").innerHTML = " " + document.getElementById("playerrange").value + " Players";
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
c.onmousedown = function(e){
m = getMousePos(c,e);
for (let i = 0; i < walls.length; i++){
var box = walls[i];
if (m.x > box.x && m.x < box.x + box.w && m.y > box.y && m.y < box.y+box.h){
console.log("wall is " + i);
offset = [m["x"]-box.x,m["y"]-box.y]
c.onmousemove = function(e){
m = getMousePos(c,e);
walls[i].x = m["x"]-offset[0];
walls[i].y = m["y"]-offset[1];
}
}
}
}
c.onmouseup = function(e){
c.onmousemove = null;
}
function showPreSim(){
c.width = c.width;
ctx.fillRect(
target["x"] - target["s"] / 2,
target["y"] - target["s"] / 2,
target["s"],
target["s"]
);
//draw walls
for (wall of walls) {
ctx.fillRect(wall.x, wall.y, wall.w, wall.h);
}
//draw player location
ctx.fillRect(190, 240, 20, 20)
}
var presimint = setInterval(showPreSim, 1000/60);
function addWall(){
walls.push({x:walls[walls.length-1].x-40, y:walls[walls.length-1].y, w:20, h:250});
}
function resetSim(){
resetPlayers();
gencounter = 0;
chart.configInfo.data.labels = [];
chart.configInfo.data.datasets[0].data = [];
chart.configInfo.data.datasets[1].data = [];
chart.chart.update();
}
function changeSpeed(speed){
clearInterval(inter);
inter = setInterval(draw, 1000/speed);
document.getElementById("speedLabel").innerHTML = " " + speed + " FPS";
}
function changeKeepState(state){
keepState = state;
}
</script>
</body>
</html>