-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDragonCurve.java
More file actions
43 lines (38 loc) · 1.21 KB
/
DragonCurve.java
File metadata and controls
43 lines (38 loc) · 1.21 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
/**
* Dragon Curve implementation.
*/
public class DragonCurve {
private static final int ORDER = 14;
private static final double STEP = 0.002;
public static void main(String[] args) {
StdDraw.setCanvasSize(900, 900);
StdDraw.setXscale(0, 1);
StdDraw.setYscale(0, 1);
// Build string using L-system
String seq = "F";
for (int i = 0; i < ORDER; i++) {
StringBuilder next = new StringBuilder();
for (char c : seq.toCharArray()) {
if (c == 'F') next.append("F+G");
else if (c == 'G') next.append("F-G");
else next.append(c);
}
seq = next.toString();
}
double x = 0.5, y = 0.5;
double angle = 0;
for (char c : seq.toCharArray()) {
if (c == 'F' || c == 'G') {
double x2 = x + STEP * Math.cos(angle);
double y2 = y + STEP * Math.sin(angle);
StdDraw.line(x, y, x2, y2);
x = x2;
y = y2;
} else if (c == '+') {
angle += Math.PI / 2;
} else if (c == '-') {
angle -= Math.PI / 2;
}
}
}
}