import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class hikagetutuji extends Applet {
  	Dimension d;
  	Panel p;

  	TextField aTextField;
  	Button button;

    int times = 8;
    Choice timesChoice;
    double xOrig1 = 100.0;
    double yOrig1 = 100.0;
    double length;
	double a = 40;

    public void init() {
	timesChoice = new Choice();
	for (int i = 1; i <= 10; i++) {
	    timesChoice.addItem("" + i);
	}
	String ar = getParameter ("angle");
	if (ar == null){
	 	a = 40;
	}else{
		a = Double.valueOf(ar).doubleValue();
	}
	p = new Panel();
	p.add(timesChoice);
	p.add(new Label("角度"));
	p.add(aTextField = new TextField("40"));
	p.add(button = new Button("変更"));

	timesChoice.select(times - 1);
	timesChoice.addItemListener(new ItemAdp());	// ItemListenerの設定

	p.setBackground(Color.pink);
	setLayout(new BorderLayout());
	add("North",p);

	button.addActionListener ( new java.awt.event.ActionListener ()
	  {
		public void actionPerformed (ActionEvent e)
		{
		  a = (Double.valueOf(aTextField.getText()).doubleValue());
		  repaint();
		}
	   });

    }

    class ItemAdp implements ItemListener {
	public void itemStateChanged(ItemEvent e) {
	    if (e.getSource() == timesChoice) {
		times = timesChoice.getSelectedIndex() + 1;
		repaint();
	    }
	}
    }

    public void paint(Graphics g) {

	double angle = 0.0;				// 角度の初期値
	xOrig1 = 100.0;					// x1座標の初期値
	yOrig1 = 100.0;					// y1座標の初期値

	int width = 100;			// 横幅
	int height = 40;			// 縦幅
	int pointN = (int) Math.pow(3, times);		// 分割数
	length = (double) (width - 10) / pointN;	// 1辺の長さ
	g.setColor(Color.red);
	drawKoch(g, times, angle);
	drawKoch(g, times, angle-120);
	drawKoch(g, times, angle+120);
    }

    //図形の描画
    public void drawKoch(Graphics g, int n, double angle) {

	double x, y, angleR;

	if (n <= 0) {					// もう分割されない状態
	    angleR = Math.PI / 180 * angle;		// 回転角度のラジアン変換
	    x = length * Math.cos(angleR) + xOrig1;	// 次のx座標値
	    y = length * Math.sin(angleR) + yOrig1;	// 次のy座標値
	    g.drawLine((int) xOrig1, (int) (200 - yOrig1), (int) x, (int) (200 - y));
							// 直線の描画
	    xOrig1 = x;					// 次の点を基点に
	    yOrig1 = y;					// 次の点を基点に
	    return;
	}
	drawKoch(g, n - 1, angle);
	drawKoch(g, n - 1, angle + a);
	drawKoch(g, n - 1, angle - a);
	drawKoch(g, n - 1, angle);
    }

}
