?? treepanel.java
字號:
/**
* 用LS 文法生成的樹
* 支持單一規則
*/
import java.awt.Point;
import java.util.Stack;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
public class TreePanel extends FractalPanel {
//樹的很多形態
/**
* F[-F]F[+F]F 25 向上
* FF+[+F-F-F]-[-F+F+F] 20 蓬松
* F[+F]F[-F+F] 25度 刺
*/
private int alpha;
private String rule;
private int time;
private String picString;
private int currentAngle = 90; // 當前繪圖方向
private Stack (State) s = new Stack (State) ();
private Point currentPoint = new Point(300,500); // 當前畫筆在的點
private int length;
// 字符串參數帶F
public TreePanel(String rule, int alpha, int time, int length) {
this.rule = rule;
this.alpha = alpha;
this.time = time;
this.length = length;
this.picString = rule;
initPic();
}
private void initPic() {
for (int i = 0; i < time; i++) {
LS();
}
}
// 根據規則生成字符串
private void LS() {
picString = picString.replaceAll("F", rule);
}
public void draw() {
//初始化
currentAngle = 90;
s = new Stack {State}();
currentPoint = new Point(300, 650);
// 對picString進行分析,根據字符串指示信息畫圖
int length = picString.length();
for (int offset = 0; offset < length; offset++) {
switch (picString.charAt(offset)) {
case 'F':
forwardLine();
break;
case 'f':
forwardWithOutLine();
break;
case '+':
antiRotate(alpha);
break;
case '-':
rotate(alpha);
break;
case '[':
saveState();
break;
case ']':
loadState();
break;
}
}
}
/***************************************************************************
* 畫圖輔助函數 坐標系說明: (0,0)為左上角的點,angle是以水平向右為0度
**************************************************************************/
/**
* 根據遞歸層數向前畫線
*/
private void forwardLine() {
Graphics g = getGraphics();
int x = currentPoint.x;
int y = currentPoint.y;
int endX = (int)(x + length*Math.cos(currentAngle/180.0 * Math.PI));
int endY = (int)(y - length*Math.sin(currentAngle/180.0 * Math.PI));
g.drawLine(x,y,endX,endY);
currentPoint.setLocation(endX,endY);
}
/**
* 根據遞歸層樹前進不畫線
*/
private void forwardWithOutLine() {
int endX = (int)(currentPoint.x + length*Math.cos(currentAngle/180.0 * Math.PI));
int endY = (int)(currentPoint.y - length*Math.sin(currentAngle/180.0 * Math.PI));
currentPoint.setLocation(endX,endY);
}
/**
* 順時針旋轉
*
* @param rotateAngle
* 旋轉角度
*/
private void rotate(int rotateAngle) {
currentAngle -= rotateAngle;
}
/**
* 逆時針旋轉
*
* @param rotateAngle
* 旋轉角度
*/
private void antiRotate(int rotateAngle) {
currentAngle += rotateAngle;
}
private void saveState() {
// State state = new State(currentPoint, currentAngle);
Point p = new Point();
p.setLocation(currentPoint.x,currentPoint.y);
State state = new State(p,currentAngle);
s.push(state);
}
private void loadState() {
State state = s.pop();
currentPoint = state.position;
currentAngle = state.angle;
}
/**
* javaBean 存放當前畫筆信息
*/
private class State {
int angle;
Point position;
State(Point currentPoint, int angle) {
position = currentPoint;
this.angle = angle;
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -