BlueGit

blue-star cellular-evolution

Files

cellular-evolution / js / game.js

game.js

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