-
Notifications
You must be signed in to change notification settings - Fork 0
/
DNA.js
49 lines (41 loc) · 967 Bytes
/
DNA.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class DNA {
constructor({ genes = [] } = {}) {
while (genes.length < DNA.lifespan) {
const newForce = p5.Vector.random2D()
newForce.setMag(DNA.maxForce)
genes.push(newForce)
}
this.genes = genes
}
static get mutationRate() {
return DNA._mutationRate
}
static set mutationRate(newRate) {
DNA._mutationRate = newRate
}
crossover(otherGenes) {
const newGenes = []
const mid = floor(random(this.genes.length))
for (let i = 0; i < DNA.lifespan; i++) {
if (i < mid) {
newGenes.push(this.genes[i])
} else {
newGenes.push(otherGenes[i])
}
}
return new DNA({
genes: newGenes
})
}
mutate() {
for (let i = 0; i < DNA.lifespan; i++) {
if (random() < DNA.mutationRate) {
this.genes[i] = p5.Vector.random2D()
this.genes[i].setMag(DNA.maxForce)
}
}
}
}
DNA.lifespan = 400
DNA.maxForce = 0.3
DNA._mutationRate = 0.02