BlueGit

blue-star cellular-evolution

Files

cellular-evolution / js / game.js

game.js

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