graphics - Trouble drawing star with an even number of points with turtle in Java -
alright, assignment, , have close figured out. basically, given code create turtle , test client draws polygon n sides. instructions modify test client draws star n points. odd-numbered values of n easy because made change turtle.turnleft(angle) turtle.turnleft(angle*2).
i think of trouble coming complete ignorance of star geometry. tried draw out , kind of make triangles between points, , i've tested few different things, keep getting lines resemble this: vvvv , turn left.
original code:
public class turtle { private double x, y; private double angle; public turtle(double x0, double y0, double a0) { x=x0; y=y0; angle=a0;} public void turnleft(double delta) {angle += delta;} public void goforward(double step) { double oldx=x, oldy=y; x+=step*math.cos(math.toradians(angle)); y+=step*math.sin(math.toradians(angle)); stddraw.line(oldx, oldy, x, y); } public static void main(string[] args) { int n=integer.parseint(args[0]); double angle = 360.0/n; double step = math.sin(math.toradians(angle/2)); turtle turtle= new turtle(0.5, 0.0, angle/2); (int i=0;i<n;i++) { turtle.goforward(step); turtle.turnleft(angle); }}}
edited again:
revised code (again):
public static void main(string[] args) { int n=integer.parseint(args[0]); double angle = 360.0/n; double q = ((n-2)*180)/n; double p = ((180-q)/2); double t = (180-q); double v = (180 - 2*t); double step = math.sin(math.toradians(angle/2)); turtle turtle= new turtle(0.5, 0.0, (angle/2 + p)); (int i=0;i<n;i++) { turtle.goforward(step/2); turtle.turnleft(-t); turtle.goforward(step/2); turtle.turnleft(180-v); }}}
this 1 gives perfect star values of n except 7 reason.
double q = ((n-2)*180.)/n;
this ensure whole expression computed using doubles , avoid truncation of decimal part... (not problem n=3, 4, 5, 6, 8, 9, 10, 12, 15, 18, 20...).
Comments
Post a Comment