这篇文章算是翻译吧,因为是参考的另一位博主的Python风格的代码,我将其改写成了C++风格。为了尊重原创性,这里贴一下文章链接: LS文法构图算法(3) Hilbert-Peano曲线。
首先附一下效果图
运行环境是VS2017,迭代五次的结果。
文法是这样的:
定义X为顺时针绘制子图,Y为逆时针绘制子图。
start=“X”(也可以是Y,只是绘制的方向不同)
replacementX = "+YF-XFX-FY+";
replacementY = "-XF+YFY+FX-";
replacementY = "-XF+YFY+FX-";
实际上解析的时候只是遇到“F”才画线,遇到X和Y并没有画线,这是我认为比较绕的地方,也花了一点时间才弄清楚。
这里只贴一下核心代码:
这部分是文法解析器,解释文法画出图形。
void Curve::DrawGrammer()
{
endX = 0, endY = 0;
direction = 0;
for (int i = 0; i < this->statement.length(); i++)
{
if (this->statement[i] == 'F')
{
float startX = this->endX;
float startY = this->endY;
this->endX = startX + this->step*(cos(this->direction));
this->endY = startY + this->step*(sin(this->direction));
cout << endX << ',' << endY << endl;
Draw_Line(startX, startY, this->endX, this->endY);
}
else if (this->statement[i] == '-')
{
this->direction = this->direction - this->angle;
}
else if (this->statement[i] == '+')
{
this->direction = this->direction + this->angle;
}
}
}
这一部分是根据迭代次数计算文法。
void Curve::CalGrammer()
{
for (int i = 0; i < this->level; i++)
{
string newStatement = "";
for (int j = 0; j < this->statement.length(); j++)
{
if (this->statement[j] == 'X')
{
newStatement = newStatement + this->replacementX;
}
else if (this->statement[j] == 'Y')
{
newStatement = newStatement + this->replacementY;
}
else
{
newStatement = newStatement + this->statement[j];
}
}
this->statement = newStatement;
cout << statement << endl;
}
}
人生的第一篇博客,以后还要继续努力,发一些自己原创的东西。