Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
zmx0142857
GitHub Repository: zmx0142857/mini-games
Path: blob/master/java/koch-curve/KochCurveTest.java
363 views
1
import java.applet.Applet;
2
import java.awt.Graphics;
3
4
public class KochCurveTest extends Applet {
5
private static final double con = Math.sqrt(3.0/4.0);
6
7
private void kochCurve(Graphics g, int depth, Segment s) {
8
/*
9
* B
10
* /\
11
* ____/ \____
12
* A C
13
*/
14
if (depth == 0)
15
return;
16
// draw dots instead of lines
17
g.drawLine((int)s.x1, (int)s.y1, (int)s.x1, (int)s.y1);
18
g.drawLine((int)s.x2, (int)s.y2, (int)s.x2, (int)s.y2);
19
double xA = (s.x1*2 + s.x2)/3;
20
double yA = (s.y1*2 + s.y2)/3;
21
double xC = (s.x1 + s.x2*2)/3;
22
double yC = (s.y1 + s.y2*2)/3;
23
double xB = (s.x1+s.x2)/2 + con/3*(s.y2-s.y1);
24
double yB = (s.y1+s.y2)/2 + con/3*(s.x1-s.x2);
25
kochCurve(g, depth-1, new Segment(s.x1, s.y1, xA, yA));
26
kochCurve(g, depth-1, new Segment(xA, yA, xB, yB));
27
kochCurve(g, depth-1, new Segment(xB, yB, xC, yC));
28
kochCurve(g, depth-1, new Segment(xC, yC, s.x2, s.y2));
29
}
30
31
private void kochSnow(Graphics g, int depth, Segment s) {
32
double x3 = (s.x1+s.x2)/2 - con*(s.y2-s.y1);
33
double y3 = (s.y1+s.y2)/2 - con*(s.x1-s.x2);
34
kochCurve(g, depth, s);
35
kochCurve(g, depth, new Segment(s.x2, s.y2, x3, y3));
36
kochCurve(g, depth, new Segment(x3, y3, s.x1, s.y1));
37
}
38
39
public void paint(Graphics g) {
40
kochSnow(g, 8, new Segment(100, 200, 600, 200));
41
}
42
}
43
44
class Segment {
45
public double x1, y1, x2, y2;
46
public Segment(double x1, double y1, double x2, double y2) {
47
this.x1 = x1;
48
this.y1 = y1;
49
this.x2 = x2;
50
this.y2 = y2;
51
}
52
}
53
54