BlueGit

blue-star cellular-evolution

Files

cellular-evolution / js / game.js

game.js

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