BlueGit

blue-star cellular-evolution

Files

cellular-evolution / js / game.js

game.js

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