├── .gitattributes ├── ConnectionGene.js ├── ConnectionHistory.js ├── GENOME.JS ├── Node.js ├── Player.js ├── PlayerOld.js ├── Population.js ├── README.md ├── Species.js ├── index.html ├── libraries ├── p5.dom.js ├── p5.js └── p5.sound.js └── sketch.js /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /ConnectionGene.js: -------------------------------------------------------------------------------- 1 | //a connection between 2 nodes 2 | class connectionGene { 3 | constructor(from, to, w, inno) { 4 | this.fromNode = from; 5 | this.toNode = to; 6 | this.weight = w; 7 | this.enabled = true; 8 | this.innovationNo = inno; //each connection is given a innovation number to compare genomes 9 | 10 | } 11 | 12 | //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 13 | //changes the this.weight 14 | mutateWeight() { 15 | var rand2 = random(1); 16 | if (rand2 < 0.1) { //10% of the time completely change the this.weight 17 | this.weight = random(-1, 1); 18 | } else { //otherwise slightly change it 19 | this.weight += (randomGaussian() / 50); 20 | //keep this.weight between bounds 21 | if (this.weight > 1) { 22 | this.weight = 1; 23 | } 24 | if (this.weight < -1) { 25 | this.weight = -1; 26 | 27 | } 28 | } 29 | } 30 | 31 | //---------------------------------------------------------------------------------------------------------- 32 | //returns a copy of this connectionGene 33 | clone(from, to) { 34 | var clone = new connectionGene(from, to, this.weight, this.innovationNo); 35 | clone.enabled = this.enabled; 36 | 37 | return clone; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /ConnectionHistory.js: -------------------------------------------------------------------------------- 1 | class connectionHistory { 2 | constructor(from, to, inno, innovationNos) { 3 | this.fromNode = from; 4 | this.toNode = to; 5 | this.innovationNumber = inno; 6 | this.innovationNumbers = []; //the innovation Numbers from the connections of the genome which first had this mutation 7 | //this represents the genome and allows us to test if another genoeme is the same 8 | //this is before this connection was added 9 | arrayCopy(innovationNos, this.innovationNumbers); //copy (from, to) 10 | } 11 | 12 | //---------------------------------------------------------------------------------------------------------------- 13 | //returns whether the genome matches the original genome and the connection is between the same nodes 14 | matches(genome, from, to) { 15 | if (genome.genes.length === this.innovationNumbers.length) { //if the number of connections are different then the genoemes aren't the same 16 | if (from.number === this.fromNode && to.number === this.toNode) { 17 | //next check if all the innovation numbers match from the genome 18 | for (var i = 0; i < genome.genes.length; i++) { 19 | if (!this.innovationNumbers.includes(genome.genes[i].innovationNo)) { 20 | return false; 21 | } 22 | } 23 | //if reached this far then the innovationNumbers match the genes innovation numbers and the connection is between the same nodes 24 | //so it does match 25 | return true; 26 | } 27 | } 28 | return false; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /GENOME.JS: -------------------------------------------------------------------------------- 1 | class Genome { 2 | constructor(inputs, outputs, crossover) { 3 | this.genes = []; //a list of connections between this.nodes which represent the NN 4 | this.nodes = []; 5 | this.inputs = inputs; 6 | this.outputs = outputs; 7 | this.layers = 2; 8 | this.nextNode = 0; 9 | // this.biasNode; 10 | this.network = []; //a list of the this.nodes in the order that they need to be considered in the NN 11 | //create input this.nodes 12 | 13 | if (crossover) { 14 | return; 15 | } 16 | 17 | for (var i = 0; i < this.inputs; i++) { 18 | this.nodes.push(new Node(i)); 19 | this.nextNode++; 20 | this.nodes[i].layer = 0; 21 | } 22 | 23 | //create output this.nodes 24 | for (var i = 0; i < this.outputs; i++) { 25 | this.nodes.push(new Node(i + this.inputs)); 26 | this.nodes[i + this.inputs].layer = 1; 27 | this.nextNode++; 28 | } 29 | 30 | this.nodes.push(new Node(this.nextNode)); //bias node 31 | this.biasNode = this.nextNode; 32 | this.nextNode++; 33 | this.nodes[this.biasNode].layer = 0; 34 | 35 | 36 | 37 | } 38 | 39 | 40 | fullyConnect(innovationHistory) { 41 | 42 | //this will be a new number if no identical genome has mutated in the same 43 | 44 | for (var i = 0; i < this.inputs; i++) { 45 | for (var j = 0; j < this.outputs; j++) { 46 | var connectionInnovationNumber = this.getInnovationNumber(innovationHistory, this.nodes[i], this.nodes[this.nodes.length - j - 2]); 47 | this.genes.push(new connectionGene(this.nodes[i], this.nodes[this.nodes.length - j - 2], random(-1, 1), connectionInnovationNumber)); 48 | } 49 | } 50 | 51 | var connectionInnovationNumber = this.getInnovationNumber(innovationHistory, this.nodes[this.biasNode], this.nodes[this.nodes.length - 2]); 52 | this.genes.push(new connectionGene(this.nodes[this.biasNode], this.nodes[this.nodes.length - 2], random(-1, 1), connectionInnovationNumber)); 53 | 54 | connectionInnovationNumber = this.getInnovationNumber(innovationHistory, this.nodes[this.biasNode], this.nodes[this.nodes.length - 3]); 55 | this.genes.push(new connectionGene(this.nodes[this.biasNode], this.nodes[this.nodes.length - 3], random(-1, 1), connectionInnovationNumber)); 56 | //add the connection with a random array 57 | 58 | 59 | //changed this so if error here 60 | this.connectNodes(); 61 | } 62 | 63 | 64 | 65 | //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 66 | //returns the node with a matching number 67 | //sometimes the this.nodes will not be in order 68 | getNode(nodeNumber) { 69 | for (var i = 0; i < this.nodes.length; i++) { 70 | if (this.nodes[i].number == nodeNumber) { 71 | return this.nodes[i]; 72 | } 73 | } 74 | return null; 75 | } 76 | 77 | 78 | //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 79 | //adds the conenctions going out of a node to that node so that it can acess the next node during feeding forward 80 | connectNodes() { 81 | 82 | for (var i = 0; i < this.nodes.length; i++) { //clear the connections 83 | this.nodes[i].outputConnections = []; 84 | } 85 | 86 | for (var i = 0; i < this.genes.length; i++) { //for each connectionGene 87 | this.genes[i].fromNode.outputConnections.push(this.genes[i]); //add it to node 88 | } 89 | } 90 | 91 | //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 92 | //feeding in input values varo the NN and returning output array 93 | feedForward(inputValues) { 94 | //set the outputs of the input this.nodes 95 | for (var i = 0; i < this.inputs; i++) { 96 | this.nodes[i].outputValue = inputValues[i]; 97 | } 98 | this.nodes[this.biasNode].outputValue = 1; //output of bias is 1 99 | 100 | for (var i = 0; i < this.network.length; i++) { //for each node in the network engage it(see node class for what this does) 101 | this.network[i].engage(); 102 | } 103 | 104 | //the outputs are this.nodes[inputs] to this.nodes [inputs+outputs-1] 105 | var outs = []; 106 | for (var i = 0; i < this.outputs; i++) { 107 | outs[i] = this.nodes[this.inputs + i].outputValue; 108 | } 109 | 110 | for (var i = 0; i < this.nodes.length; i++) { //reset all the this.nodes for the next feed forward 111 | this.nodes[i].inputSum = 0; 112 | } 113 | 114 | return outs; 115 | } 116 | 117 | //---------------------------------------------------------------------------------------------------------------------------------------- 118 | //sets up the NN as a list of this.nodes in order to be engaged 119 | 120 | generateNetwork() { 121 | this.connectNodes(); 122 | this.network = []; 123 | //for each layer add the node in that layer, since layers cannot connect to themselves there is no need to order the this.nodes within a layer 124 | 125 | for (var l = 0; l < this.layers; l++) { //for each layer 126 | for (var i = 0; i < this.nodes.length; i++) { //for each node 127 | if (this.nodes[i].layer == l) { //if that node is in that layer 128 | this.network.push(this.nodes[i]); 129 | } 130 | } 131 | } 132 | } 133 | //----------------------------------------------------------------------------------------------------------------------------------------- 134 | //mutate the NN by adding a new node 135 | //it does this by picking a random connection and disabling it then 2 new connections are added 136 | //1 between the input node of the disabled connection and the new node 137 | //and the other between the new node and the output of the disabled connection 138 | addNode(innovationHistory) { 139 | //pick a random connection to create a node between 140 | if (this.genes.length == 0) { 141 | this.addConnection(innovationHistory); 142 | return; 143 | } 144 | var randomConnection = floor(random(this.genes.length)); 145 | 146 | while (this.genes[randomConnection].fromNode == this.nodes[this.biasNode] && this.genes.length != 1) { //dont disconnect bias 147 | randomConnection = floor(random(this.genes.length)); 148 | } 149 | 150 | this.genes[randomConnection].enabled = false; //disable it 151 | 152 | var newNodeNo = this.nextNode; 153 | this.nodes.push(new Node(newNodeNo)); 154 | this.nextNode++; 155 | //add a new connection to the new node with a weight of 1 156 | var connectionInnovationNumber = this.getInnovationNumber(innovationHistory, this.genes[randomConnection].fromNode, this.getNode(newNodeNo)); 157 | this.genes.push(new connectionGene(this.genes[randomConnection].fromNode, this.getNode(newNodeNo), 1, connectionInnovationNumber)); 158 | 159 | 160 | connectionInnovationNumber = this.getInnovationNumber(innovationHistory, this.getNode(newNodeNo), this.genes[randomConnection].toNode); 161 | //add a new connection from the new node with a weight the same as the disabled connection 162 | this.genes.push(new connectionGene(this.getNode(newNodeNo), this.genes[randomConnection].toNode, this.genes[randomConnection].weight, connectionInnovationNumber)); 163 | this.getNode(newNodeNo).layer = this.genes[randomConnection].fromNode.layer + 1; 164 | 165 | 166 | connectionInnovationNumber = this.getInnovationNumber(innovationHistory, this.nodes[this.biasNode], this.getNode(newNodeNo)); 167 | //connect the bias to the new node with a weight of 0 168 | this.genes.push(new connectionGene(this.nodes[this.biasNode], this.getNode(newNodeNo), 0, connectionInnovationNumber)); 169 | 170 | //if the layer of the new node is equal to the layer of the output node of the old connection then a new layer needs to be created 171 | //more accurately the layer numbers of all layers equal to or greater than this new node need to be incrimented 172 | if (this.getNode(newNodeNo).layer == this.genes[randomConnection].toNode.layer) { 173 | for (var i = 0; i < this.nodes.length - 1; i++) { //dont include this newest node 174 | if (this.nodes[i].layer >= this.getNode(newNodeNo).layer) { 175 | this.nodes[i].layer++; 176 | } 177 | } 178 | this.layers++; 179 | } 180 | this.connectNodes(); 181 | } 182 | 183 | //------------------------------------------------------------------------------------------------------------------ 184 | //adds a connection between 2 this.nodes which aren't currently connected 185 | addConnection(innovationHistory) { 186 | //cannot add a connection to a fully connected network 187 | if (this.fullyConnected()) { 188 | console.log("connection failed"); 189 | return; 190 | } 191 | 192 | 193 | //get random this.nodes 194 | var randomNode1 = floor(random(this.nodes.length)); 195 | var randomNode2 = floor(random(this.nodes.length)); 196 | while (this.randomConnectionNodesAreShit(randomNode1, randomNode2)) { //while the random this.nodes are no good 197 | //get new ones 198 | randomNode1 = floor(random(this.nodes.length)); 199 | randomNode2 = floor(random(this.nodes.length)); 200 | } 201 | var temp; 202 | if (this.nodes[randomNode1].layer > this.nodes[randomNode2].layer) { //if the first random node is after the second then switch 203 | temp = randomNode2; 204 | randomNode2 = randomNode1; 205 | randomNode1 = temp; 206 | } 207 | 208 | //get the innovation number of the connection 209 | //this will be a new number if no identical genome has mutated in the same way 210 | var connectionInnovationNumber = this.getInnovationNumber(innovationHistory, this.nodes[randomNode1], this.nodes[randomNode2]); 211 | //add the connection with a random array 212 | 213 | this.genes.push(new connectionGene(this.nodes[randomNode1], this.nodes[randomNode2], random(-1, 1), connectionInnovationNumber)); //changed this so if error here 214 | this.connectNodes(); 215 | } 216 | //------------------------------------------------------------------------------------------------------------------------------------------- 217 | randomConnectionNodesAreShit(r1, r2) { 218 | if (this.nodes[r1].layer == this.nodes[r2].layer) return true; // if the this.nodes are in the same layer 219 | if (this.nodes[r1].isConnectedTo(this.nodes[r2])) return true; //if the this.nodes are already connected 220 | 221 | 222 | 223 | return false; 224 | } 225 | 226 | //------------------------------------------------------------------------------------------------------------------------------------------- 227 | //returns the innovation number for the new mutation 228 | //if this mutation has never been seen before then it will be given a new unique innovation number 229 | //if this mutation matches a previous mutation then it will be given the same innovation number as the previous one 230 | getInnovationNumber(innovationHistory, from, to) { 231 | var isNew = true; 232 | var connectionInnovationNumber = nextConnectionNo; 233 | for (var i = 0; i < innovationHistory.length; i++) { //for each previous mutation 234 | if (innovationHistory[i].matches(this, from, to)) { //if match found 235 | isNew = false; //its not a new mutation 236 | connectionInnovationNumber = innovationHistory[i].innovationNumber; //set the innovation number as the innovation number of the match 237 | break; 238 | } 239 | } 240 | 241 | if (isNew) { //if the mutation is new then create an arrayList of varegers representing the current state of the genome 242 | var innoNumbers = []; 243 | for (var i = 0; i < this.genes.length; i++) { //set the innovation numbers 244 | innoNumbers.push(this.genes[i].innovationNo); 245 | } 246 | 247 | //then add this mutation to the innovationHistory 248 | innovationHistory.push(new connectionHistory(from.number, to.number, connectionInnovationNumber, innoNumbers)); 249 | nextConnectionNo++; 250 | } 251 | return connectionInnovationNumber; 252 | } 253 | //---------------------------------------------------------------------------------------------------------------------------------------- 254 | 255 | //returns whether the network is fully connected or not 256 | fullyConnected() { 257 | 258 | var maxConnections = 0; 259 | var nodesInLayers = []; //array which stored the amount of this.nodes in each layer 260 | for (var i = 0; i < this.layers; i++) { 261 | nodesInLayers[i] = 0; 262 | } 263 | //populate array 264 | for (var i = 0; i < this.nodes.length; i++) { 265 | nodesInLayers[this.nodes[i].layer] += 1; 266 | } 267 | //for each layer the maximum amount of connections is the number in this layer * the number of this.nodes infront of it 268 | //so lets add the max for each layer together and then we will get the maximum amount of connections in the network 269 | for (var i = 0; i < this.layers - 1; i++) { 270 | var nodesInFront = 0; 271 | for (var j = i + 1; j < this.layers; j++) { //for each layer infront of this layer 272 | nodesInFront += nodesInLayers[j]; //add up this.nodes 273 | } 274 | 275 | maxConnections += nodesInLayers[i] * nodesInFront; 276 | } 277 | 278 | if (maxConnections <= this.genes.length) { //if the number of connections is equal to the max number of connections possible then it is full 279 | return true; 280 | } 281 | 282 | return false; 283 | } 284 | 285 | 286 | //------------------------------------------------------------------------------------------------------------------------------- 287 | //mutates the genome 288 | mutate(innovationHistory) { 289 | if (this.genes.length == 0) { 290 | this.addConnection(innovationHistory); 291 | } 292 | 293 | 294 | var rand1 = random(1); 295 | if (rand1 < 0.8) { // 80% of the time mutate weights 296 | 297 | for (var i = 0; i < this.genes.length; i++) { 298 | this.genes[i].mutateWeight(); 299 | } 300 | } 301 | 302 | //5% of the time add a new connection 303 | var rand2 = random(1); 304 | if (rand2 < 0.05) { 305 | 306 | this.addConnection(innovationHistory); 307 | } 308 | 309 | //1% of the time add a node 310 | var rand3 = random(1); 311 | if (rand3 < 0.01) { 312 | 313 | this.addNode(innovationHistory); 314 | } 315 | } 316 | 317 | //--------------------------------------------------------------------------------------------------------------------------------- 318 | //called when this Genome is better that the other parent 319 | crossover(parent2) { 320 | var child = new Genome(this.inputs, this.outputs, true); 321 | child.genes = []; 322 | child.nodes = []; 323 | child.layers = this.layers; 324 | child.nextNode = this.nextNode; 325 | child.biasNode = this.biasNode; 326 | var childGenes = []; // new ArrayList();//list of genes to be inherrited form the parents 327 | var isEnabled = []; // new ArrayList(); 328 | //all inherited genes 329 | for (var i = 0; i < this.genes.length; i++) { 330 | var setEnabled = true; //is this node in the chlid going to be enabled 331 | 332 | var parent2gene = this.matchingGene(parent2, this.genes[i].innovationNo); 333 | if (parent2gene != -1) { //if the genes match 334 | if (!this.genes[i].enabled || !parent2.genes[parent2gene].enabled) { //if either of the matching genes are disabled 335 | 336 | if (random(1) < 0.75) { //75% of the time disabel the childs gene 337 | setEnabled = false; 338 | } 339 | } 340 | var rand = random(1); 341 | if (rand < 0.5) { 342 | childGenes.push(this.genes[i]); 343 | 344 | //get gene from this fucker 345 | } else { 346 | //get gene from parent2 347 | childGenes.push(parent2.genes[parent2gene]); 348 | } 349 | } else { //disjoint or excess gene 350 | childGenes.push(this.genes[i]); 351 | setEnabled = this.genes[i].enabled; 352 | } 353 | isEnabled.push(setEnabled); 354 | } 355 | 356 | 357 | //since all excess and disjovar genes are inherrited from the more fit parent (this Genome) the childs structure is no different from this parent | with exception of dormant connections being enabled but this wont effect this.nodes 358 | //so all the this.nodes can be inherrited from this parent 359 | for (var i = 0; i < this.nodes.length; i++) { 360 | child.nodes.push(this.nodes[i].clone()); 361 | } 362 | 363 | //clone all the connections so that they connect the childs new this.nodes 364 | 365 | for (var i = 0; i < childGenes.length; i++) { 366 | child.genes.push(childGenes[i].clone(child.getNode(childGenes[i].fromNode.number), child.getNode(childGenes[i].toNode.number))); 367 | child.genes[i].enabled = isEnabled[i]; 368 | } 369 | 370 | child.connectNodes(); 371 | return child; 372 | } 373 | 374 | //---------------------------------------------------------------------------------------------------------------------------------------- 375 | //returns whether or not there is a gene matching the input innovation number in the input genome 376 | matchingGene(parent2, innovationNumber) { 377 | for (var i = 0; i < parent2.genes.length; i++) { 378 | if (parent2.genes[i].innovationNo == innovationNumber) { 379 | return i; 380 | } 381 | } 382 | return -1; //no matching gene found 383 | } 384 | //---------------------------------------------------------------------------------------------------------------------------------------- 385 | //prints out info about the genome to the console 386 | printGenome() { 387 | console.log("Prvar genome layers:" + this.layers); 388 | console.log("bias node: " + this.biasNode); 389 | console.log("this.nodes"); 390 | for (var i = 0; i < this.nodes.length; i++) { 391 | console.log(this.nodes[i].number + ","); 392 | } 393 | console.log("Genes"); 394 | for (var i = 0; i < this.genes.length; i++) { //for each connectionGene 395 | console.log("gene " + this.genes[i].innovationNo + "From node " + this.genes[i].fromNode.number + "To node " + this.genes[i].toNode.number + 396 | "is enabled " + this.genes[i].enabled + "from layer " + this.genes[i].fromNode.layer + "to layer " + this.genes[i].toNode.layer + "weight: " + this.genes[i].weight); 397 | } 398 | 399 | console.log(); 400 | } 401 | 402 | //---------------------------------------------------------------------------------------------------------------------------------------- 403 | //returns a copy of this genome 404 | clone() { 405 | 406 | var clone = new Genome(this.inputs, this.outputs, true); 407 | 408 | for (var i = 0; i < this.nodes.length; i++) { //copy this.nodes 409 | clone.nodes.push(this.nodes[i].clone()); 410 | } 411 | 412 | //copy all the connections so that they connect the clone new this.nodes 413 | 414 | for (var i = 0; i < this.genes.length; i++) { //copy genes 415 | clone.genes.push(this.genes[i].clone(clone.getNode(this.genes[i].fromNode.number), clone.getNode(this.genes[i].toNode.number))); 416 | } 417 | 418 | clone.layers = this.layers; 419 | clone.nextNode = this.nextNode; 420 | clone.biasNode = this.biasNode; 421 | clone.connectNodes(); 422 | 423 | return clone; 424 | } 425 | //---------------------------------------------------------------------------------------------------------------------------------------- 426 | //draw the genome on the screen 427 | drawGenome(startX, startY, w, h) { 428 | //i know its ugly but it works (and is not that important) so I'm not going to mess with it 429 | var allNodes = []; //new ArrayList>(); 430 | var nodePoses = []; // new ArrayList(); 431 | var nodeNumbers = []; // new ArrayList(); 432 | 433 | //get the positions on the screen that each node is supposed to be in 434 | 435 | 436 | //split the this.nodes varo layers 437 | for (var i = 0; i < this.layers; i++) { 438 | var temp = []; // new ArrayList(); 439 | for (var j = 0; j < this.nodes.length; j++) { //for each node 440 | if (this.nodes[j].layer == i) { //check if it is in this layer 441 | temp.push(this.nodes[j]); //add it to this layer 442 | } 443 | } 444 | allNodes.push(temp); //add this layer to all this.nodes 445 | } 446 | 447 | //for each layer add the position of the node on the screen to the node posses arraylist 448 | for (var i = 0; i < this.layers; i++) { 449 | fill(255, 0, 0); 450 | var x = startX + float((i + 1.0) * w) / float(this.layers + 1.0); 451 | for (var j = 0; j < allNodes[i].length; j++) { //for the position in the layer 452 | var y = startY + float((j + 1.0) * h) / float(allNodes[i].length + 1.0); 453 | nodePoses.push(createVector(x, y)); 454 | nodeNumbers.push(allNodes[i][j].number); 455 | } 456 | } 457 | 458 | //draw connections 459 | stroke(0); 460 | strokeWeight(2); 461 | for (var i = 0; i < this.genes.length; i++) { 462 | if (this.genes[i].enabled) { 463 | stroke(0); 464 | } else { 465 | stroke(100); 466 | } 467 | var from; 468 | var to; 469 | from = nodePoses[nodeNumbers.indexOf(this.genes[i].fromNode.number)]; 470 | to = nodePoses[nodeNumbers.indexOf(this.genes[i].toNode.number)]; 471 | if (this.genes[i].weight > 0) { 472 | stroke(255, 0, 0); 473 | } else { 474 | stroke(0, 0, 255); 475 | } 476 | strokeWeight(map(abs(this.genes[i].weight), 0, 1, 0, 3)); 477 | line(from.x, from.y, to.x, to.y); 478 | } 479 | 480 | //draw this.nodes last so they appear ontop of the connection lines 481 | for (var i = 0; i < nodePoses.length; i++) { 482 | fill(255); 483 | stroke(0); 484 | strokeWeight(1); 485 | ellipse(nodePoses[i].x, nodePoses[i].y, 20, 20); 486 | textSize(10); 487 | fill(0); 488 | textAlign(CENTER, CENTER); 489 | text(nodeNumbers[i], nodePoses[i].x, nodePoses[i].y); 490 | 491 | } 492 | 493 | // print out neural network info text 494 | // textAlign(RIGHT); 495 | // fill(255); 496 | // textSize(15); 497 | // noStroke(); 498 | // text("car angle", nodePoses[0].x - 20, nodePoses[0].y); 499 | // text("touching ground", nodePoses[1].x - 20, nodePoses[1].y); 500 | // text("angular velocity", nodePoses[2].x - 20, nodePoses[2].y); 501 | // text("Distance to ground", nodePoses[3].x - 20, nodePoses[3].y); 502 | // text("gradient", nodePoses[4].x - 20, nodePoses[4].y); 503 | // text("bias", nodePoses[5].x - 20, nodePoses[5].y); 504 | // textAlign(LEFT); 505 | // text("gas", nodePoses[nodePoses.length - 2].x + 20, nodePoses[nodePoses.length - 2].y); 506 | // text("break", nodePoses[nodePoses.length - 1].x + 20, nodePoses[nodePoses.length - 1].y); 507 | 508 | 509 | 510 | } 511 | } 512 | -------------------------------------------------------------------------------- /Node.js: -------------------------------------------------------------------------------- 1 | class Node { 2 | 3 | constructor(no) { 4 | this.number = no; 5 | this.inputSum = 0; //current sum i.e. before activation 6 | this.outputValue = 0; //after activation function is applied 7 | this.outputConnections = []; //new ArrayList(); 8 | this.layer = 0; 9 | this.drawPos = createVector(); 10 | } 11 | 12 | //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 13 | //the node sends its output to the inputs of the nodes its connected to 14 | engage() { 15 | if(this.layer != 0) { //no sigmoid for the inputs and bias 16 | this.outputValue = this.sigmoid(this.inputSum); 17 | } 18 | 19 | for(var i = 0; i < this.outputConnections.length; i++) { //for each connection 20 | if(this.outputConnections[i].enabled) { //dont do shit if not enabled 21 | this.outputConnections[i].toNode.inputSum += this.outputConnections[i].weight * this.outputValue; //add the weighted output to the sum of the inputs of whatever node this node is connected to 22 | } 23 | } 24 | } 25 | //---------------------------------------------------------------------------------------------------------------------------------------- 26 | //not used 27 | stepFunction(x) { 28 | if(x < 0) { 29 | return 0; 30 | } else { 31 | return 1; 32 | } 33 | } 34 | //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 35 | //sigmoid activation function 36 | sigmoid(x) { 37 | return 1.0 / (1.0 + pow(Math.E, -4.9 * x)); //todo check pow 38 | } 39 | //---------------------------------------------------------------------------------------------------------------------------------------------------------- 40 | //returns whether this node connected to the parameter node 41 | //used when adding a new connection 42 | isConnectedTo(node) { 43 | if(node.layer == this.layer) { //nodes in the same this.layer cannot be connected 44 | return false; 45 | } 46 | 47 | //you get it 48 | if(node.layer < this.layer) { 49 | for(var i = 0; i < node.outputConnections.length; i++) { 50 | if(node.outputConnections[i].toNode == this) { 51 | return true; 52 | } 53 | } 54 | } else { 55 | for(var i = 0; i < this.outputConnections.length; i++) { 56 | if(this.outputConnections[i].toNode == node) { 57 | return true; 58 | } 59 | } 60 | } 61 | 62 | return false; 63 | } 64 | //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 65 | //returns a copy of this node 66 | clone() { 67 | var clone = new Node(this.number); 68 | clone.layer = this.layer; 69 | return clone; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Player.js: -------------------------------------------------------------------------------- 1 | class Player { 2 | 3 | constructor() { 4 | 5 | this.fitness = 0; 6 | this.vision = []; //the input array fed into the neuralNet 7 | this.decision = []; //the out put of the NN 8 | this.unadjustedFitness; 9 | this.lifespan = 0; //how long the player lived for this.fitness 10 | this.bestScore = 0; //stores the this.score achieved used for replay 11 | this.dead = false; 12 | this.score = 0; 13 | this.gen = 0; 14 | 15 | this.genomeInputs = 5; 16 | this.genomeOutputs = 2; 17 | this.brain = new Genome(this.genomeInputs, this.genomeOutputs); 18 | } 19 | 20 | //--------------------------------------------------------------------------------------------------------------------------------------------------------- 21 | show() { 22 | //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< max) { 51 | max = this.decision[i]; 52 | maxIndex = i; 53 | } 54 | } 55 | 56 | //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< max) { 51 | max = this.decision[i]; 52 | maxIndex = i; 53 | } 54 | } 55 | 56 | //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<(); 5 | this.bestPlayer; //the best ever player 6 | this.bestScore = 0; //the score of the best ever player 7 | this.globalBestScore = 0; 8 | this.gen = 1; 9 | this.innovationHistory = []; // new ArrayList(); 10 | this.genPlayers = []; //new ArrayList(); 11 | this.species = []; //new ArrayList(); 12 | 13 | this.massExtinctionEvent = false; 14 | this.newStage = false; 15 | 16 | for (var i = 0; i < size; i++) { 17 | this.players.push(new Player()); 18 | this.players[this.players.length - 1].brain.mutate(this.innovationHistory); 19 | this.players[this.players.length - 1].brain.generateNetwork(); 20 | } 21 | } 22 | updateAlive() { 23 | for (var i = 0; i < this.players.length; i++) { 24 | if (!this.players[i].dead) { 25 | this.players[i].look(); //get inputs for brain 26 | this.players[i].think(); //use outputs from neural network 27 | this.players[i].update(); //move the player according to the outputs from the neural network 28 | if (!showNothing && (!showBest || i == 0)) { 29 | this.players[i].show(); 30 | } 31 | if (this.players[i].score > this.globalBestScore) { 32 | this.globalBestScore = this.players[i].score; 33 | } 34 | } 35 | } 36 | 37 | } 38 | //------------------------------------------------------------------------------------------------------------------------------------------ 39 | //returns true if all the players are dead sad 40 | done() { 41 | for (var i = 0; i < this.players.length; i++) { 42 | if (!this.players[i].dead) { 43 | return false; 44 | } 45 | } 46 | return true; 47 | } 48 | //------------------------------------------------------------------------------------------------------------------------------------------ 49 | //sets the best player globally and for thisthis.gen 50 | setBestPlayer() { 51 | var tempBest = this.species[0].players[0]; 52 | tempBest.gen = this.gen; 53 | 54 | 55 | //if best thisthis.gen is better than the global best score then set the global best as the best thisthis.gen 56 | 57 | if (tempBest.score >= this.bestScore) { 58 | this.genPlayers.push(tempBest.cloneForReplay()); 59 | console.log("old best: " + this.bestScore); 60 | console.log("new best: " + tempBest.score); 61 | this.bestScore = tempBest.score; 62 | this.bestPlayer = tempBest.cloneForReplay(); 63 | } 64 | } 65 | 66 | //------------------------------------------------------------------------------------------------------------------------------------------------ 67 | //this function is called when all the players in the this.players are dead and a newthis.generation needs to be made 68 | naturalSelection() { 69 | 70 | // this.batchNo = 0; 71 | var previousBest = this.players[0]; 72 | this.speciate(); //seperate the this.players varo this.species 73 | this.calculateFitness(); //calculate the fitness of each player 74 | this.sortSpecies(); //sort the this.species to be ranked in fitness order, best first 75 | if (this.massExtinctionEvent) { 76 | this.massExtinction(); 77 | this.massExtinctionEvent = false; 78 | } 79 | this.cullSpecies(); //kill off the bottom half of each this.species 80 | this.setBestPlayer(); //save the best player of thisthis.gen 81 | this.killStaleSpecies(); //remove this.species which haven't improved in the last 15(ish)this.generations 82 | this.killBadSpecies(); //kill this.species which are so bad that they cant reproduce 83 | 84 | // if (this.gensSinceNewWorld >= 0 || this.bestScore > (grounds[0].distance - 350) / 10) { 85 | // this.gensSinceNewWorld = 0; 86 | // console.log(this.gensSinceNewWorld); 87 | // console.log(this.bestScore); 88 | // console.log(grounds[0].distance); 89 | // newWorlds(); 90 | // } 91 | 92 | console.log("generation " + this.gen + " Number of mutations " + this.innovationHistory.length + " species: " + this.species.length + " <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"); 93 | 94 | 95 | var averageSum = this.getAvgFitnessSum(); 96 | var children = []; 97 | for (var j = 0; j < this.species.length; j++) { //for each this.species 98 | children.push(this.species[j].champ.clone()); //add champion without any mutation 99 | var NoOfChildren = floor(this.species[j].averageFitness / averageSum * this.players.length) - 1; //the number of children this this.species is allowed, note -1 is because the champ is already added 100 | for (var i = 0; i < NoOfChildren; i++) { //get the calculated amount of children from this this.species 101 | children.push(this.species[j].giveMeBaby(this.innovationHistory)); 102 | } 103 | } 104 | if (children.length < this.players.length) { 105 | children.push(previousBest.clone()); 106 | } 107 | while (children.length < this.players.length) { //if not enough babies (due to flooring the number of children to get a whole var) 108 | children.push(this.species[0].giveMeBaby(this.innovationHistory)); //get babies from the best this.species 109 | } 110 | 111 | this.players = []; 112 | arrayCopy(children, this.players); //set the children as the current this.playersulation 113 | this.gen += 1; 114 | for (var i = 0; i < this.players.length; i++) { //generate networks for each of the children 115 | this.players[i].brain.generateNetwork(); 116 | } 117 | } 118 | 119 | //------------------------------------------------------------------------------------------------------------------------------------------ 120 | //seperate this.players into this.species based on how similar they are to the leaders of each this.species in the previousthis.gen 121 | speciate() { 122 | for (var s of this.species) { //empty this.species 123 | s.players = []; 124 | } 125 | for (var i = 0; i < this.players.length; i++) { //for each player 126 | var speciesFound = false; 127 | for (var s of this.species) { //for each this.species 128 | if (s.sameSpecies(this.players[i].brain)) { //if the player is similar enough to be considered in the same this.species 129 | s.addToSpecies(this.players[i]); //add it to the this.species 130 | speciesFound = true; 131 | break; 132 | } 133 | } 134 | if (!speciesFound) { //if no this.species was similar enough then add a new this.species with this as its champion 135 | this.species.push(new Species(this.players[i])); 136 | } 137 | } 138 | } 139 | //------------------------------------------------------------------------------------------------------------------------------------------ 140 | //calculates the fitness of all of the players 141 | calculateFitness() { 142 | for (var i = 1; i < this.players.length; i++) { 143 | this.players[i].calculateFitness(); 144 | } 145 | } 146 | //------------------------------------------------------------------------------------------------------------------------------------------ 147 | //sorts the players within a this.species and the this.species by their fitnesses 148 | sortSpecies() { 149 | //sort the players within a this.species 150 | for (var s of this.species) { 151 | s.sortSpecies(); 152 | } 153 | 154 | //sort the this.species by the fitness of its best player 155 | //using selection sort like a loser 156 | var temp = []; //new ArrayList(); 157 | for (var i = 0; i < this.species.length; i++) { 158 | var max = 0; 159 | var maxIndex = 0; 160 | for (var j = 0; j < this.species.length; j++) { 161 | if (this.species[j].bestFitness > max) { 162 | max = this.species[j].bestFitness; 163 | maxIndex = j; 164 | } 165 | } 166 | temp.push(this.species[maxIndex]); 167 | this.species.splice(maxIndex, 1); 168 | // this.species.remove(maxIndex); 169 | i--; 170 | } 171 | this.species = []; 172 | arrayCopy(temp, this.species); 173 | 174 | } 175 | //------------------------------------------------------------------------------------------------------------------------------------------ 176 | //kills all this.species which haven't improved in 15this.generations 177 | killStaleSpecies() { 178 | for (var i = 2; i < this.species.length; i++) { 179 | if (this.species[i].staleness >= 15) { 180 | // .remove(i); 181 | // splice(this.species, i) 182 | this.species.splice(i, 1); 183 | i--; 184 | } 185 | } 186 | } 187 | //------------------------------------------------------------------------------------------------------------------------------------------ 188 | //if a this.species sucks so much that it wont even be allocated 1 child for the nextthis.generation then kill it now 189 | killBadSpecies() { 190 | var averageSum = this.getAvgFitnessSum(); 191 | 192 | for (var i = 1; i < this.species.length; i++) { 193 | if (this.species[i].averageFitness / averageSum * this.players.length < 1) { //if wont be given a single child 194 | // this.species.remove(i); //sad 195 | this.species.splice(i, 1); 196 | 197 | i--; 198 | } 199 | } 200 | } 201 | //------------------------------------------------------------------------------------------------------------------------------------------ 202 | //returns the sum of each this.species average fitness 203 | getAvgFitnessSum() { 204 | var averageSum = 0; 205 | for (var s of this.species) { 206 | averageSum += s.averageFitness; 207 | } 208 | return averageSum; 209 | } 210 | 211 | //------------------------------------------------------------------------------------------------------------------------------------------ 212 | //kill the bottom half of each this.species 213 | cullSpecies() { 214 | for (var s of this.species) { 215 | s.cull(); //kill bottom half 216 | s.fitnessSharing(); //also while we're at it lets do fitness sharing 217 | s.setAverage(); //reset averages because they will have changed 218 | } 219 | } 220 | 221 | 222 | massExtinction() { 223 | for (var i = 5; i < this.species.length; i++) { 224 | // this.species.remove(i); //sad 225 | this.species.splice(i, 1); 226 | 227 | i--; 228 | } 229 | } 230 | //------------------------------------------------------------------------------------------------------------------------------------------ 231 | // BATCH LEARNING 232 | //------------------------------------------------------------------------------------------------------------------------------------------ 233 | //update all the players which are alive 234 | updateAliveInBatches() { 235 | let aliveCount = 0; 236 | for (var i = 0; i < this.players.length; i++) { 237 | if (this.playerInBatch(this.players[i])) { 238 | 239 | if (!this.players[i].dead) { 240 | aliveCount++; 241 | this.players[i].look(); //get inputs for brain 242 | this.players[i].think(); //use outputs from neural network 243 | this.players[i].update(); //move the player according to the outputs from the neural network 244 | if (!showNothing && (!showBest || i == 0)) { 245 | this.players[i].show(); 246 | } 247 | if (this.players[i].score > this.globalBestScore) { 248 | this.globalBestScore = this.players[i].score; 249 | } 250 | } 251 | } 252 | } 253 | 254 | 255 | if (aliveCount == 0) { 256 | this.batchNo++; 257 | } 258 | } 259 | 260 | 261 | playerInBatch(player) { 262 | for (var i = this.batchNo * this.worldsPerBatch; i < min((this.batchNo + 1) * this.worldsPerBatch, worlds.length); i++) { 263 | if (player.world == worlds[i]) { 264 | return true; 265 | } 266 | } 267 | 268 | return false; 269 | 270 | 271 | } 272 | 273 | stepWorldsInBatch() { 274 | for (var i = this.batchNo * this.worldsPerBatch; i < min((this.batchNo + 1) * this.worldsPerBatch, worlds.length); i++) { 275 | worlds[i].Step(1 / 30, 10, 10); 276 | } 277 | } 278 | //------------------------------------------------------------------------------------------------------------------------------------------ 279 | //returns true if all the players in a batch are dead sad 280 | batchDead() { 281 | for (var i = this.batchNo * this.playersPerBatch; i < min((this.batchNo + 1) * this.playersPerBatch, this.players.length); i++) { 282 | if (!this.players[i].dead) { 283 | return false; 284 | } 285 | } 286 | return true; 287 | } 288 | 289 | } 290 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NEAT Template JavaScript 2 | -------------------------------------------------------------------------------- /Species.js: -------------------------------------------------------------------------------- 1 | class Species { 2 | 3 | constructor(p) { 4 | this.players = []; 5 | this.bestFitness = 0; 6 | this.champ; 7 | this.averageFitness = 0; 8 | this.staleness = 0; //how many generations the species has gone without an improvement 9 | this.rep; 10 | 11 | //-------------------------------------------- 12 | //coefficients for testing compatibility 13 | this.excessCoeff = 1; 14 | this.weightDiffCoeff = 0.5; 15 | this.compatibilityThreshold = 3; 16 | if (p) { 17 | this.players.push(p); 18 | //since it is the only one in the species it is by default the best 19 | this.bestFitness = p.fitness; 20 | this.rep = p.brain.clone(); 21 | this.champ = p.cloneForReplay(); 22 | } 23 | } 24 | 25 | //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 26 | //returns whether the parameter genome is in this species 27 | sameSpecies(g) { 28 | var compatibility; 29 | var excessAndDisjoint = this.getExcessDisjoint(g, this.rep); //get the number of excess and disjoint genes between this player and the current species this.rep 30 | var averageWeightDiff = this.averageWeightDiff(g, this.rep); //get the average weight difference between matching genes 31 | 32 | 33 | var largeGenomeNormaliser = g.genes.length - 20; 34 | if (largeGenomeNormaliser < 1) { 35 | largeGenomeNormaliser = 1; 36 | } 37 | 38 | compatibility = (this.excessCoeff * excessAndDisjoint / largeGenomeNormaliser) + (this.weightDiffCoeff * averageWeightDiff); //compatibility formula 39 | return (this.compatibilityThreshold > compatibility); 40 | } 41 | 42 | //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 43 | //add a player to the species 44 | addToSpecies(p) { 45 | this.players.push(p); 46 | } 47 | 48 | //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 49 | //returns the number of excess and disjoint genes between the 2 input genomes 50 | //i.e. returns the number of genes which dont match 51 | getExcessDisjoint(brain1, brain2) { 52 | var matching = 0.0; 53 | for (var i = 0; i < brain1.genes.length; i++) { 54 | for (var j = 0; j < brain2.genes.length; j++) { 55 | if (brain1.genes[i].innovationNo == brain2.genes[j].innovationNo) { 56 | matching++; 57 | break; 58 | } 59 | } 60 | } 61 | return (brain1.genes.length + brain2.genes.length - 2 * (matching)); //return no of excess and disjoint genes 62 | } 63 | //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 64 | //returns the avereage weight difference between matching genes in the input genomes 65 | averageWeightDiff(brain1, brain2) { 66 | if (brain1.genes.length == 0 || brain2.genes.length == 0) { 67 | return 0; 68 | } 69 | 70 | 71 | var matching = 0; 72 | var totalDiff = 0; 73 | for (var i = 0; i < brain1.genes.length; i++) { 74 | for (var j = 0; j < brain2.genes.length; j++) { 75 | if (brain1.genes[i].innovationNo == brain2.genes[j].innovationNo) { 76 | matching++; 77 | totalDiff += abs(brain1.genes[i].weight - brain2.genes[j].weight); 78 | break; 79 | } 80 | } 81 | } 82 | if (matching == 0) { //divide by 0 error 83 | return 100; 84 | } 85 | return totalDiff / matching; 86 | } 87 | //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 88 | //sorts the species by fitness 89 | sortSpecies() { 90 | 91 | var temp = []; // new ArrayList < Player > (); 92 | 93 | //selection short 94 | for (var i = 0; i < this.players.length; i++) { 95 | var max = 0; 96 | var maxIndex = 0; 97 | for (var j = 0; j < this.players.length; j++) { 98 | if (this.players[j].fitness > max) { 99 | max = this.players[j].fitness; 100 | maxIndex = j; 101 | } 102 | } 103 | temp.push(this.players[maxIndex]); 104 | 105 | this.players.splice(maxIndex, 1); 106 | // this.players.remove(maxIndex); 107 | i--; 108 | } 109 | 110 | // this.players = (ArrayList) temp.clone(); 111 | arrayCopy(temp, this.players); 112 | if (this.players.length == 0) { 113 | this.staleness = 200; 114 | return; 115 | } 116 | //if new best player 117 | if (this.players[0].fitness > this.bestFitness) { 118 | this.staleness = 0; 119 | this.bestFitness = this.players[0].fitness; 120 | this.rep = this.players[0].brain.clone(); 121 | this.champ = this.players[0].cloneForReplay(); 122 | } else { //if no new best player 123 | this.staleness++; 124 | } 125 | } 126 | 127 | //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 128 | //simple stuff 129 | setAverage() { 130 | var sum = 0; 131 | for (var i = 0; i < this.players.length; i++) { 132 | sum += this.players[i].fitness; 133 | } 134 | this.averageFitness = sum / this.players.length; 135 | } 136 | //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 137 | 138 | //gets baby from the this.players in this species 139 | giveMeBaby(innovationHistory) { 140 | var baby; 141 | if (random(1) < 0.25) { //25% of the time there is no crossover and the child is simply a clone of a random(ish) player 142 | baby = this.selectPlayer().clone(); 143 | } else { //75% of the time do crossover 144 | 145 | //get 2 random(ish) parents 146 | var parent1 = this.selectPlayer(); 147 | var parent2 = this.selectPlayer(); 148 | 149 | //the crossover function expects the highest fitness parent to be the object and the lowest as the argument 150 | if (parent1.fitness < parent2.fitness) { 151 | baby = parent2.crossover(parent1); 152 | } else { 153 | baby = parent1.crossover(parent2); 154 | } 155 | } 156 | baby.brain.mutate(innovationHistory); //mutate that baby brain 157 | return baby; 158 | } 159 | 160 | //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 161 | //selects a player based on it fitness 162 | selectPlayer() { 163 | var fitnessSum = 0; 164 | for (var i = 0; i < this.players.length; i++) { 165 | fitnessSum += this.players[i].fitness; 166 | } 167 | var rand = random(fitnessSum); 168 | var runningSum = 0; 169 | 170 | for (var i = 0; i < this.players.length; i++) { 171 | runningSum += this.players[i].fitness; 172 | if (runningSum > rand) { 173 | return this.players[i]; 174 | } 175 | } 176 | //unreachable code to make the parser happy 177 | return this.players[0]; 178 | } 179 | //------------------------------------------------------------------------------------------------------------------------------------------ 180 | //kills off bottom half of the species 181 | cull() { 182 | if (this.players.length > 2) { 183 | for (var i = this.players.length / 2; i < this.players.length; i++) { 184 | // this.players.remove(i); 185 | this.players.splice(i, 1); 186 | i--; 187 | } 188 | } 189 | } 190 | //------------------------------------------------------------------------------------------------------------------------------------------ 191 | //in order to protect unique this.players, the fitnesses of each player is divided by the number of this.players in the species that that player belongs to 192 | fitnessSharing() { 193 | for (var i = 0; i < this.players.length; i++) { 194 | this.players[i].fitness /= this.players.length; 195 | } 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 |

Neat template

23 |
24 |
25 |
26 | 27 | 28 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /libraries/p5.dom.js: -------------------------------------------------------------------------------- 1 | /*! p5.dom.js v0.3.2 March 25, 2017 */ 2 | /** 3 | *

The web is much more than just canvas and p5.dom makes it easy to interact 4 | * with other HTML5 objects, including text, hyperlink, image, input, video, 5 | * audio, and webcam.

6 | *

There is a set of creation methods, DOM manipulation methods, and 7 | * an extended p5.Element that supports a range of HTML elements. See the 8 | * 9 | * beyond the canvas tutorial for a full overview of how this addon works. 10 | * 11 | *

Methods and properties shown in black are part of the p5.js core, items in 12 | * blue are part of the p5.dom library. You will need to include an extra file 13 | * in order to access the blue functions. See the 14 | * using a library 15 | * section for information on how to include this library. p5.dom comes with 16 | * p5 complete or you can download the single file 17 | * 18 | * here.

19 | *

See tutorial: beyond the canvas 20 | * for more info on how to use this libary. 21 | * 22 | * @module p5.dom 23 | * @submodule p5.dom 24 | * @for p5.dom 25 | * @main 26 | */ 27 | 28 | (function (root, factory) { 29 | if (typeof define === 'function' && define.amd) 30 | define('p5.dom', ['p5'], function (p5) { (factory(p5));}); 31 | else if (typeof exports === 'object') 32 | factory(require('../p5')); 33 | else 34 | factory(root['p5']); 35 | }(this, function (p5) { 36 | 37 | // ============================================================================= 38 | // p5 additions 39 | // ============================================================================= 40 | 41 | /** 42 | * Searches the page for an element with the given ID, class, or tag name (using the '#' or '.' 43 | * prefixes to specify an ID or class respectively, and none for a tag) and returns it as 44 | * a p5.Element. If a class or tag name is given with more than 1 element, 45 | * only the first element will be returned. 46 | * The DOM node itself can be accessed with .elt. 47 | * Returns null if none found. You can also specify a container to search within. 48 | * 49 | * @method select 50 | * @param {String} name id, class, or tag name of element to search for 51 | * @param {String} [container] id, p5.Element, or HTML element to search within 52 | * @return {Object|p5.Element|Null} p5.Element containing node found 53 | * @example 54 | *

55 | * function setup() { 56 | * createCanvas(100,100); 57 | * //translates canvas 50px down 58 | * select('canvas').position(100, 100); 59 | * } 60 | *
61 | *
62 | * // these are all valid calls to select() 63 | * var a = select('#moo'); 64 | * var b = select('#blah', '#myContainer'); 65 | * var c = select('#foo', b); 66 | * var d = document.getElementById('beep'); 67 | * var e = select('p', d); 68 | *
69 | * 70 | */ 71 | p5.prototype.select = function (e, p) { 72 | var res = null; 73 | var container = getContainer(p); 74 | if (e[0] === '.'){ 75 | e = e.slice(1); 76 | res = container.getElementsByClassName(e); 77 | if (res.length) { 78 | res = res[0]; 79 | } else { 80 | res = null; 81 | } 82 | }else if (e[0] === '#'){ 83 | e = e.slice(1); 84 | res = container.getElementById(e); 85 | }else { 86 | res = container.getElementsByTagName(e); 87 | if (res.length) { 88 | res = res[0]; 89 | } else { 90 | res = null; 91 | } 92 | } 93 | if (res) { 94 | return wrapElement(res); 95 | } else { 96 | return null; 97 | } 98 | }; 99 | 100 | /** 101 | * Searches the page for elements with the given class or tag name (using the '.' prefix 102 | * to specify a class and no prefix for a tag) and returns them as p5.Elements 103 | * in an array. 104 | * The DOM node itself can be accessed with .elt. 105 | * Returns an empty array if none found. 106 | * You can also specify a container to search within. 107 | * 108 | * @method selectAll 109 | * @param {String} name class or tag name of elements to search for 110 | * @param {String} [container] id, p5.Element, or HTML element to search within 111 | * @return {Array} Array of p5.Elements containing nodes found 112 | * @example 113 | *
114 | * function setup() { 115 | * createButton('btn'); 116 | * createButton('2nd btn'); 117 | * createButton('3rd btn'); 118 | * var buttons = selectAll('button'); 119 | * 120 | * for (var i = 0; i < buttons.length; i++){ 121 | * buttons[i].size(100,100); 122 | * } 123 | * } 124 | *
125 | *
126 | * // these are all valid calls to selectAll() 127 | * var a = selectAll('.moo'); 128 | * var b = selectAll('div'); 129 | * var c = selectAll('button', '#myContainer'); 130 | * var d = select('#container'); 131 | * var e = selectAll('p', d); 132 | * var f = document.getElementById('beep'); 133 | * var g = select('.blah', f); 134 | *
135 | * 136 | */ 137 | p5.prototype.selectAll = function (e, p) { 138 | var arr = []; 139 | var res; 140 | var container = getContainer(p); 141 | if (e[0] === '.'){ 142 | e = e.slice(1); 143 | res = container.getElementsByClassName(e); 144 | } else { 145 | res = container.getElementsByTagName(e); 146 | } 147 | if (res) { 148 | for (var j = 0; j < res.length; j++) { 149 | var obj = wrapElement(res[j]); 150 | arr.push(obj); 151 | } 152 | } 153 | return arr; 154 | }; 155 | 156 | /** 157 | * Helper function for select and selectAll 158 | */ 159 | function getContainer(p) { 160 | var container = document; 161 | if (typeof p === 'string' && p[0] === '#'){ 162 | p = p.slice(1); 163 | container = document.getElementById(p) || document; 164 | } else if (p instanceof p5.Element){ 165 | container = p.elt; 166 | } else if (p instanceof HTMLElement){ 167 | container = p; 168 | } 169 | return container; 170 | } 171 | 172 | /** 173 | * Helper function for getElement and getElements. 174 | */ 175 | function wrapElement(elt) { 176 | if(elt.tagName === "INPUT" && elt.type === "checkbox") { 177 | var converted = new p5.Element(elt); 178 | converted.checked = function(){ 179 | if (arguments.length === 0){ 180 | return this.elt.checked; 181 | } else if(arguments[0]) { 182 | this.elt.checked = true; 183 | } else { 184 | this.elt.checked = false; 185 | } 186 | return this; 187 | }; 188 | return converted; 189 | } else if (elt.tagName === "VIDEO" || elt.tagName === "AUDIO") { 190 | return new p5.MediaElement(elt); 191 | } else { 192 | return new p5.Element(elt); 193 | } 194 | } 195 | 196 | /** 197 | * Removes all elements created by p5, except any canvas / graphics 198 | * elements created by createCanvas or createGraphics. 199 | * Event handlers are removed, and element is removed from the DOM. 200 | * @method removeElements 201 | * @example 202 | *
203 | * function setup() { 204 | * createCanvas(100, 100); 205 | * createDiv('this is some text'); 206 | * createP('this is a paragraph'); 207 | * } 208 | * function mousePressed() { 209 | * removeElements(); // this will remove the div and p, not canvas 210 | * } 211 | *
212 | * 213 | */ 214 | p5.prototype.removeElements = function (e) { 215 | for (var i=0; i 243 | * var myDiv; 244 | * function setup() { 245 | * myDiv = createDiv('this is some text'); 246 | * } 247 | * 248 | */ 249 | 250 | /** 251 | * Creates a <p></p> element in the DOM with given inner HTML. Used 252 | * for paragraph length text. 253 | * Appends to the container node if one is specified, otherwise 254 | * appends to body. 255 | * 256 | * @method createP 257 | * @param {String} html inner HTML for element created 258 | * @return {Object|p5.Element} pointer to p5.Element holding created node 259 | * @example 260 | *
261 | * var myP; 262 | * function setup() { 263 | * myP = createP('this is some text'); 264 | * } 265 | *
266 | */ 267 | 268 | /** 269 | * Creates a <span></span> element in the DOM with given inner HTML. 270 | * Appends to the container node if one is specified, otherwise 271 | * appends to body. 272 | * 273 | * @method createSpan 274 | * @param {String} html inner HTML for element created 275 | * @return {Object|p5.Element} pointer to p5.Element holding created node 276 | * @example 277 | *
278 | * var mySpan; 279 | * function setup() { 280 | * mySpan = createSpan('this is some text'); 281 | * } 282 | *
283 | */ 284 | var tags = ['div', 'p', 'span']; 285 | tags.forEach(function(tag) { 286 | var method = 'create' + tag.charAt(0).toUpperCase() + tag.slice(1); 287 | p5.prototype[method] = function(html) { 288 | var elt = document.createElement(tag); 289 | elt.innerHTML = typeof html === undefined ? "" : html; 290 | return addElement(elt, this); 291 | } 292 | }); 293 | 294 | /** 295 | * Creates an <img> element in the DOM with given src and 296 | * alternate text. 297 | * Appends to the container node if one is specified, otherwise 298 | * appends to body. 299 | * 300 | * @method createImg 301 | * @param {String} src src path or url for image 302 | * @param {String} [alt] alternate text to be used if image does not load 303 | * @param {Function} [successCallback] callback to be called once image data is loaded 304 | * @return {Object|p5.Element} pointer to p5.Element holding created node 305 | * @example 306 | *
307 | * var img; 308 | * function setup() { 309 | * img = createImg('http://p5js.org/img/asterisk-01.png'); 310 | * } 311 | *
312 | */ 313 | p5.prototype.createImg = function() { 314 | var elt = document.createElement('img'); 315 | var args = arguments; 316 | var self; 317 | var setAttrs = function(){ 318 | self.width = elt.offsetWidth || elt.width; 319 | self.height = elt.offsetHeight || elt.height; 320 | if (args.length > 1 && typeof args[1] === 'function'){ 321 | self.fn = args[1]; 322 | self.fn(); 323 | }else if (args.length > 1 && typeof args[2] === 'function'){ 324 | self.fn = args[2]; 325 | self.fn(); 326 | } 327 | }; 328 | elt.src = args[0]; 329 | if (args.length > 1 && typeof args[1] === 'string'){ 330 | elt.alt = args[1]; 331 | } 332 | elt.onload = function(){ 333 | setAttrs(); 334 | } 335 | self = addElement(elt, this); 336 | return self; 337 | }; 338 | 339 | /** 340 | * Creates an <a></a> element in the DOM for including a hyperlink. 341 | * Appends to the container node if one is specified, otherwise 342 | * appends to body. 343 | * 344 | * @method createA 345 | * @param {String} href url of page to link to 346 | * @param {String} html inner html of link element to display 347 | * @param {String} [target] target where new link should open, 348 | * could be _blank, _self, _parent, _top. 349 | * @return {Object|p5.Element} pointer to p5.Element holding created node 350 | * @example 351 | *
352 | * var myLink; 353 | * function setup() { 354 | * myLink = createA('http://p5js.org/', 'this is a link'); 355 | * } 356 | *
357 | */ 358 | p5.prototype.createA = function(href, html, target) { 359 | var elt = document.createElement('a'); 360 | elt.href = href; 361 | elt.innerHTML = html; 362 | if (target) elt.target = target; 363 | return addElement(elt, this); 364 | }; 365 | 366 | /** INPUT **/ 367 | 368 | 369 | /** 370 | * Creates a slider <input></input> element in the DOM. 371 | * Use .size() to set the display length of the slider. 372 | * Appends to the container node if one is specified, otherwise 373 | * appends to body. 374 | * 375 | * @method createSlider 376 | * @param {Number} min minimum value of the slider 377 | * @param {Number} max maximum value of the slider 378 | * @param {Number} [value] default value of the slider 379 | * @param {Number} [step] step size for each tick of the slider (if step is set to 0, the slider will move continuously from the minimum to the maximum value) 380 | * @return {Object|p5.Element} pointer to p5.Element holding created node 381 | * @example 382 | *
383 | * var slider; 384 | * function setup() { 385 | * slider = createSlider(0, 255, 100); 386 | * slider.position(10, 10); 387 | * slider.style('width', '80px'); 388 | * } 389 | * 390 | * function draw() { 391 | * var val = slider.value(); 392 | * background(val); 393 | * } 394 | *
395 | * 396 | *
397 | * var slider; 398 | * function setup() { 399 | * colorMode(HSB); 400 | * slider = createSlider(0, 360, 60, 40); 401 | * slider.position(10, 10); 402 | * slider.style('width', '80px'); 403 | * } 404 | * 405 | * function draw() { 406 | * var val = slider.value(); 407 | * background(val, 100, 100, 1); 408 | * } 409 | *
410 | */ 411 | p5.prototype.createSlider = function(min, max, value, step) { 412 | var elt = document.createElement('input'); 413 | elt.type = 'range'; 414 | elt.min = min; 415 | elt.max = max; 416 | if (step === 0) { 417 | elt.step = .000000000000000001; // smallest valid step 418 | } else if (step) { 419 | elt.step = step; 420 | } 421 | if (typeof(value) === "number") elt.value = value; 422 | return addElement(elt, this); 423 | }; 424 | 425 | /** 426 | * Creates a <button></button> element in the DOM. 427 | * Use .size() to set the display size of the button. 428 | * Use .mousePressed() to specify behavior on press. 429 | * Appends to the container node if one is specified, otherwise 430 | * appends to body. 431 | * 432 | * @method createButton 433 | * @param {String} label label displayed on the button 434 | * @param {String} [value] value of the button 435 | * @return {Object|p5.Element} pointer to p5.Element holding created node 436 | * @example 437 | *
438 | * var button; 439 | * function setup() { 440 | * createCanvas(100, 100); 441 | * background(0); 442 | * button = createButton('click me'); 443 | * button.position(19, 19); 444 | * button.mousePressed(changeBG); 445 | * } 446 | * 447 | * function changeBG() { 448 | * var val = random(255); 449 | * background(val); 450 | * } 451 | *
452 | */ 453 | p5.prototype.createButton = function(label, value) { 454 | var elt = document.createElement('button'); 455 | elt.innerHTML = label; 456 | elt.value = value; 457 | if (value) elt.value = value; 458 | return addElement(elt, this); 459 | }; 460 | 461 | /** 462 | * Creates a checkbox <input></input> element in the DOM. 463 | * Calling .checked() on a checkbox returns if it is checked or not 464 | * 465 | * @method createCheckbox 466 | * @param {String} [label] label displayed after checkbox 467 | * @param {boolean} [value] value of the checkbox; checked is true, unchecked is false.Unchecked if no value given 468 | * @return {Object|p5.Element} pointer to p5.Element holding created node 469 | * @example 470 | *
471 | * var checkbox; 472 | * 473 | * function setup() { 474 | * checkbox = createCheckbox('label', false); 475 | * checkbox.changed(myCheckedEvent); 476 | * } 477 | * 478 | * function myCheckedEvent() { 479 | * if (this.checked()) { 480 | * console.log("Checking!"); 481 | * } else { 482 | * console.log("Unchecking!"); 483 | * } 484 | * } 485 | *
486 | */ 487 | p5.prototype.createCheckbox = function() { 488 | var elt = document.createElement('div'); 489 | var checkbox = document.createElement('input'); 490 | checkbox.type = 'checkbox'; 491 | elt.appendChild(checkbox); 492 | //checkbox must be wrapped in p5.Element before label so that label appears after 493 | var self = addElement(elt, this); 494 | self.checked = function(){ 495 | var cb = self.elt.getElementsByTagName('input')[0]; 496 | if (cb) { 497 | if (arguments.length === 0){ 498 | return cb.checked; 499 | }else if(arguments[0]){ 500 | cb.checked = true; 501 | }else{ 502 | cb.checked = false; 503 | } 504 | } 505 | return self; 506 | }; 507 | this.value = function(val){ 508 | self.value = val; 509 | return this; 510 | }; 511 | if (arguments[0]){ 512 | var ran = Math.random().toString(36).slice(2); 513 | var label = document.createElement('label'); 514 | checkbox.setAttribute('id', ran); 515 | label.htmlFor = ran; 516 | self.value(arguments[0]); 517 | label.appendChild(document.createTextNode(arguments[0])); 518 | elt.appendChild(label); 519 | } 520 | if (arguments[1]){ 521 | checkbox.checked = true; 522 | } 523 | return self; 524 | }; 525 | 526 | /** 527 | * Creates a dropdown menu <select></select> element in the DOM. 528 | * @method createSelect 529 | * @param {boolean} [multiple] true if dropdown should support multiple selections 530 | * @return {Object|p5.Element} pointer to p5.Element holding created node 531 | * @example 532 | *
533 | * var sel; 534 | * 535 | * function setup() { 536 | * textAlign(CENTER); 537 | * background(200); 538 | * sel = createSelect(); 539 | * sel.position(10, 10); 540 | * sel.option('pear'); 541 | * sel.option('kiwi'); 542 | * sel.option('grape'); 543 | * sel.changed(mySelectEvent); 544 | * } 545 | * 546 | * function mySelectEvent() { 547 | * var item = sel.value(); 548 | * background(200); 549 | * text("it's a "+item+"!", 50, 50); 550 | * } 551 | *
552 | */ 553 | p5.prototype.createSelect = function(mult) { 554 | var elt = document.createElement('select'); 555 | if (mult){ 556 | elt.setAttribute('multiple', 'true'); 557 | } 558 | var self = addElement(elt, this); 559 | self.option = function(name, value){ 560 | var opt = document.createElement('option'); 561 | opt.innerHTML = name; 562 | if (arguments.length > 1) 563 | opt.value = value; 564 | else 565 | opt.value = name; 566 | elt.appendChild(opt); 567 | }; 568 | self.selected = function(value){ 569 | var arr = []; 570 | if (arguments.length > 0){ 571 | for (var i = 0; i < this.elt.length; i++){ 572 | if (value.toString() === this.elt[i].value){ 573 | this.elt.selectedIndex = i; 574 | } 575 | } 576 | return this; 577 | }else{ 578 | if (mult){ 579 | for (var i = 0; i < this.elt.selectedOptions.length; i++){ 580 | arr.push(this.elt.selectedOptions[i].value); 581 | } 582 | return arr; 583 | }else{ 584 | return this.elt.value; 585 | } 586 | } 587 | }; 588 | return self; 589 | }; 590 | 591 | /** 592 | * Creates a radio button <input></input> element in the DOM. 593 | * The .option() method can be used to set options for the radio after it is 594 | * created. The .value() method will return the currently selected option. 595 | * 596 | * @method createRadio 597 | * @param {String} [divId] the id and name of the created div and input field respectively 598 | * @return {Object|p5.Element} pointer to p5.Element holding created node 599 | * @example 600 | *
601 | * var radio; 602 | * 603 | * function setup() { 604 | * radio = createRadio(); 605 | * radio.option("black"); 606 | * radio.option("white"); 607 | * radio.option("gray"); 608 | * radio.style('width', '60px'); 609 | * textAlign(CENTER); 610 | * fill(255, 0, 0); 611 | * } 612 | * 613 | * function draw() { 614 | * var val = radio.value(); 615 | * background(val); 616 | * text(val, width/2, height/2); 617 | * } 618 | *
619 | *
620 | * var radio; 621 | * 622 | * function setup() { 623 | * radio = createRadio(); 624 | * radio.option('apple', 1); 625 | * radio.option('bread', 2); 626 | * radio.option('juice', 3); 627 | * radio.style('width', '60px'); 628 | * textAlign(CENTER); 629 | * } 630 | * 631 | * function draw() { 632 | * background(200); 633 | * var val = radio.value(); 634 | * if (val) { 635 | * text('item cost is $'+val, width/2, height/2); 636 | * } 637 | * } 638 | *
639 | */ 640 | p5.prototype.createRadio = function() { 641 | var radios = document.querySelectorAll("input[type=radio]"); 642 | var count = 0; 643 | if(radios.length > 1){ 644 | var length = radios.length; 645 | var prev=radios[0].name; 646 | var current = radios[1].name; 647 | count = 1; 648 | for(var i = 1; i < length; i++) { 649 | current = radios[i].name; 650 | if(prev != current){ 651 | count++; 652 | } 653 | prev = current; 654 | } 655 | } 656 | else if (radios.length == 1){ 657 | count = 1; 658 | } 659 | var elt = document.createElement('div'); 660 | var self = addElement(elt, this); 661 | var times = -1; 662 | self.option = function(name, value){ 663 | var opt = document.createElement('input'); 664 | opt.type = 'radio'; 665 | opt.innerHTML = name; 666 | if (arguments.length > 1) 667 | opt.value = value; 668 | else 669 | opt.value = name; 670 | opt.setAttribute('name',"defaultradio"+count); 671 | elt.appendChild(opt); 672 | if (name){ 673 | times++; 674 | var ran = Math.random().toString(36).slice(2); 675 | var label = document.createElement('label'); 676 | opt.setAttribute('id', "defaultradio"+count+"-"+times); 677 | label.htmlFor = "defaultradio"+count+"-"+times; 678 | label.appendChild(document.createTextNode(name)); 679 | elt.appendChild(label); 680 | } 681 | return opt; 682 | }; 683 | self.selected = function(){ 684 | var length = this.elt.childNodes.length; 685 | if(arguments.length == 1) { 686 | for (var i = 0; i < length; i+=2){ 687 | if(this.elt.childNodes[i].value == arguments[0]) 688 | this.elt.childNodes[i].checked = true; 689 | } 690 | return this; 691 | } else { 692 | for (var i = 0; i < length; i+=2){ 693 | if(this.elt.childNodes[i].checked == true) 694 | return this.elt.childNodes[i].value; 695 | } 696 | } 697 | }; 698 | self.value = function(){ 699 | var length = this.elt.childNodes.length; 700 | if(arguments.length == 1) { 701 | for (var i = 0; i < length; i+=2){ 702 | if(this.elt.childNodes[i].value == arguments[0]) 703 | this.elt.childNodes[i].checked = true; 704 | } 705 | return this; 706 | } else { 707 | for (var i = 0; i < length; i+=2){ 708 | if(this.elt.childNodes[i].checked == true) 709 | return this.elt.childNodes[i].value; 710 | } 711 | return ""; 712 | } 713 | }; 714 | return self 715 | }; 716 | 717 | /** 718 | * Creates an <input></input> element in the DOM for text input. 719 | * Use .size() to set the display length of the box. 720 | * Appends to the container node if one is specified, otherwise 721 | * appends to body. 722 | * 723 | * @method createInput 724 | * @param {Number} [value] default value of the input box 725 | * @param {String} [type] type of text, ie text, password etc. Defaults to text 726 | * @return {Object|p5.Element} pointer to p5.Element holding created node 727 | * @example 728 | *
729 | * function setup(){ 730 | * var inp = createInput(''); 731 | * inp.input(myInputEvent); 732 | * } 733 | * 734 | * function myInputEvent(){ 735 | * console.log('you are typing: ', this.value()); 736 | * } 737 | * 738 | *
739 | */ 740 | p5.prototype.createInput = function(value, type) { 741 | var elt = document.createElement('input'); 742 | elt.type = type ? type : 'text'; 743 | if (value) elt.value = value; 744 | return addElement(elt, this); 745 | }; 746 | 747 | /** 748 | * Creates an <input></input> element in the DOM of type 'file'. 749 | * This allows users to select local files for use in a sketch. 750 | * 751 | * @method createFileInput 752 | * @param {Function} [callback] callback function for when a file loaded 753 | * @param {String} [multiple] optional to allow multiple files selected 754 | * @return {Object|p5.Element} pointer to p5.Element holding created DOM element 755 | * @example 756 | * var input; 757 | * var img; 758 | * 759 | * function setup() { 760 | * input = createFileInput(handleFile); 761 | * input.position(0, 0); 762 | * } 763 | * 764 | * function draw() { 765 | * if (img) { 766 | * image(img, 0, 0, width, height); 767 | * } 768 | * } 769 | * 770 | * function handleFile(file) { 771 | * print(file); 772 | * if (file.type === 'image') { 773 | * img = createImg(file.data); 774 | * img.hide(); 775 | * } 776 | * } 777 | */ 778 | p5.prototype.createFileInput = function(callback, multiple) { 779 | 780 | // Is the file stuff supported? 781 | if (window.File && window.FileReader && window.FileList && window.Blob) { 782 | // Yup, we're ok and make an input file selector 783 | var elt = document.createElement('input'); 784 | elt.type = 'file'; 785 | 786 | // If we get a second argument that evaluates to true 787 | // then we are looking for multiple files 788 | if (multiple) { 789 | // Anything gets the job done 790 | elt.multiple = 'multiple'; 791 | } 792 | 793 | // Function to handle when a file is selected 794 | // We're simplifying life and assuming that we always 795 | // want to load every selected file 796 | function handleFileSelect(evt) { 797 | // These are the files 798 | var files = evt.target.files; 799 | // Load each one and trigger a callback 800 | for (var i = 0; i < files.length; i++) { 801 | var f = files[i]; 802 | var reader = new FileReader(); 803 | function makeLoader(theFile) { 804 | // Making a p5.File object 805 | var p5file = new p5.File(theFile); 806 | return function(e) { 807 | p5file.data = e.target.result; 808 | callback(p5file); 809 | }; 810 | }; 811 | reader.onload = makeLoader(f); 812 | 813 | // Text or data? 814 | // This should likely be improved 815 | if (f.type.indexOf('text') > -1) { 816 | reader.readAsText(f); 817 | } else { 818 | reader.readAsDataURL(f); 819 | } 820 | } 821 | } 822 | 823 | // Now let's handle when a file was selected 824 | elt.addEventListener('change', handleFileSelect, false); 825 | return addElement(elt, this); 826 | } else { 827 | console.log('The File APIs are not fully supported in this browser. Cannot create element.'); 828 | } 829 | }; 830 | 831 | 832 | /** VIDEO STUFF **/ 833 | 834 | function createMedia(pInst, type, src, callback) { 835 | var elt = document.createElement(type); 836 | 837 | // allow src to be empty 838 | var src = src || ''; 839 | if (typeof src === 'string') { 840 | src = [src]; 841 | } 842 | for (var i=0; i