BlueGit

blue-star cellular-evolution

Files

cellular-evolution / js / game.js

game.js

game.js 12.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
10 start: function()
11 {
12 this.transform.scale.x = 0;
13 this.transform.scale.y = 0;
14
15 var scaleUpTween = new TWEEN.Tween(this.transform.scale);
16
17 scaleUpTween.to({x: [1.5, 1], y: [1.5, 1]}, Math.random() * 2200);
18
19 scaleUpTween.easing(TWEEN.Easing.Back.Out);
20
21 scaleUpTween.start();
22 },
23
24 update: function()
25 {
26 var rotated = this.localPos.rotate(this.parentCreature.transform.rotation);
27 this.transform.position = rotated.add(this.parentCreature.transform.position);
28 },
29
30 setType: function(typeID)
31 {
32 this.renderer.subImage = typeID;
33 }
34}
35
36/**
37 * It's a thing!
38 */
39
40var creature =
41{
42 dna: {},
43 cellInstances: [],
44
45 start: function()
46 {
47
48 },
49
50 initCells()
51 {
52 for(var i = 0; i < this.dna.length; i++)
53 {
54 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_orb, 500);
55
56 newCell.setType(this.dna[i].type);
57 newCell.parentCreature = this;
58 newCell.localPos = new vector(this.dna[i].pos.x * 32, this.dna[i].pos.y * 32)
59
60 this.cellInstances.push(newCell);
61 }
62 },
63
64 update: function(deltaTime)
65 {
66 this.transform.rotation += deltaTime * 60;
67 this.transform.position = this.transform.position.add(this.transform.forward().stretch(deltaTime * 250))
68 },
69
70 onDestroy: function()
71 {
72
73 },
74
75 onCollision: function(other)
76 {
77
78 }
79}
80
81
82/**
83 * DNA strings contain the makeup of a creature, seriving as a template for the creature factory
84 * The DNA string must be automatically generatable so that random mutations can occur.
85 *
86 * 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.
87 *
88 * 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.
89 *
90 * definitions:
91 * - cell: one out of many objects of uniform size that make up a creature
92 * - sensor: a cell that is able to detect things
93 * - 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'
94 * - Synapse: a connection between a sensor and an activator
95 * - 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)
96 *
97 * Types of mutations that can occur:
98 * - add or remove connections between sensors and activators (unlikely)
99 * - add or remove cells of any type (very unlikely)
100 * - change the strength of Synapses (likely)
101 *
102 * Types of cells:
103 * ACTIVATORS
104 * - Mouth: can Bite, which will eat whatever is in front of it, be that a cell or a food pellet
105 * - Locomotor: When activated, pushes the creature in the direction of the creature's center, relative from the locomotor cell
106 * - Rotator: Applies torque when activated. 0.5 is neural, 0 is full left, 1 is full right
107 *
108 * SENSORS
109 * - Eye: Activates whenever there is a cell or food pellet near it within a certain range and in a certain direction
110 *
111 * OTHER
112 * - 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.
113 * - Meat: A cell which does nothing except connect other cells. (and potentially function as armor)
114 * - 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
115 *
116 * 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).
117 *
118 * Examples:
119 * One cell:
120 * {
121 * ID : number. Each new cell will take the first available number so that numbers from deleted cells are re-used
122 * Type: number, corresponding to the cell type.
123 * In: [array of ID's to inbound Synapses and strength, e.g.: {ID:5,Strength:1.2},{ID:8,Strength:1.2}]
124 * 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)
125 * }
126 *
127 * The output of a Cell is determined as follows:
128 * OUT = Sigmoid ( IN1Val*IN1Weight + IN2Val*IN2Weight + IN3Val*IN3Weight + ... )
129 * 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.
130 *
131 * 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.
132 *
133 * Note that any cells which would be disconnected from the heart should be automatically removed from the DNA string
134 *
135 * --
136 *
137 * This file will handle:
138 * - Generating new DNA strings
139 * - Mutating existing DNA strings
140 */
141
142/**
143 * Potential issues:
144 *
145 * Infinite circular connections in braincells.
146 * Solutions:
147 * - Don't allow braincells to connect to braincells (would fix, but is undesirable as it limits brain complexity)
148 * - 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.
149 */
150
151//TODO: Make sort of random maybe
152function GenerateNewDNA(startingCells = 10)
153{
154 var dna = [
155 {
156 id: 0,
157 type: TYPES.HEART,
158 inputs: [],
159 pos: {x:0, y:0}
160 }
161 ];
162
163 for(var i = 0; i < startingCells; i++)
164 AddRandomCell(dna)
165
166 return dna;
167}
168
169function AddRandomCell(creature)
170{
171 var totalWeight = 0;
172 var weights = Object.values(Weights);
173
174 for (var i = 0; i < weights.length; i++)
175 {
176 totalWeight += weights[i];
177 }
178
179 var current = Math.random() * totalWeight;
180 var selected;
181
182 for (const [key, value] of Object.entries(Weights))
183 {
184 current -= value;
185
186 if(current <= 0)
187 {
188 selected = key;
189 break;
190 }
191 }
192
193 var id = 1;
194
195 for(var i = 0; i < creature.length; i++)
196 {
197 while(id == creature[i].id)
198 id++;
199 }
200
201 var done = false;
202 var pos = {x:0, y:0}
203
204 while(!done)
205 {
206 done = true;
207
208 for(var i = 0; i < creature.length; i++)
209 {
210 if(pos.x == creature[i].pos.x && pos.y == creature[i].pos.y)
211 {
212 done = false;
213 var val = Math.random() > 0.5? -1 : 1;
214 var key = Math.random() > 0.5? "y" : "x";
215
216 pos[key] += val;
217 break;
218 }
219 }
220 }
221
222 var cell =
223 {
224 id: id,
225 type: TYPES[selected],
226 inputs: [],
227 pos: pos
228 }
229
230 creature.push(cell);
231}
232
233var TYPES =
234{
235 HEART: 0,
236 BRAIN: 1,
237 MOUTH: 2,
238 LOCOMOTOR: 3,
239 ROTATOR: 4,
240 EYE: 5,
241 STOMACH: 6,
242 MEAT: 7
243}
244
245var Weights =
246{
247 BRAIN: 1,
248 MOUTH: 2,
249 LOCOMOTOR: 2,
250 ROTATOR: 1,
251 EYE: 2,
252 STOMACH: 3,
253 MEAT: 4
254}
255
256
257
258function sigmoid(z)
259{
260 return 1 / (1 + Math.exp(-z));
261}
262
263/**
264 * Snake Food
265 */
266
267var gem =
268{
269 start: function()
270 {
271 this.renderer.subImage = Math.floor(Math.random() * this.renderer.image.subImages);
272
273 this.transform.scale.x = 0;
274 this.transform.scale.y = 0;
275
276 var scaleUpTween = new TWEEN.Tween(this.transform.scale);
277
278 scaleUpTween.to({x: [1.5, 1], y: [1.5, 1]}, 800);
279
280 scaleUpTween.easing(TWEEN.Easing.Back.Out);
281
282 scaleUpTween.start();
283
284 this.shakeLength = 1000;
285 this.shakes = 4;
286 this.shakeAngle = 45;
287
288 this.minShakeTimer = 5;
289 this.maxShakeTimer = 20;
290 this.shakeTimer = this.minShakeTimer + (Math.random() * (this.maxShakeTimer - this.minShakeTimer));
291 this.currentShakeTimer = 0;
292
293 GameAudio.play("bubble");
294 },
295
296 update: function(deltaTime)
297 {
298 this.currentShakeTimer += deltaTime;
299
300 if(this.currentShakeTimer >= this.shakeTimer)
301 {
302 this.shake();
303
304 this.shakeTimer = this.minShakeTimer + (Math.random() * (this.maxShakeTimer - this.minShakeTimer));
305
306 this.currentShakeTimer = 0;
307 }
308 },
309
310 onDestroy: function()
311 {
312 gemSpawner.currentActive--;
313
314 enemySnake.edibles.remove(this);
315 },
316
317 onCollision: function(other)
318 {
319 if (other.name == "snake" && !this.destroyed)
320 {
321 other.grow(1, -1);
322 this.destroy();
323 }
324 },
325
326 shake: function(callback, context)
327 {
328 var singleShakeTime = this.shakes / this.shakeLength;
329
330 var shakeTween = new TWEEN.Tween(this.transform);
331
332 var angles = [];
333
334 var offset = Math.round(Math.random() * 5);
335
336 for (var i = 0; i < this.shakes; i++)
337 {
338 var intensiy = 1 - (i / this.shakes);
339
340 // Direction of the shake (is 'i' odd?)
341 var dir = !((i + offset) % 2)? -1 : 1;
342
343 var angleRad = this.shakeAngle;
344
345 var angle = angleRad * dir * intensiy;
346
347 angles.push(angle);
348 }
349
350 angles.push(0);
351
352 shakeTween.to({rotation: angles}, this.shakeLength);
353
354 shakeTween.easing(TWEEN.Easing.Quadratic.InOut);
355
356 if (callback)
357 {
358 shakeTween.onComplete.addOnce(callback, context);
359 }
360
361 shakeTween.start();
362 }
363}
364
365/**
366 * Gem Spawner spawns gems in the world
367 */
368var gemSpawner =
369{
370 start: function()
371 {
372 gemSpawner.currentActive = 0;
373
374 this.maxGems = 7;
375
376 for (var i = 0; i < this.maxGems; i++)
377 {
378 this.spawnGem(i * 200, i == this.maxGems - 1);
379 }
380
381 this.spawnInUpdate = false;
382
383 this.allGems = [];
384 },
385
386 spawnGem: function(delay, enableSpawningAfter)
387 {
388 delay = delay || 0;
389
390 if (gemSpawner.currentActive < this.maxGems)
391 {
392 gemSpawner.currentActive++;
393
394 timingUtil.delay(delay, function()
395 {
396 var x = 100 + Math.random() * (GameWindow.width - 200);
397 var y = 100 + Math.random() * (GameWindow.height - 200);
398
399 this.allGems.push(GameObject.create(gem, x, y, s_gem, 0));
400
401 this.allGems = this.allGems.filter(function(item)
402 {
403 return !item.destroyed;
404 });
405
406 if (enableSpawningAfter)
407 {
408 this.spawnInUpdate = true;
409 }
410 }, this);
411 }
412 },
413
414 onDestroy: function()
415 {
416 for (var i = 0; i < this.allGems.length; i++)
417 {
418 this.allGems[i].destroy();
419 }
420 },
421
422 update: function(deltaTime)
423 {
424 if (this.spawnInUpdate)
425 {
426 this.spawnGem(500 + (Math.random() * 500));
427 }
428 }
429}
430
431/***
432 * All images used in the game are initialized here
433 */
434
435var s_head = new image("images/head.png", 4, 4);
436var s_orb = new image("images/orb.png", 8, 4);
437var s_gem = new image("images/gems.png", 72, 6);
438
439/**
440 * Main script
441 */
442
443window.onload = init;
444
445function DoInheritance()
446{
447 //resultclass = GameObject.inherit(baseclass, childclass);
448}
449
450function init()
451{
452 DoInheritance();
453 //Game.initialize(xpos, ypos, width, height, fps, callback)
454 // -2 to account for borders
455 var width = window.innerWidth - 2;
456 var height = window.innerHeight - 2;
457
458 Game.initialize(0, 0, width, height, gameStart);
459}
460
461function gameStart()
462{
463 GameWindow.backgroundColor = {r:100, g:149, b:237};
464
465 Game.setUpdateFunction(update); // Let the game engine know we want to link our 'update()' to the game's update step.
466
467 GameAudio.init(sounds, soundsFolder);
468
469 p1 = GameObject.create(gemSpawner, GameWindow.width / 2, GameWindow.height / 2, null, 500);
470 tester = GameObject.create(creature, GameWindow.width / 2, GameWindow.height / 2, null, 500);
471
472 tester.dna = GenerateNewDNA();
473 tester.initCells();
474}
475
476function update(deltaTime)
477{
478
479}
480
481/**
482 * All sounds in the game
483 */
484
485var soundsFolder = "sounds";
486var sounds =
487[
488 {
489 name: "bubble",
490 volume: 1
491 },
492 {
493 name: "glass",
494 volume: 0.9
495 },
496 {
497 name: "tap",
498 volume: 1
499 },
500 {
501 name: "bite",
502 volume: 1
503 },
504 {
505 name: "pop",
506 volume: 0.1
507 }
508
509]; //List of all sound files as strings (do not include file extension)
510