BlueGit

blue-star cellular-evolution

Files

cellular-evolution / js / game.js

game.js

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