BlueGit

blue-star cellular-evolution

Files

cellular-evolution / js / game.js

game.js

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