Path: blob/master/java/koch-curve/KochCurveTest.java
363 views
import java.applet.Applet;1import java.awt.Graphics;23public class KochCurveTest extends Applet {4private static final double con = Math.sqrt(3.0/4.0);56private void kochCurve(Graphics g, int depth, Segment s) {7/*8* B9* /\10* ____/ \____11* A C12*/13if (depth == 0)14return;15// draw dots instead of lines16g.drawLine((int)s.x1, (int)s.y1, (int)s.x1, (int)s.y1);17g.drawLine((int)s.x2, (int)s.y2, (int)s.x2, (int)s.y2);18double xA = (s.x1*2 + s.x2)/3;19double yA = (s.y1*2 + s.y2)/3;20double xC = (s.x1 + s.x2*2)/3;21double yC = (s.y1 + s.y2*2)/3;22double xB = (s.x1+s.x2)/2 + con/3*(s.y2-s.y1);23double yB = (s.y1+s.y2)/2 + con/3*(s.x1-s.x2);24kochCurve(g, depth-1, new Segment(s.x1, s.y1, xA, yA));25kochCurve(g, depth-1, new Segment(xA, yA, xB, yB));26kochCurve(g, depth-1, new Segment(xB, yB, xC, yC));27kochCurve(g, depth-1, new Segment(xC, yC, s.x2, s.y2));28}2930private void kochSnow(Graphics g, int depth, Segment s) {31double x3 = (s.x1+s.x2)/2 - con*(s.y2-s.y1);32double y3 = (s.y1+s.y2)/2 - con*(s.x1-s.x2);33kochCurve(g, depth, s);34kochCurve(g, depth, new Segment(s.x2, s.y2, x3, y3));35kochCurve(g, depth, new Segment(x3, y3, s.x1, s.y1));36}3738public void paint(Graphics g) {39kochSnow(g, 8, new Segment(100, 200, 600, 200));40}41}4243class Segment {44public double x1, y1, x2, y2;45public Segment(double x1, double y1, double x2, double y2) {46this.x1 = x1;47this.y1 = y1;48this.x2 = x2;49this.y2 = y2;50}51}525354