BlueGit

blue-star cellular-evolution

Files

cellular-evolution / js / game.js

game.js

build
timfa Tim · pushed by timfa · 5 years ago
2997d069 History
game.js 21.6 KiB Download Raw
1/**
2 * Part of a creature!
3 */
4
5var cell =
6{
7 localPos: new vector(0, 0),
8 parentCreature: null,
9 type: -1,
10 cellRef: -1,
11 currentSensorSignal: 0, //only used for sensors, else forever zero
12 lastSum: 0, //used for debug purposes
13 energy: 1,
14 maxEnergy: 1,
15 debugShouldDraw: false,
16
17 start: function()
18 {
19 this.transform.scale.x = 0;
20 this.transform.scale.y = 0;
21
22 var scaleUpTween = new TWEEN.Tween(this.transform.scale);
23
24 scaleUpTween.to({x: [1.5, 1], y: [1.5, 1]}, Math.random() * 3200);
25
26 scaleUpTween.easing(TWEEN.Easing.Back.Out);
27
28 scaleUpTween.start();
29 },
30
31 activate: function(strength, deltaTime)
32 {
33 this.lastSum = strength;
34
35 switch(this.type)
36 {
37 case TYPES.LOCOMOTOR:
38 var actualStrength = Math.max(0, strength)
39 if(actualStrength > 0)
40 {
41 var power = this.parentCreature.consumeEnergy(actualStrength * deltaTime)
42 var rotated = this.localPos.rotate(this.parentCreature.transform.rotation);
43
44 this.parentCreature.transform.position = this.parentCreature.transform.position.subtract(rotated.stretch(deltaTime * power));
45 }
46 break;
47 case TYPES.ROTATOR:
48 var power = this.parentCreature.consumeEnergy(Math.abs(strength) * deltaTime)
49 this.parentCreature.transform.rotation += (strength) * deltaTime * 100 * power;
50 break;
51 }
52 },
53
54 onCollision: function(other)
55 {
56 if (this.type == TYPES.MOUTH && !this.destroyed)
57 {
58 if(other.parentCreature == this.parentCreature)
59 return;
60
61 this.parentCreature.gainEnergy(this.maxEnergy / 3);
62 other.destroy();
63 }
64 },
65
66 draw: function()
67 {
68 this.defaultDraw();
69
70 if(this.debugShouldDraw)
71 {
72 GameWindow.canvasContext.fillStyle = 'black';
73 GameWindow.canvasContext.fillText(this.lastSum, this.transform.position.x, this.transform.position.y);
74 }
75 },
76
77 update: function()
78 {
79 var rotated = this.localPos.rotate(this.parentCreature.transform.rotation);
80 this.transform.position = rotated.stretch(this.transform.scale.x).add(this.parentCreature.transform.position);
81
82 if(this.type == TYPES.EYE)
83 this.transform.rotation = rotated.toAngle();
84
85 if(this.type == TYPES.LOCOMOTOR)
86 this.transform.rotation = rotated.toAngle() - 90;
87
88 if(this.type == TYPES.STOMACH)
89 this.currentSensorSignal = (this.energy / this.maxEnergy);
90 },
91
92 setType: function(typeID)
93 {
94 this.renderer.subImage = typeID;
95 this.type = typeID;
96 }
97}
98
99/**
100 * It's a thing!
101 */
102
103var creature =
104{
105 dna: {},
106 cellInstances: [],
107
108 start: function()
109 {
110
111 },
112
113 initCells()
114 {
115 for(var i = 0; i < this.dna.length; i++)
116 {
117 var newCell = GameObject.create(cell, this.transform.position.x + (this.dna[i].pos.x * 32), this.transform.position.y + (this.dna[i].pos.y * 32), s_cell, 400);
118
119 newCell.setType(this.dna[i].type);
120 newCell.parentCreature = this;
121 newCell.localPos = new vector(this.dna[i].pos.x * 32, this.dna[i].pos.y * 32)
122
123 newCell.cellRef = i;
124
125 this.cellInstances.push(newCell);
126 }
127 },
128
129 update: function(deltaTime)
130 {
131 for(var i = this.cellInstances.length -1; i >= 0; i--) //reverse loop for deletion of references to destroyed cells
132 {
133 if(this.cellInstances[i].destroyed)
134 this.cellInstances.splice(i, 1);
135 }
136
137 for(var i = 0; i < this.cellInstances.length; i++) //loop through instances instead of dna so that destroyed cells are immediately ignored
138 {
139 var type = this.dna[this.cellInstances[i].cellRef].type;
140
141 if(type == TYPES.LOCOMOTOR || type == TYPES.ROTATOR)
142 {
143 if(this.dna[this.cellInstances[i].cellRef].inputs.length > 0)
144 {
145 var sum = sigmoid(this.getCellInputSum(this.cellInstances[i]));
146
147 //TODO: Act on the sum we've received (ALWAYS between 0 and 1, but VERY rarely exactly 0 or 1)
148
149 this.cellInstances[i].activate(sum, deltaTime);
150 }
151 }
152 }
153
154 //this.transform.rotation += deltaTime * 60;
155 //this.transform.position = this.transform.position.add(this.transform.forward().stretch(deltaTime * 250))
156 },
157
158 consumeEnergy: function(energyNeeded) //returns a number between 0 and 1. 0 meaning no energy was consumed (because we ran out), 1 means all of the energy was consumed.
159 {
160 var stomachRef = -1;
161 var amt = 0;
162
163 for(var i = 0; i < this.cellInstances.length; i++)
164 {
165 if(this.cellInstances[i].type == TYPES.STOMACH)
166 {
167 if(this.cellInstances[i].energy > amt)
168 {
169 stomachRef = i;
170 amt = this.cellInstances[i].energy;
171 }
172 }
173 }
174
175 if(stomachRef == -1)
176 return 0;
177
178 var efficiency = Math.min(1, this.cellInstances[stomachRef].energy / energyNeeded)
179
180 this.cellInstances[stomachRef].energy = Math.max(0, this.cellInstances[stomachRef].energy - energyNeeded)
181
182 return efficiency;
183 },
184
185 draw: function()
186 {
187 for(var i = 0; i < this.cellInstances.length; i++)
188 {
189 if(this.dna[this.cellInstances[i].cellRef].inputs.length > 0)
190 {
191 for(var c = 0; c < this.dna[this.cellInstances[i].cellRef].inputs.length; c++)
192 {
193 var pos = this.findCellInstanceByCellId(this.dna[this.cellInstances[i].cellRef].inputs[c].id).transform.position;
194
195 GameWindow.canvasContext.strokeStyle = 'red';
196 GameWindow.canvasContext.beginPath();
197 GameWindow.canvasContext.moveTo(this.cellInstances[i].transform.position.x, this.cellInstances[i].transform.position.y);
198 GameWindow.canvasContext.lineTo(pos.x, pos.y);
199 GameWindow.canvasContext.stroke();
200 }
201 }
202 }
203 },
204
205 gainEnergy: function(amount)
206 {
207 var stomachRef = -1;
208 var amt = 10000;
209
210 for(var i = 0; i < this.cellInstances.length; i++)
211 {
212 if(this.cellInstances[i].type == TYPES.STOMACH)
213 {
214 if(this.cellInstances[i].energy < amt)
215 {
216 stomachRef = i;
217 amt = this.cellInstances[i].energy;
218 }
219 }
220 }
221
222 if(stomachRef == -1)
223 return 0;
224
225 this.cellInstances[stomachRef].energy = Math.min(cell.maxEnergy, this.cellInstances[stomachRef].energy + amount)
226 },
227
228 getCellInputSum: function(cellInstance, tracer = [])
229 {
230 var cellId = this.dna[cellInstance.cellRef].id;
231
232 if(tracer.indexOf(cellId) >= 0) //is my id already in the tracer?
233 return 0;
234
235 tracer.push(cellId)
236
237 var currentSum = cellInstance.currentSensorSignal;
238 cellInstance.debugShouldDraw = true;
239
240 if(this.dna[cellInstance.cellRef].inputs.length > 0)
241 {
242 for(var i = 0; i < this.dna[cellInstance.cellRef].inputs.length; i++)
243 {
244 var synapse = this.dna[cellInstance.cellRef].inputs[i];
245
246 var cInstance = this.findCellInstanceByCellId(synapse.id);
247 var inputSum = this.getCellInputSum(cInstance, tracer);
248
249 currentSum += sigmoid(inputSum * synapse.strength);
250 }
251 }
252
253 cellInstance.lastSum = currentSum;
254
255 return currentSum + this.dna[cellInstance.cellRef].bias;
256 },
257
258 findCellInstanceByCellId: function(id)
259 {
260 for(var i = 0; i < this.cellInstances.length; i++)
261 {
262 if(this.dna[this.cellInstances[i].cellRef].id == id)
263 return this.cellInstances[i];
264 }
265 },
266
267 onDestroy: function()
268 {
269
270 },
271
272 onCollision: function(other)
273 {
274
275 }
276}
277
278
279/**
280 * DNA strings contain the makeup of a creature, seriving as a template for the creature factory
281 * The DNA string must be automatically generatable so that random mutations can occur.
282 *
283 * In essence, it is a list of cell types with potential Synapses. Any 'sensor' cell can have one or more connections to 'activatable' cells such as locomotion cells or mouths.
284 *
285 * A DNA string should be able to be parsed to a simple string (hence the name), meaning the factory must be able to interpret relations from a data structure that doesn't support references.
286 *
287 * definitions:
288 * - cell: one out of many objects of uniform size that make up a creature
289 * - sensor: a cell that is able to detect things
290 * - activator: a cell that can respond to the signal of a Synapse, using energy from Stomach cells. When no energy is available, the Activators are unable to do anything and as such the creature will essentially be 'dead'
291 * - Synapse: a connection between a sensor and an activator
292 * - braincell: a cell that acts as a hybrid activator/sensor. It receives inputs like an activator would, but instead of doing something on its own, it has outbound Synapse connections of its own to one or more sensors (or other brain cells)
293 *
294 * Types of mutations that can occur:
295 * - add or remove connections between sensors and activators (unlikely)
296 * - add or remove cells of any type (very unlikely)
297 * - change the strength of Synapses (likely)
298 *
299 * Types of cells:
300 * ACTIVATORS
301 * - Mouth: can Bite, which will eat whatever is in front of it, be that a cell or a food pellet (TEMP: automatically works without input for now)
302 * - Locomotor: When activated, pushes the creature in the direction of the creature's center, relative from the locomotor cell
303 * - Rotator: Applies torque when activated. 0.5 is neural, 0 is full left, 1 is full right
304 *
305 * SENSORS
306 * - Eye: Activates whenever there is a cell or food pellet near it within a certain range and in a certain direction
307 *
308 * OTHER
309 * - Stomach: Can contain energy. Each cell/pellet eaten increases energy in any available Stomach cells. All Activators require an amount of energy from any of the available Stomach cells to function.
310 * - Meat: A cell which does nothing except connect other cells. (and potentially function as armor)
311 * - Heart: Does nothing, but when the heart is destroyed the creature will die. Creature cannot have more than one Heart, which is always at 0,0
312 *
313 * A creature will multiply when all its Stomach cells are completely full, draining each of them by 50%. This spawns an Egg which will hatch into a copy of the parent creature with a slight mutation applied as soon as there is space available (read: the parent creature has moved suffficiently far away).
314 *
315 * Examples:
316 * One cell:
317 * {
318 * ID : number. Each new cell will take the first available number so that numbers from deleted cells are re-used
319 * Type: number, corresponding to the cell type.
320 * In: [array of ID's to inbound Synapses and strength, e.g.: {ID:5,Strength:1.2},{ID:8,Strength:1.2}]
321 * Pos: {X, Y} vector, where 0,0 is the center of a creature which will ALWAYS be a Heart. (note that center of mass, as in the average position of all cells, will be used to determine direction for locomotors and such, not 0,0)
322 * }
323 *
324 * The output of a Cell is determined as follows:
325 * OUT = Sigmoid ( IN1Val*IN1Weight + IN2Val*IN2Weight + IN3Val*IN3Weight + ... )
326 * Sigmoid will accept numbers from negative infinity up until positive infinity, and as such the weights of all Synapses need not be clamped. Sigmoid will always output a value between zero and one.
327 *
328 * Functionally, outputs will be determined from the Activators. Activators request their inputs to calculate, which in turn request their inputs to calculate, until all values have been determined.
329 *
330 * Note that any cells which would be disconnected from the heart should be automatically removed from the DNA string
331 *
332 * --
333 *
334 * This file will handle:
335 * - Generating new DNA strings
336 * - Mutating existing DNA strings
337 */
338
339/**
340 * Potential issues:
341 *
342 * Infinite circular connections in braincells.
343 * Solutions:
344 * - Don't allow braincells to connect to braincells (would fix, but is undesirable as it limits brain complexity)
345 * - use value 0 when the last cell of a circle is detected. e.g.: A B and C are a loop. A requests input from B, which requests input from C, which requests input from A. A would complete the circle and start a loop, so instead 0 is returned.
346 */
347
348//TODO: Make sort of random maybe
349function GenerateNewDNA(startingCells = 10)
350{
351 var dna = [
352 {
353 id: 0,
354 type: TYPES.HEART,
355 inputs: [],
356 pos: {x:0, y:0}
357 }
358 ];
359
360 for(var i = 0; i < startingCells; i++)
361 AddRandomCell(dna)
362
363 for(var i = 0; i < startingCells; i++)
364 AddRandomSynapse(dna)
365
366 dna[0].inputs = [];
367
368 return dna;
369}
370
371function MutateDNA(dna)
372{
373 var rand = Math.random();
374
375 MutateBiases(dna, 1 - rand);
376
377 if(rand < 0.1)
378 AddRandomCell(dna);
379
380 if(rand < 0.2)
381 AddRandomSynapse(dna);
382
383 if(rand < 0.7)
384 MutateSynapses(dna, 1 - rand);
385}
386
387function MutateBiases(dna, strength)
388{
389 for(var i = 0; i < dna.length; i++)
390 {
391 dna[i].bias += -(strength/2) + (Math.random() * strength);
392 }
393}
394
395function MutateSynapses(dna, strength)
396{
397 for(var i = 0; i < dna.length; i++)
398 {
399 if(dna[i].inputs.length > 0)
400 {
401 for(var o = 0; o < dna[i].inputs.length; o++)
402 {
403 dna[i].inputs[o].strength += (-0.5 + Math.random()) * strength;
404 }
405 }
406 }
407}
408
409function AddRandomSynapse(dna, att = 0)
410{
411 if(att > 10)
412 return; //can't be done, give up
413
414 var receivers = [];
415 var senders = [];
416
417 for(var i = 0; i < dna.length; i++)
418 {
419 if(dna[i].type == TYPES.BRAIN)
420 {
421 receivers.push(i);
422 senders.push(i);
423 }
424
425 if(dna[i].type == TYPES.EYE || dna[i].type == TYPES.STOMACH || dna[i].type == TYPES.NOSE || dna[i].type == TYPES.HEATSENSOR)
426 {
427 senders.push(i);
428 }
429
430 if(dna[i].type == TYPES.LOCOMOTOR || dna[i].type == TYPES.ROTATOR)
431 {
432 receivers.push(i);
433 }
434 }
435
436 var ri = Math.floor(Math.random() * receivers.length);
437 var si = Math.floor(Math.random() * senders.length)
438
439 var tri = receivers[ri]
440 var tsi = senders[si];
441
442 var OK = true
443
444 for(var i = 0; i < dna[tri].inputs.length; i++)
445 {
446 if(dna[tri].inputs[i].id == dna[tsi].id)
447 OK = false; //duplicate
448 }
449
450 if(tri != tsi && tri != 0 && tsi != 0 && OK) //todo: check for duplicates
451 {
452 dna[tri].inputs.push({id:dna[tsi].id, strength: (-0.5 + Math.random())});
453 }
454 else
455 {
456 AddRandomSynapse(dna, att + 1); //re-try
457 }
458}
459
460function AddRandomCell(dna)
461{
462 var totalWeight = 0;
463 var weights = Object.values(Weights);
464
465 for (var i = 0; i < weights.length; i++)
466 {
467 totalWeight += weights[i];
468 }
469
470 var current = Math.random() * totalWeight;
471 var selected;
472
473 for (const [key, value] of Object.entries(Weights))
474 {
475 current -= value;
476
477 if(current <= 0)
478 {
479 selected = key;
480 break;
481 }
482 }
483
484 var id = 1;
485
486 for(var i = 0; i < dna.length; i++)
487 {
488 while(id == dna[i].id)
489 id++;
490 }
491
492 var done = false;
493 var pos = {x:0, y:0}
494
495 while(!done)
496 {
497 done = true;
498
499 for(var i = 0; i < dna.length; i++)
500 {
501 if(pos.x == dna[i].pos.x && pos.y == dna[i].pos.y)
502 {
503 done = false;
504 var val = Math.random() > 0.5? -1 : 1;
505 var key = Math.random() > 0.5? "y" : "x";
506
507 pos[key] += val;
508 break;
509 }
510 }
511 }
512
513 var cell =
514 {
515 id: id,
516 type: TYPES[selected],
517 inputs: [],
518 pos: pos,
519 bias: 0
520 }
521
522 dna.push(cell);
523}
524
525var TYPES =
526{
527 HEART: 0,
528 BRAIN: 1,
529 MOUTH: 2,
530 LOCOMOTOR: 3,
531 ROTATOR: 4,
532 EYE: 5,
533 STOMACH: 6,
534 MEAT: 7,
535 NOSE: 8,
536 HEATSENSOR: 9
537}
538
539var Weights =
540{
541 BRAIN: 2.2,
542 MOUTH: 2,
543 LOCOMOTOR: 2,
544 ROTATOR: 1,
545 EYE: 2.4,
546 STOMACH: 3,
547 MEAT: 4,
548 NOSE: 1.5,
549 HEATSENSOR: 1.3
550}
551
552
553
554function sigmoid(z)
555{
556 return (-0.5 + (1 / (1 + Math.exp(-z)))) * 2;
557}
558
559
560/**
561 * Snake Food
562 */
563
564var gem =
565{
566 start: function()
567 {
568 this.name = "gem";
569 this.renderer.subImage = Math.floor(Math.random() * this.renderer.image.subImages);
570
571 this.transform.scale.x = 0;
572 this.transform.scale.y = 0;
573
574 var scaleUpTween = new TWEEN.Tween(this.transform.scale);
575
576 scaleUpTween.to({x: [1.5, 1], y: [1.5, 1]}, 800);
577
578 scaleUpTween.easing(TWEEN.Easing.Back.Out);
579
580 scaleUpTween.start();
581
582 this.shakeLength = 1000;
583 this.shakes = 4;
584 this.shakeAngle = 45;
585
586 this.minShakeTimer = 5;
587 this.maxShakeTimer = 20;
588 this.shakeTimer = this.minShakeTimer + (Math.random() * (this.maxShakeTimer - this.minShakeTimer));
589 this.currentShakeTimer = 0;
590
591 GameAudio.play("bubble");
592 },
593
594 update: function(deltaTime)
595 {
596 this.currentShakeTimer += deltaTime;
597
598 if(this.currentShakeTimer >= this.shakeTimer)
599 {
600 this.shake();
601
602 this.shakeTimer = this.minShakeTimer + (Math.random() * (this.maxShakeTimer - this.minShakeTimer));
603
604 this.currentShakeTimer = 0;
605 }
606 },
607
608 onDestroy: function()
609 {
610 gemSpawner.currentActive--;
611 },
612
613 onCollision: function(other)
614 {
615 if (other.name == "snake" && !this.destroyed)
616 {
617 other.grow(1, -1);
618 this.destroy();
619 }
620 },
621
622 shake: function(callback, context)
623 {
624 var singleShakeTime = this.shakes / this.shakeLength;
625
626 var shakeTween = new TWEEN.Tween(this.transform);
627
628 var angles = [];
629
630 var offset = Math.round(Math.random() * 5);
631
632 for (var i = 0; i < this.shakes; i++)
633 {
634 var intensiy = 1 - (i / this.shakes);
635
636 // Direction of the shake (is 'i' odd?)
637 var dir = !((i + offset) % 2)? -1 : 1;
638
639 var angleRad = this.shakeAngle;
640
641 var angle = angleRad * dir * intensiy;
642
643 angles.push(angle);
644 }
645
646 angles.push(0);
647
648 shakeTween.to({rotation: angles}, this.shakeLength);
649
650 shakeTween.easing(TWEEN.Easing.Quadratic.InOut);
651
652 if (callback)
653 {
654 shakeTween.onComplete.addOnce(callback, context);
655 }
656
657 shakeTween.start();
658 }
659}
660
661/**
662 * Gem Spawner spawns gems in the world
663 */
664var gemSpawner =
665{
666 start: function()
667 {
668 gemSpawner.currentActive = 0;
669
670 this.maxGems = 7;
671
672 for (var i = 0; i < this.maxGems; i++)
673 {
674 this.spawnGem(i * 200, i == this.maxGems - 1);
675 }
676
677 this.spawnInUpdate = false;
678
679 this.allGems = [];
680 },
681
682 spawnGem: function(delay, enableSpawningAfter)
683 {
684 delay = delay || 0;
685
686 if (gemSpawner.currentActive < this.maxGems)
687 {
688 gemSpawner.currentActive++;
689
690 timingUtil.delay(delay, function()
691 {
692 var x = 100 + Math.random() * (GameWindow.width - 200);
693 var y = 100 + Math.random() * (GameWindow.height - 200);
694
695 this.allGems.push(GameObject.create(gem, x, y, s_gem, 0));
696
697 this.allGems = this.allGems.filter(function(item)
698 {
699 return !item.destroyed;
700 });
701
702 if (enableSpawningAfter)
703 {
704 this.spawnInUpdate = true;
705 }
706 }, this);
707 }
708 },
709
710 onDestroy: function()
711 {
712 for (var i = 0; i < this.allGems.length; i++)
713 {
714 this.allGems[i].destroy();
715 }
716 },
717
718 update: function(deltaTime)
719 {
720 if (this.spawnInUpdate)
721 {
722 this.spawnGem(500 + (Math.random() * 500));
723 }
724 }
725}
726
727/***
728 * All images used in the game are initialized here
729 */
730
731var s_head = new image("images/head.png", 4, 4);
732var s_orb = new image("images/orb.png", 8, 4);
733var s_cell = new image("images/cells.png", 12, 4);
734var s_gem = new image("images/gems.png", 72, 6);
735
736/**
737 * Main script
738 */
739
740window.onload = init;
741
742function DoInheritance()
743{
744 //resultclass = GameObject.inherit(baseclass, childclass);
745}
746
747function init()
748{
749 DoInheritance();
750 //Game.initialize(xpos, ypos, width, height, fps, callback)
751 // -2 to account for borders
752 var width = window.innerWidth - 2;
753 var height = window.innerHeight - 2;
754
755 Game.initialize(0, 0, width, height, gameStart);
756}
757
758function gameStart()
759{
760 GameWindow.backgroundColor = {r:100, g:149, b:237};
761
762 Game.setUpdateFunction(update); // Let the game engine know we want to link our 'update()' to the game's update step.
763
764 GameAudio.init(sounds, soundsFolder);
765
766 p1 = GameObject.create(gemSpawner, GameWindow.width / 2, GameWindow.height / 2, null, 500);
767 tester = GameObject.create(creature, GameWindow.width / 3, GameWindow.height / 2, null, 500);
768
769 tester.dna = GenerateNewDNA();
770 tester.initCells();
771
772 tester2 = GameObject.create(creature, (GameWindow.width / 3) * 2, GameWindow.height / 2, null, 500);
773
774 tester2.dna = GenerateNewDNA();
775 tester2.initCells();
776}
777
778function update(deltaTime)
779{
780
781}
782
783
784
785/**
786 * All sounds in the game
787 */
788
789var soundsFolder = "sounds";
790var sounds =
791[
792 {
793 name: "bubble",
794 volume: 1
795 },
796 {
797 name: "glass",
798 volume: 0.9
799 },
800 {
801 name: "tap",
802 volume: 1
803 },
804 {
805 name: "bite",
806 volume: 1
807 },
808 {
809 name: "pop",
810 volume: 0.1
811 }
812
813]; //List of all sound files as strings (do not include file extension)
814