-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
93 lines (77 loc) · 2.48 KB
/
main.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
const carCanvas=document.getElementById("carCanvas");
carCanvas.width=window.innerWidth - 330;
const networkCanvas=document.getElementById("networkCanvas");
networkCanvas.width=300;
carCanvas.height=window.innerHeight;
networkCanvas.height=window.innerHeight;
const carCtx = carCanvas.getContext("2d");
const networkCtx = networkCanvas.getContext("2d");
const worldString = localStorage.getItem("world");
const worldInfo = worldString ? JSON.parse(worldString) : null;
const world = worldInfo
? World.load(worldInfo)
: new World(new Graph());
const viewport = new Viewport(carCanvas, world.zoom, world.offset);
const N=100;
const cars=generateCars(N);
let bestCar=cars[0];
if(localStorage.getItem("bestBrain")){
for(let i=0;i<cars.length;i++){
cars[i].brain=JSON.parse(
localStorage.getItem("bestBrain"));
if(i!=0){
NeuralNetwork.mutate(cars[i].brain,0.4);
}
}
}
const traffic=[];
const roadBorders = world.roadBorders.map((s) => [s.p1, s.p2]);
animate();
function save(){
localStorage.setItem("bestBrain",
JSON.stringify(bestCar.brain));
}
function discard(){
localStorage.removeItem("bestBrain");
}
function generateCars(N){
const startPoints = world.markings.filter((m) => m instanceof Start);
const startPoint = startPoints.length > 0
? startPoints[0].center
: new Point(100, 100);
const dir = startPoints.length > 0
? startPoints[0].directionVector
: new Point(0, -1);
const startAngle = - angle(dir) + Math.PI / 2;
const cars=[];
for(let i=1;i<=N;i++){
cars.push(new Car(startPoint.x, startPoint.y,30,50,"AI",startAngle));
}
return cars;
}
function animate(time){
for(let i=0;i<traffic.length;i++){
traffic[i].update(roadBorders,[]);
}
for(let i=0;i<cars.length;i++){
cars[i].update(roadBorders,traffic);
}
bestCar=cars.find(
c=>c.fittness==Math.max(
...cars.map(c=>c.fittness)
));
world.cars = cars;
world.bestCar = bestCar;
viewport.offset.x = -bestCar.x;
viewport.offset.y = -bestCar.y;
viewport.reset();
const viewPoint = scale(viewport.getOffset(), -1);
world.draw(carCtx, viewPoint, false);
for(let i=0;i<traffic.length;i++){
traffic[i].draw(carCtx);
}
networkCtx.lineDashOffset=-time/50;
networkCtx.clearRect(0, 0, networkCanvas.width, networkCanvas.height);
Visualizer.drawNetwork(networkCtx,bestCar.brain);
requestAnimationFrame(animate);
}