-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBetaAwareEnvoAgents.html
818 lines (719 loc) · 28 KB
/
BetaAwareEnvoAgents.html
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Enhanced Multi-Agent Environmental Simulation</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #1a1a1a;
color: white;
margin: 0;
overflow: hidden;
}
#controls {
position: absolute;
top: 10px;
left: 10px;
z-index: 10;
background: rgba(0, 0, 0, 0.8);
padding: 15px;
border-radius: 8px;
}
#controls label, #controls button {
display: block;
margin: 10px 0;
}
#performance {
position: absolute;
bottom: 10px;
right: 10px;
z-index: 10;
background: rgba(0, 0, 0, 0.8);
padding: 15px;
border-radius: 8px;
color: white;
}
#eventLog {
position: absolute;
top: 200px;
left: 10px;
z-index: 10;
background: rgba(0, 0, 0, 0.8);
padding: 15px;
border-radius: 8px;
color: white;
max-height: 200px;
overflow-y: scroll;
}
#eventLog ul {
list-style-type: none;
padding: 0;
}
#eventLog li {
margin-bottom: 5px;
}
</style>
</head>
<body>
<div id="controls">
<label>Agent Speed:</label>
<input type="range" id="speedSlider" min="1" max="10" value="5">
<label>Threat Aggressiveness:</label>
<input type="range" id="threatSlider" min="1" max="5" value="3">
<button onclick="resetSimulation()">Reset Simulation</button>
<button onclick="createEnvironmentalTask()">Create Environmental Task</button>
</div>
<div id="performance">
<p>FPS: <span id="fps"></span></p>
<p>Simulation Step Time: <span id="stepTime"></span> ms</p>
</div>
<div id="eventLog">
<h3>Event Log</h3>
<ul id="eventList"></ul>
</div>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
const settings = {
agent: {
count: 30,
maxSpeed: 6,
maxHealth: 150,
reproductionRate: 0.1,
visionRadius: 150,
sustainabilityAwareness: 1,
maxCount: 100,
},
threat: {
count: 10,
speed: 3,
health: 50,
aggressiveness: 3,
},
food: {
count: 20,
respawnRate: 5000,
},
task: {
count: 0,
completionReward: 20,
},
obstacle: {
count: 40,
ageLimit: 300,
},
qLearning: {
learningRate: 0.1,
discountRate: 0.9,
explorationRate: 0.2,
},
shelter: {
count: 10,
},
eventLog: {
maxSize: 1000,
},
dayNightCycle: {
enabled: true,
timeIncrement: 0.1,
}
};
let timeOfDay = 0; // 0 to 24 representing hours
const eventLog = [];
function logEvent(event) {
eventLog.push({ time: Date.now(), ...event });
if (eventLog.length > settings.eventLog.maxSize) {
eventLog.shift();
}
}
class Entity {
constructor(x, y, size, color) {
this.x = x;
this.y = y;
this.size = size;
this.color = color;
this.isAlive = true;
}
distanceTo(other) {
const dx = other.x - this.x;
const dy = other.y - this.y;
return Math.hypot(dx, dy);
}
draw() {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fill();
}
keepWithinBounds() {
this.x = Math.max(this.size, Math.min(canvas.width - this.size, this.x));
this.y = Math.max(this.size, Math.min(canvas.height - this.size, this.y));
}
}
class Agent extends Entity {
constructor(x, y, traits = {}) {
super(x, y, traits.size || (Math.random() * 4 + 3), "blue");
this.health = settings.agent.maxHealth;
this.speed = traits.speed || (Math.random() * settings.agent.maxSpeed + 1);
this._visionRadius = traits.visionRadius || settings.agent.visionRadius;
this.sustainabilityAwareness = traits.sustainabilityAwareness || settings.agent.sustainabilityAwareness;
this.qTable = {}; // Q-learning table
this.lastState = null;
this.lastAction = null;
this.actions = this.getActions();
this.generation = traits.generation || 1;
this.id = Agent.nextId++;
}
static nextId = 1;
get visionRadius() {
const baseVision = this._visionRadius;
// Reduce vision at night (e.g., between 18 and 6)
if (timeOfDay >= 18 || timeOfDay <= 6) {
return baseVision * 0.5;
} else {
return baseVision;
}
}
draw() {
// Color changes based on generation
this.color = `hsl(${(this.generation * 30) % 360}, 100%, 50%)`;
super.draw();
}
move() {
const state = this.getState();
const actions = this.getActions();
let action = this.chooseAction(actions);
switch (action) {
case 'move_towards_food':
this.moveTowardsFood();
break;
case 'move_towards_task':
this.moveTowardsTask();
break;
case 'avoid_threat':
this.avoidThreat();
break;
case 'avoid_obstacle':
this.avoidObstacle();
break;
case 'move_towards_shelter':
this.moveTowardsShelter();
break;
default:
this.moveRandomly();
}
this.keepWithinBounds();
if (this.lastState && this.lastAction) {
const reward = this.getReward();
const nextState = this.getState();
this.updateQTable(this.lastState, this.lastAction, reward, nextState);
}
this.lastState = state;
this.lastAction = action;
this.communicate();
}
getState() {
const nearestFood = this.getNearestFood();
const nearestThreat = this.getNearestThreat();
const nearestTask = this.getNearestTask();
const nearestObstacle = this.getNearestObstacle();
const nearestShelter = this.getNearestShelter();
// Discretize distances
return {
foodDistance: this.getDistanceCategory(nearestFood?.distance),
threatDistance: this.getDistanceCategory(nearestThreat?.distance),
taskDistance: this.getDistanceCategory(nearestTask?.distance),
obstacleDistance: this.getDistanceCategory(nearestObstacle?.distance),
shelterDistance: this.getDistanceCategory(nearestShelter?.distance),
};
}
getDistanceCategory(distance) {
if (distance == null) return 'none';
const normalized = distance / Math.hypot(canvas.width, canvas.height);
if (normalized < 0.2) return 'very_close';
else if (normalized < 0.4) return 'close';
else if (normalized < 0.6) return 'medium';
else if (normalized < 0.8) return 'far';
else return 'very_far';
}
getActions() {
return ['move_towards_food', 'move_towards_task', 'avoid_threat', 'avoid_obstacle', 'move_towards_shelter', 'move_randomly'];
}
chooseAction(actions) {
if (Math.random() < settings.qLearning.explorationRate) {
return actions[Math.floor(Math.random() * actions.length)];
} else {
let bestAction = actions[0];
let bestQValue = -Infinity;
for (const action of actions) {
const qValue = this.qTable[this.stateKey(this.getState()) + action] || 0;
if (qValue > bestQValue) {
bestQValue = qValue;
bestAction = action;
}
}
return bestAction;
}
}
updateQTable(state, action, reward, nextState) {
const currentQ = this.qTable[this.stateKey(state) + action] || 0;
const maxNextQ = this.actions.length > 0 ? Math.max(...this.actions.map(a => this.qTable[this.stateKey(nextState) + a] || 0)) : 0;
this.qTable[this.stateKey(state) + action] = currentQ + settings.qLearning.learningRate * (reward + settings.qLearning.discountRate * maxNextQ - currentQ);
}
stateKey(state) {
return `${state.foodDistance},${state.threatDistance},${state.taskDistance},${state.obstacleDistance},${state.shelterDistance}`;
}
getReward() {
if (this.health > settings.agent.maxHealth * 0.8) return 1;
else if (this.health < settings.agent.maxHealth * 0.2) return -1;
else return 0;
}
moveTowardsFood() {
const food = this.getNearestFood();
if (food) {
this.moveTowards(food.target);
}
}
moveTowardsTask() {
const task = this.getNearestTask();
if (task) {
this.moveTowards(task.target);
}
}
avoidThreat() {
const threat = this.getNearestThreat();
if (threat) {
this.moveAwayFrom(threat.target);
}
}
avoidObstacle() {
const obstacle = this.getNearestObstacle();
if (obstacle) {
this.moveAwayFrom(obstacle.target);
}
}
moveTowardsShelter() {
const shelter = this.getNearestShelter();
if (shelter) {
this.moveTowards(shelter.target);
}
}
moveRandomly() {
this.x += (Math.random() - 0.5) * this.speed;
this.y += (Math.random() - 0.5) * this.speed;
}
moveTowards(target) {
const dx = target.x - this.x;
const dy = target.y - this.y;
const dist = Math.hypot(dx, dy);
if (dist > 0) {
this.x += (dx / dist) * this.speed;
this.y += (dy / dist) * this.speed;
}
}
moveAwayFrom(target) {
const dx = this.x - target.x;
const dy = this.y - target.y;
const dist = Math.hypot(dx, dy);
if (dist > 0) {
this.x += (dx / dist) * this.speed;
this.y += (dy / dist) * this.speed;
}
}
getNearestFood() {
if (foods.length === 0) return null;
let nearest = null;
let minDist = Infinity;
for (const food of foods) {
const dist = this.distanceTo(food);
if (dist < minDist && dist < this.visionRadius) {
nearest = { target: food, distance: dist };
minDist = dist;
}
}
return nearest;
}
getNearestThreat() {
if (threats.length === 0) return null;
let nearest = null;
let minDist = Infinity;
for (const threat of threats) {
const dist = this.distanceTo(threat);
if (dist < minDist && dist < this.visionRadius) {
nearest = { target: threat, distance: dist };
minDist = dist;
}
}
return nearest;
}
getNearestTask() {
if (tasks.length === 0) return null;
let nearest = null;
let minDist = Infinity;
for (const task of tasks) {
const dist = this.distanceTo(task);
if (dist < minDist && dist < this.visionRadius) {
nearest = { target: task, distance: dist };
minDist = dist;
}
}
return nearest;
}
getNearestObstacle() {
if (obstacles.length === 0) return null;
let nearest = null;
let minDist = Infinity;
for (const obstacle of obstacles) {
const dist = this.distanceTo(obstacle);
if (dist < minDist && dist < this.visionRadius) {
nearest = { target: obstacle, distance: dist };
minDist = dist;
}
}
return nearest;
}
getNearestShelter() {
if (shelters.length === 0) return null;
let nearest = null;
let minDist = Infinity;
for (const shelter of shelters) {
const dist = this.distanceTo(shelter);
if (dist < minDist && dist < this.visionRadius) {
nearest = { target: shelter, distance: dist };
minDist = dist;
}
}
return nearest;
}
reproduce() {
if (agents.length >= settings.agent.maxCount) return null;
const mutationRate = 0.1;
const traits = {
speed: this.speed + (Math.random() < mutationRate ? (Math.random() - 0.5) : 0),
visionRadius: this._visionRadius + (Math.random() < mutationRate ? (Math.random() * 10 - 5) : 0),
size: this.size + (Math.random() < mutationRate ? (Math.random() - 0.5) : 0),
sustainabilityAwareness: this.sustainabilityAwareness,
generation: this.generation + 1,
};
const offspring = new Agent(this.x, this.y, traits);
// Inherit Q-table with potential mutations
offspring.qTable = JSON.parse(JSON.stringify(this.qTable));
return offspring;
}
engageThreat(threat) {
const dx = threat.x - this.x;
const dy = threat.y - this.y;
const distance = Math.hypot(dx, dy);
if (distance < this.size + threat.size) {
threat.health -= 10;
if (threat.health <= 0) threat.despawn();
}
}
despawn() {
this.isAlive = false;
}
communicate() {
const nearbyAgents = agents.filter(otherAgent =>
otherAgent !== this && this.distanceTo(otherAgent) < this.visionRadius
);
for (const otherAgent of nearbyAgents) {
// Share knowledge (e.g., Q-tables)
otherAgent.receiveInformation(this);
}
}
receiveInformation(otherAgent) {
// Merge Q-tables or update beliefs
for (let key in otherAgent.qTable) {
if (!this.qTable[key]) {
this.qTable[key] = otherAgent.qTable[key];
} else {
// Average the Q-values
this.qTable[key] = (this.qTable[key] + otherAgent.qTable[key]) / 2;
}
}
}
}
class Threat extends Entity {
constructor(x, y, target) {
super(x, y, 8, "red");
this.speed = settings.threat.speed * settings.threat.aggressiveness;
this.health = settings.threat.health;
this.target = target;
}
move() {
if (!this.target || !this.target.isAlive) {
if (agents.length > 0) {
this.target = agents[Math.floor(Math.random() * agents.length)];
} else {
return;
}
}
const dx = this.target.x - this.x;
const dy = this.target.y - this.y;
const dist = Math.hypot(dx, dy);
if (dist > 0) {
this.x += (dx / dist) * this.speed;
this.y += (dy / dist) * this.speed;
this.keepWithinBounds();
if (dist < this.size + this.target.size) {
this.target.health -= 15 * settings.threat.aggressiveness;
this.despawn();
}
}
}
despawn() {
this.isAlive = false;
}
}
class Food extends Entity {
constructor(x, y) {
super(x, y, 5, "green");
this.spawnTime = Date.now();
}
despawn() {
this.isAlive = false;
}
checkDespawn() {
if (Date.now() - this.spawnTime > settings.food.respawnRate) {
this.despawn();
}
}
}
class Task extends Entity {
constructor(x, y) {
super(x, y, 6, "yellow");
}
despawn() {
this.isAlive = false;
}
complete() {
this.despawn();
// Reward agents involved
}
}
class Obstacle extends Entity {
constructor(x, y) {
super(x, y, Math.random() * 10 + 5, "gray");
this.age = 0;
this.ageLimit = settings.obstacle.ageLimit;
}
update() {
this.age += 1;
if (this.age > this.ageLimit) this.despawn();
}
despawn() {
this.isAlive = false;
}
}
class Shelter extends Entity {
constructor(x, y) {
super(x, y, 10, "brown");
}
despawn() {
this.isAlive = false;
}
}
const agents = [];
const threats = [];
const foods = [];
const tasks = [];
const obstacles = [];
const shelters = [];
function initializeSimulation() {
agents.length = 0;
threats.length = 0;
foods.length = 0;
tasks.length = 0;
obstacles.length = 0;
shelters.length = 0;
eventLog.length = 0;
for (let i = 0; i < settings.agent.count; i++) {
agents.push(new Agent(Math.random() * canvas.width, Math.random() * canvas.height));
}
for (let i = 0; i < settings.threat.count; i++) {
if (agents.length > 0) {
const target = agents[Math.floor(Math.random() * agents.length)];
threats.push(new Threat(Math.random() * canvas.width, Math.random() * canvas.height, target));
}
}
for (let i = 0; i < settings.food.count; i++) {
foods.push(new Food(Math.random() * canvas.width, Math.random() * canvas.height));
}
for (let i = 0; i < settings.obstacle.count; i++) {
obstacles.push(new Obstacle(Math.random() * canvas.width, Math.random() * canvas.height));
}
for (let i = 0; i < settings.shelter.count; i++) {
shelters.push(new Shelter(Math.random() * canvas.width, Math.random() * canvas.height));
}
}
function spawnFood() {
if (foods.length < settings.food.count) {
foods.push(new Food(Math.random() * canvas.width, Math.random() * canvas.height));
}
}
function spawnThreat() {
if (threats.length < settings.threat.count && agents.length > 0) {
const target = agents[Math.floor(Math.random() * agents.length)];
threats.push(new Threat(Math.random() * canvas.width, Math.random() * canvas.height, target));
}
}
function createEnvironmentalTask() {
tasks.push(new Task(Math.random() * canvas.width, Math.random() * canvas.height));
}
function updateTime() {
timeOfDay = (timeOfDay + settings.dayNightCycle.timeIncrement) % 24;
}
function drawBackground() {
let alpha = 0;
if (timeOfDay >= 18) {
alpha = (timeOfDay - 18) / 6;
} else if (timeOfDay <= 6) {
alpha = (6 - timeOfDay) / 6;
}
ctx.fillStyle = `rgba(0, 0, 0, ${alpha * 0.5})`;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
let lastTimestamp = performance.now();
let fps, stepTime;
function updateSimulation(timestamp) {
const delta = timestamp - lastTimestamp;
lastTimestamp = timestamp;
fps = (1000 / delta).toFixed(1);
const startTime = performance.now();
ctx.clearRect(0, 0, canvas.width, canvas.height);
updateTime();
drawBackground();
// Update agents
for (let i = agents.length - 1; i >= 0; i--) {
const agent = agents[i];
if (agent.health <= 0) {
logEvent({ type: 'AgentDeath', agentId: agent.id, generation: agent.generation });
agent.despawn();
continue;
}
agent.move();
agent.health -= 0.05;
if (agent.health > settings.agent.maxHealth * 1.5 && agents.length < settings.agent.maxCount) {
const offspring = agent.reproduce();
if (offspring) {
agents.push(offspring);
logEvent({ type: 'AgentReproduction', parentId: agent.id, offspringId: offspring.id, generation: offspring.generation });
agent.health -= settings.agent.maxHealth * 0.5;
}
}
agent.draw();
}
// Remove despawned agents
for (let i = agents.length - 1; i >= 0; i--) {
if (!agents[i].isAlive) {
agents.splice(i, 1);
}
}
// Update threats
for (let i = threats.length - 1; i >= 0; i--) {
const threat = threats[i];
threat.move();
threat.draw();
}
// Remove despawned threats
for (let i = threats.length - 1; i >= 0; i--) {
if (!threats[i].isAlive) {
threats.splice(i, 1);
}
}
// Update foods
for (let i = foods.length - 1; i >= 0; i--) {
const food = foods[i];
food.draw();
food.checkDespawn();
for (const agent of agents) {
if (agent.distanceTo(food) < agent.size + food.size) {
agent.health = Math.min(agent.health + 20, settings.agent.maxHealth);
food.despawn();
logEvent({ type: 'FoodConsumed', agentId: agent.id });
}
}
}
// Remove despawned foods
for (let i = foods.length - 1; i >= 0; i--) {
if (!foods[i].isAlive) {
foods.splice(i, 1);
}
}
// Update tasks
for (let i = tasks.length - 1; i >= 0; i--) {
const task = tasks[i];
task.draw();
for (const agent of agents) {
if (agent.distanceTo(task) < agent.size + task.size) {
agent.health += settings.task.completionReward;
task.despawn();
logEvent({ type: 'TaskCompleted', agentId: agent.id });
}
}
}
// Remove despawned tasks
for (let i = tasks.length - 1; i >= 0; i--) {
if (!tasks[i].isAlive) {
tasks.splice(i, 1);
}
}
// Update obstacles
for (let i = obstacles.length - 1; i >= 0; i--) {
const obstacle = obstacles[i];
obstacle.update();
obstacle.draw();
}
// Remove despawned obstacles
for (let i = obstacles.length - 1; i >= 0; i--) {
if (!obstacles[i].isAlive) {
obstacles.splice(i, 1);
}
}
// Draw shelters
for (const shelter of shelters) {
shelter.draw();
}
spawnFood();
spawnThreat();
stepTime = (performance.now() - startTime).toFixed(1);
// Update performance display
document.getElementById('fps').innerText = fps;
document.getElementById('stepTime').innerText = stepTime;
requestAnimationFrame(updateSimulation);
}
function resetSimulation() {
initializeSimulation();
}
document.getElementById("speedSlider").addEventListener("input", e => {
const speed = parseFloat(e.target.value);
agents.forEach(agent => agent.speed = speed);
});
document.getElementById("threatSlider").addEventListener("input", e => {
settings.threat.aggressiveness = parseFloat(e.target.value);
threats.forEach(threat => threat.speed = settings.threat.speed * settings.threat.aggressiveness);
});
function updateEventLog() {
const eventList = document.getElementById('eventList');
eventList.innerHTML = '';
for (const event of eventLog) {
const listItem = document.createElement('li');
listItem.textContent = `[${new Date(event.time).toLocaleTimeString()}] ${event.type}`;
eventList.appendChild(listItem);
}
}
// Call updateEventLog at regular intervals
setInterval(updateEventLog, 1000);
initializeSimulation();
updateSimulation(performance.now());
</script>
</body>
</html>