Add classes for drawing snowflakes

This commit is contained in:
Manuel Thalmann 2022-10-11 22:27:54 +02:00
parent 3c1486854b
commit 67d698f537
3 changed files with 119 additions and 0 deletions

View file

@ -0,0 +1,39 @@
package ch.nuth.zhaw.exbox;
/**
* Provides the functionality to draw a snowflake.
*/
public class SnowflakeServer implements CommandExecutor {
@Override
public String execute(String command) {
int recursionLevel = Integer.parseInt(command);
Turtle turtle = Turtle.instance();
drawSnowflake(turtle, recursionLevel);
return turtle.getTrace();
}
public void drawSnowflake(Turtle turtle, int recursionLevel) {
turtle.reset(0.1, 0.266);
turtle.turn(60);
for (int i = 0; i < 3; i++) {
drawLine(turtle, recursionLevel, 0.8);
turtle.turn(-120);
}
}
public void drawLine(Turtle turtle, int recursionLevel, double destination) {
if (recursionLevel == 0) {
turtle.move(destination);
} else {
double distance = destination / 3;
for (int i = 0; i < 3; i++) {
drawLine(turtle, recursionLevel - 1, distance);
turtle.turn(i % 2 == 0 ? 60 : -120);
}
drawLine(turtle, recursionLevel - 1, distance);
}
}
}

View file

@ -0,0 +1,17 @@
package ch.nuth.zhaw.exbox;
public class TestGraphicServer implements CommandExecutor {
String figure = "<line x1=\"0.1\" y1 = \"0.8\" x2=\"0.9\" y2 = \"0.8\" />\n" +
"<line x1=\"0.2\" y1 = \"0.4\" x2=\"0.2\" y2 = \"0.8\" />\n" +
"<line x1=\"0.3\" y1 = \"0.4\" x2=\"0.3\" y2 = \"0.8\" />\n" +
"<line x1=\"0.3\" y1 = \"0.4\" x2=\"0.7\" y2 = \"0.4\" />\n" +
"<line x1=\"0.3\" y1 = \"0.6\" x2=\"0.4\" y2 = \"0.6\" />\n" +
"<line x1=\"0.5\" y1 = \"0.8\" x2=\"0.5\" y2 = \"0.6\" />\n" +
"<line x1=\"0.5\" y1 = \"0.6\" x2=\"0.7\" y2 = \"0.6\" />\n" +
"<line x1=\"0.7\" y1 = \"0.6\" x2=\"0.7\" y2 = \"0.4\" />\n" +
"<line x1=\"0.8\" y1 = \"0.4\" x2=\"0.8\" y2 = \"0.8\" />\n";
public String execute(String command) {
return figure;
}
}

View file

@ -0,0 +1,63 @@
package ch.nuth.zhaw.exbox;
public class Turtle {
private static StringBuffer b;
private static double x, y;
private static double angle;
private static Turtle theTurtle;
public static Turtle instance() {
if (theTurtle == null) {
theTurtle = new Turtle();
}
return theTurtle;
}
public Turtle() {
this(0, 0);
}
public Turtle(double x, double y) {
reset(x, y);
theTurtle = this;
}
public void reset(double x, double y) {
b = new StringBuffer();
Turtle.x = x;
Turtle.y = y;
angle = 0;
}
public void clear() {
reset(0, 0);
}
public String getTrace() {
return b.toString();
}
private double round(double d) {
return Math.round(d * 10000) / 10000.0;
}
public void move(double dist) {
b.append("<line x1=\"");
b.append(Double.toString(round(x)));
b.append("\" y1=\"");
b.append(Double.toString(round(y)));
b.append("\" ");
x += Math.cos(angle) * dist;
y += Math.sin(angle) * dist;
b.append("x2=\"");
b.append(Double.toString(round(x)));
b.append("\" y2=\"");
b.append(Double.toString(round(y)));
b.append("\"/>\n");
}
public void turn(double turnAngle) {
angle += turnAngle * Math.PI / 180;
}
}