BlueGit

blue-star cellular-evolution

Files

cellular-evolution / js / game.js

game.js

game.js 21.2 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: 100,
14 maxEnergy: 100,
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(10);
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;
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 if(rand < 0.1)
376 AddRandomCell(dna);
377
378 if(rand < 0.2)
379 AddRandomSynapse(dna);
380
381 if(rand < 0.7)
382 MutateSynapses(dna, 1 - rand);
383}
384
385function MutateSynapses(dna, strength)
386{
387 for(var i = 0; i < dna.length; i++)
388 {
389 if(dna[i].inputs.length > 0)
390 {
391 for(var o = 0; o < dna[i].inputs.length; o++)
392 {
393 dna[i].inputs[o].strength += (-0.5 + Math.random()) * strength;
394 }
395 }
396 }
397}
398
399function AddRandomSynapse(dna, att = 0)
400{
401 if(att > 10)
402 return; //can't be done, give up
403
404 var receivers = [];
405 var senders = [];
406
407 for(var i = 0; i < dna.length; i++)
408 {
409 if(dna[i].type == TYPES.BRAIN)
410 {
411 receivers.push(i);
412 senders.push(i);
413 }
414
415 if(dna[i].type == TYPES.EYE || dna[i].type == TYPES.STOMACH || dna[i].type == TYPES.NOSE || dna[i].type == TYPES.HEATSENSOR)
416 {
417 senders.push(i);
418 }
419
420 if(dna[i].type == TYPES.LOCOMOTOR || dna[i].type == TYPES.ROTATOR)
421 {
422 receivers.push(i);
423 }
424 }
425
426 var ri = Math.floor(Math.random() * receivers.length);
427 var si = Math.floor(Math.random() * senders.length)
428
429 var tri = receivers[ri]
430 var tsi = senders[si];
431
432 var OK = true
433
434 for(var i = 0; i < dna[tri].inputs.length; i++)
435 {
436 if(dna[tri].inputs[i].id == dna[tsi].id)
437 OK = false; //duplicate
438 }
439
440 if(tri != tsi && tri != 0 && tsi != 0 && OK) //todo: check for duplicates
441 {
442 dna[tri].inputs.push({id:dna[tsi].id, strength: (-0.5 + Math.random())});
443 }
444 else
445 {
446 AddRandomSynapse(dna, att + 1); //re-try
447 }
448}
449
450function AddRandomCell(dna)
451{
452 var totalWeight = 0;
453 var weights = Object.values(Weights);
454
455 for (var i = 0; i < weights.length; i++)
456 {
457 totalWeight += weights[i];
458 }
459
460 var current = Math.random() * totalWeight;
461 var selected;
462
463 for (const [key, value] of Object.entries(Weights))
464 {
465 current -= value;
466
467 if(current <= 0)
468 {
469 selected = key;
470 break;
471 }
472 }
473
474 var id = 1;
475
476 for(var i = 0; i < dna.length; i++)
477 {
478 while(id == dna[i].id)
479 id++;
480 }
481
482 var done = false;
483 var pos = {x:0, y:0}
484
485 while(!done)
486 {
487 done = true;
488
489 for(var i = 0; i < dna.length; i++)
490 {
491 if(pos.x == dna[i].pos.x && pos.y == dna[i].pos.y)
492 {
493 done = false;
494 var val = Math.random() > 0.5? -1 : 1;
495 var key = Math.random() > 0.5? "y" : "x";
496
497 pos[key] += val;
498 break;
499 }
500 }
501 }
502
503 var cell =
504 {
505 id: id,
506 type: TYPES[selected],
507 inputs: [],
508 pos: pos
509 }
510
511 dna.push(cell);
512}
513
514var TYPES =
515{
516 HEART: 0,
517 BRAIN: 1,
518 MOUTH: 2,
519 LOCOMOTOR: 3,
520 ROTATOR: 4,
521 EYE: 5,
522 STOMACH: 6,
523 MEAT: 7,
524 NOSE: 8,
525 HEATSENSOR: 9
526}
527
528var Weights =
529{
530 BRAIN: 2.2,
531 MOUTH: 2,
532 LOCOMOTOR: 2,
533 ROTATOR: 1,
534 EYE: 2.4,
535 STOMACH: 3,
536 MEAT: 4,
537 NOSE: 1.5,
538 HEATSENSOR: 1.3
539}
540
541
542
543function sigmoid(z)
544{
545 return (-0.5 + (1 / (1 + Math.exp(-z)))) * 2;
546}
547
548
549/**
550 * Snake Food
551 */
552
553var gem =
554{
555 start: function()
556 {
557 this.name = "gem";
558 this.renderer.subImage = Math.floor(Math.random() * this.renderer.image.subImages);
559
560 this.transform.scale.x = 0;
561 this.transform.scale.y = 0;
562
563 var scaleUpTween = new TWEEN.Tween(this.transform.scale);
564
565 scaleUpTween.to({x: [1.5, 1], y: [1.5, 1]}, 800);
566
567 scaleUpTween.easing(TWEEN.Easing.Back.Out);
568
569 scaleUpTween.start();
570
571 this.shakeLength = 1000;
572 this.shakes = 4;
573 this.shakeAngle = 45;
574
575 this.minShakeTimer = 5;
576 this.maxShakeTimer = 20;
577 this.shakeTimer = this.minShakeTimer + (Math.random() * (this.maxShakeTimer - this.minShakeTimer));
578 this.currentShakeTimer = 0;
579
580 GameAudio.play("bubble");
581 },
582
583 update: function(deltaTime)
584 {
585 this.currentShakeTimer += deltaTime;
586
587 if(this.currentShakeTimer >= this.shakeTimer)
588 {
589 this.shake();
590
591 this.shakeTimer = this.minShakeTimer + (Math.random() * (this.maxShakeTimer - this.minShakeTimer));
592
593 this.currentShakeTimer = 0;
594 }
595 },
596
597 onDestroy: function()
598 {
599 gemSpawner.currentActive--;
600 },
601
602 onCollision: function(other)
603 {
604 if (other.name == "snake" && !this.destroyed)
605 {
606 other.grow(1, -1);
607 this.destroy();
608 }
609 },
610
611 shake: function(callback, context)
612 {
613 var singleShakeTime = this.shakes / this.shakeLength;
614
615 var shakeTween = new TWEEN.Tween(this.transform);
616
617 var angles = [];
618
619 var offset = Math.round(Math.random() * 5);
620
621 for (var i = 0; i < this.shakes; i++)
622 {
623 var intensiy = 1 - (i / this.shakes);
624
625 // Direction of the shake (is 'i' odd?)
626 var dir = !((i + offset) % 2)? -1 : 1;
627
628 var angleRad = this.shakeAngle;
629
630 var angle = angleRad * dir * intensiy;
631
632 angles.push(angle);
633 }
634
635 angles.push(0);
636
637 shakeTween.to({rotation: angles}, this.shakeLength);
638
639 shakeTween.easing(TWEEN.Easing.Quadratic.InOut);
640
641 if (callback)
642 {
643 shakeTween.onComplete.addOnce(callback, context);
644 }
645
646 shakeTween.start();
647 }
648}
649
650/**
651 * Gem Spawner spawns gems in the world
652 */
653var gemSpawner =
654{
655 start: function()
656 {
657 gemSpawner.currentActive = 0;
658
659 this.maxGems = 7;
660
661 for (var i = 0; i < this.maxGems; i++)
662 {
663 this.spawnGem(i * 200, i == this.maxGems - 1);
664 }
665
666 this.spawnInUpdate = false;
667
668 this.allGems = [];
669 },
670
671 spawnGem: function(delay, enableSpawningAfter)
672 {
673 delay = delay || 0;
674
675 if (gemSpawner.currentActive < this.maxGems)
676 {
677 gemSpawner.currentActive++;
678
679 timingUtil.delay(delay, function()
680 {
681 var x = 100 + Math.random() * (GameWindow.width - 200);
682 var y = 100 + Math.random() * (GameWindow.height - 200);
683
684 this.allGems.push(GameObject.create(gem, x, y, s_gem, 0));
685
686 this.allGems = this.allGems.filter(function(item)
687 {
688 return !item.destroyed;
689 });
690
691 if (enableSpawningAfter)
692 {
693 this.spawnInUpdate = true;
694 }
695 }, this);
696 }
697 },
698
699 onDestroy: function()
700 {
701 for (var i = 0; i < this.allGems.length; i++)
702 {
703 this.allGems[i].destroy();
704 }
705 },
706
707 update: function(deltaTime)
708 {
709 if (this.spawnInUpdate)
710 {
711 this.spawnGem(500 + (Math.random() * 500));
712 }
713 }
714}
715
716/***
717 * All images used in the game are initialized here
718 */
719
720var s_head = new image("images/head.png", 4, 4);
721var s_orb = new image("images/orb.png", 8, 4);
722var s_cell = new image("images/cells.png", 12, 4);
723var s_gem = new image("images/gems.png", 72, 6);
724
725/**
726 * Main script
727 */
728
729window.onload = init;
730
731function DoInheritance()
732{
733 //resultclass = GameObject.inherit(baseclass, childclass);
734}
735
736function init()
737{
738 DoInheritance();
739 //Game.initialize(xpos, ypos, width, height, fps, callback)
740 // -2 to account for borders
741 var width = window.innerWidth - 2;
742 var height = window.innerHeight - 2;
743
744 Game.initialize(0, 0, width, height, gameStart);
745}
746
747function gameStart()
748{
749 GameWindow.backgroundColor = {r:100, g:149, b:237};
750
751 Game.setUpdateFunction(update); // Let the game engine know we want to link our 'update()' to the game's update step.
752
753 GameAudio.init(sounds, soundsFolder);
754
755 p1 = GameObject.create(gemSpawner, GameWindow.width / 2, GameWindow.height / 2, null, 500);
756 tester = GameObject.create(creature, GameWindow.width / 2, GameWindow.height / 2, null, 500);
757
758 tester.dna = GenerateNewDNA();
759 tester.initCells();
760}
761
762function update(deltaTime)
763{
764
765}
766
767
768
769/**
770 * All sounds in the game
771 */
772
773var soundsFolder = "sounds";
774var sounds =
775[
776 {
777 name: "bubble",
778 volume: 1
779 },
780 {
781 name: "glass",
782 volume: 0.9
783 },
784 {
785 name: "tap",
786 volume: 1
787 },
788 {
789 name: "bite",
790 volume: 1
791 },
792 {
793 name: "pop",
794 volume: 0.1
795 }
796
797]; //List of all sound files as strings (do not include file extension)
798