プログラマの数学の第6章では再帰について丁寧に説明されています。その中で、タートルグラフィックスについての説明があるのですが、面白かったので実際に作成してみました。自分で作成すると理解も深まりますね。
import java.applet.*; import java.awt.*; import java.awt.image.*; /* <applet code="TurtleGraphicsApplet.class" width="800" height="600"> </applet> */ public class TurtleGraphicsApplet extends Applet { Dimension size; double x0,y0,x1,y1; double direction; public void init(){ size = getSize(); x0 = (double)size.width / 2.0; y0 = (double)9.0 * size.height / 10.0; } public void paint(Graphics g){ direction = 0.0; g.setColor(Color.blue); drawTree(12,g); } void drawTree(int n,Graphics g){ if (n == 0) return; else { left(); forward(n,g); drawTree(n-1,g); back(n); right(); right(); forward(n,g); drawTree(n-1,g); back(n); left(); } } void left(){ direction -= 15.0; } void right(){ direction += 15.0; } void forward(int n,Graphics g){ x1 = x0 + (double)n * 6.0 * Math.sin(Math.PI*direction/180.0); y1 = y0 - (double)n * 6.0 * Math.cos(Math.PI*direction/180.0); g.drawLine((int)x0,(int)y0,(int)x1,(int)y1); x0 = x1; y0 = y1; } void back(int n){ x0 = x1 - (double)n * 6.0 * Math.sin(Math.PI*direction/180.0); y0 = y1 + (double)n * 6.0 * Math.cos(Math.PI*direction/180.0); x1 = x0; y1 = y0; } }
実行
$ javac TurtleGraphicsApplet.java $ appletviewer TurtleGraphicsApplet.java