核心方法:递归
绘制平面山脉模型核心就是,画布上取两点,然后不断循环取横坐标中点,中点纵坐标取随机数,代码如下
public void recur(Graphics g, double x1, double x2, double y1, double y2, int range) {
double x3 = (x1 + x2) / 2;
double y3 = (y1 + y2) / 2;
if (x2-x1<= 15) {
g.drawLine((int) x1, (int) y1, (int) x3, (int) y3);
g.drawLine((int) x2, (int) y2, (int) x3, (int) y3);
return;
}
Random rand=new Random();
int num=rand.nextInt(range);
recur(g, x1, x3, y1, y3-num, range);
recur(g, x3, x2, y3-num, y2, range);
}
但是结果差强人意
很明显这并不像平面山脉,解决方案就在于我们需要每次递归时将纵坐标随机数值减小,,从而形成一种连绵起伏的效果,改进后代码如下
public void recur(Graphics g, double x1, double x2, double y1, double y2, int range) {
//range我用的是300,大家可以自己调节
double x3 = (x1 + x2) / 2;
double y3 = (y1 + y2) / 2;
if (x2-x1<= 1|range==0) {
g.drawLine((int) x1, (int) y1, (int) x3, (int) y3);
g.drawLine((int) x2, (int) y2, (int) x3, (int) y3);
return;
}
Random rand=new Random();
int num=rand.nextInt(range*2)-range;
range*=0.5;
recur(g, x1, x3, y1, y3+num, range);
recur(g, x3, x2, y3+num, y2, range);
}
效果还是很接近真实山脉的
之后我们可以对山脉进行颜色填充美化,基于 Polygon 类,传入不同的透明度进行不同山脉的区别,代码如下
public void recur(Graphics g, double x1, double x2, double y1, double y2, int range,int alp) {
//实例range用的是300
//四座山脉透明度分别为220,180,120,40
double x3 = (x1 + x2) / 2;
double y3 = (y1 + y2) / 2;
if (x2-x1<= 1|range==0) {
g.drawLine((int) x1, (int) y1, (int) x3, (int) y3);
g.drawLine((int) x2, (int) y2, (int) x3, (int) y3);
Polygon p=new Polygon();
p.addPoint((int)x3, (int)y3);
p.addPoint((int)x1, (int)y1);
p.addPoint((int)x1, 800);
p.addPoint((int)x2, 800);
p.addPoint((int)x2, (int)y2);
g.setColor(new Color(0,0,0,alp));
g.fillPolygon(p);
return;
}
Random rand=new Random();
int num=rand.nextInt(range*2)-range;
range*=0.5;
//上面的0.5也可以改变,他控制的是循环次数和山脉的陡峭度,大家可以改变尝试
recur(g, x1, x3, y1, y3+num, range,alp);
recur(g, x3, x2, y3+num, y2, range,alp);
}
大功告成,感谢观众老爷们阅读 ≧◇≦,如有错误,敬请指正