通過這樣的課程,您可以先進行計算並在第三步中繪製整個事物。
這段代碼完全沒有用處。會出現一些錯誤,但你可能會想到如何做到這一點...
public class MyLine {
private Random random;
public MyLine(int Level, PointF Start, PointF End, int Angle) {
this.random = new Random();
this.Level = Level;
this.Start = Start;
this.End = End;
this.Angle = Angle;
}
public int Level{get;set;}
public PointF Start { get; set; }
public PointF End { get; set; }
public float MyLength {
get {
return (float)Math.Sqrt(Math.Pow(End.X - Start.X, 2) + Math.Pow(End.Y - Start.Y, 2));
}
}
public int Angle { get; set; }
public MyLine MySideLine { get; set; }
public void CalculateSideLine() {
float middleX = Start.X + (End.X - Start.X)/2f;
float k = (End.Y - Start.Y)/(End.X - Start.X);
float d = (End.X * Start.Y - Start.X * End.Y)/(End.X - Start.X);
float middleY = k * middleX + d;
PointF newStart = new PointF(middleX, middleY);
int angle = random.Next(10, 80);
if (random.Next(0, 1) == 0)
angle = angle + 90;
float LengthPercentage = (float)random.NextDouble();
if (LengthPercentage < 0.5)
LengthPercentage = 0.5f;
float newLength = MyLength * LengthPercentage;
//Now we know the starting point of the new line, its angle and the length
//I do not have enough time to write the complete calculation down but it's result would be a new endPoint
//You think of a circle with its middle on "newStart" and its radius = "newLength".
//This circle you'll have to intersect with the line through "newStart" with the given angle.
//There are two results, you have to choose the one in the right direction
PointF newEnd = new PointF(0, 0); //This you'll have to find yourself...
this.MySideLine = new MyLine(this.Level++, newStart, newEnd, angle);
//this will calculate a new nested side line and - kind of recursively - go deeper and deeper.
//you'll have to find a break condition on a certain level.
this.MySideLine.CalculateSideLine();
//Be aware of randomly angle of 90 or 0. you might want to calculate two side lines on each twig (otherwise it will not look like a tree)
}
//This will draw the line to a Graphics (e.g. look at Form.CreateGraphics())
//it will kind of recursively draw down the full tree.
public void DrawMeAndMySideLine(Graphics g){
g.DrawLine(Pens.Black,this.Start,this.End);
this.MySideLine.DrawMeAndMySideLine(g);
}
}
我看不到有關隨機角度的任何事情。你需要計算它還是在給定的時間間隔內是「任何」角度?此外,你可能會發佈一個** short **樣本,你現在已經有了這個算法。有時候,它可以幫助你理解這個問題。第2行會在原始行的同一點開始嗎? –
這似乎更像是一個幾何問題,而不是一個編程問題。這是不完全清楚你想要做什麼。 –
@MattBurland - 這個問題似乎與確定子分支的算法有關,我認爲這種混淆正是因爲OP對如何生成這樣的算法感到困惑。他似乎在思考如何使用面向對象的思想來解決這個問題。但我認爲你是對的,這有一個沉重的幾何構件。可能是幾何組件將他從OO扔掉,並讓他只考慮程序。 – AgapwIesu