Koch科赫雪花的實現
阿新 • • 發佈:2019-01-07
科赫曲線是一條線。雪花就是從三條線開始
package 科赫雪花; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class kehe_snow extends JFrame{ final static JSlider js = new JSlider(1,10,5); private int width=600; private int count; double x1,y1,x2,y2,x3,y3; double PI=Math.PI; private Graphics g; public void showUI(int count){ this.setSize(new Dimension(width,width)); this.setTitle("科赫雪花"); this.setVisible(true); this.setDefaultCloseOperation(3); this.setResizable(false); g=this.getGraphics(); FlowLayout fl = new FlowLayout(); this.setLayout(fl); count=js.getValue(); this.add(js); js.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { // TODO Auto-generated method stub update(); } }); this.addMouseListener(new MouseAdapter() { //只需要重寫需要的方法即可,因為父類不是介面: //滑鼠按下時的點的座標 public void mouseReleased(MouseEvent e) { draw(e); } }); } public void update(){ repaint(); } public static void main(String[]args){ kehe_snow ks = new kehe_snow(); ks.showUI(js.getValue()); } //雪花就是三個科赫曲線,引用三次遞迴即可 public void draw(MouseEvent e){ x1=width/4; y1=width/4; x2=width*3/4; y2=width/4; x3=width/2; y3=(1+Math.sqrt(3))*width/4; draw_digui(g,x2,y2,x1,y1,js.getValue()); draw_digui(g,x3,y3,x2,y2,js.getValue()); draw_digui(g,x1,y1,x3,y3,js.getValue()); } public void draw_digui(Graphics g,double x1,double y1,double x2,double y2,int count){ double x3,y3,//第一個三等分點 x5,y5,//第二個三等分點 x4,y4,//頂點 l,theta;//正三角形底邊長和角度 if(count<=1){ g.drawLine((int)x1,width-(int)y1,(int)x2,width-(int)y2);//由於轉換了座標系,所以相應的要轉換會原來以右上角為座標原點的座標系,只需要變化Y的值即可 }else{ //第一個三等分點 x3 = x1+(x2-x1)/3; y3 = y1+(y2-y1)/3; //第二個三等分點 x5= x2-(x2-x1)/3; y5= y2-(y2-y1)/3; //求三角形邊長和三角形底邊的傾斜角 l=Math.sqrt((y5-y3)*(y5-y3)+(x5-x3)*(x5-x3)); theta=Math.atan((y5-y3)/(x5-x3)); //對角的條件的限制 if((theta>=0) && ((x5-x3)<0)||(theta<=0)&&((x5-x3)<0)){ theta=theta+PI; } //頂點 x4=x3+Math.cos(theta+PI/3)*l; y4=y3+Math.sin(theta+PI/3)*l; count--; draw_digui(g,x1,y1,x3,y3,count); draw_digui(g,x3,y3,x4,y4,count); draw_digui(g,x4,y4,x5,y5,count); draw_digui(g,x5,y5,x2,y2,count); } } }