-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGene.ts
More file actions
90 lines (73 loc) · 1.72 KB
/
Gene.ts
File metadata and controls
90 lines (73 loc) · 1.72 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import {MUTATION_RATE, MUTATION_AMOUNT} from './constants.js'
class Gene {
private readonly rgba: number[];
// list of x, y values
// ex: [x1, y1, x2, y2, x3, y3]
private readonly points: number[];
constructor(
rgba: number[],
points: number[]
) {
this.rgba = rgba
this.points = points
}
static randomGene(numOfPoints: number): Gene {
let points: number[] = []
for (let i = 0; i < numOfPoints; i++) {
points.push(
Math.random() + Math.random() - 0.5,
Math.random() + Math.random() - 0.5
)
}
return new Gene(
[
Math.random(),
Math.random(),
Math.random(),
Math.max(Math.random() * Math.random(), 0.2)
],
points
)
}
mutate(numOfPoints: number): Gene {
let newRGBA = [...this.rgba]
let newPoints = [...this.points]
for (let i = 0; i < 4; i++) {
if (Math.random() < MUTATION_RATE) {
newRGBA[i] += Math.random() * MUTATION_AMOUNT * 2 - MUTATION_AMOUNT
newRGBA[i] = Gene.boundCheck(newRGBA[i])
}
}
for (let i = 0; i < numOfPoints * 2; i++){
if (Math.random() < MUTATION_RATE) {
newPoints[i] += Math.random() * MUTATION_AMOUNT * 2 - MUTATION_AMOUNT
newPoints[i] = Gene.boundCheck(newPoints[i])
}
}
return new Gene(
newRGBA,
newPoints
)
}
private static boundCheck(val: number): number {
if (val < 0)
val = 0;
if (val > 1)
val = 1;
return val
}
public getPoints() {
return this.points
}
public getColor() {
return this.rgba
}
}
export default class GeneTriangle extends Gene {
constructor(
rgba: number[],
points: number[]
) {
super(rgba, points)
}
}