java平面山脉模型
CGH150 人气:0核心方法:递归
其实当我第一次看到这个题目时,心中想的不就是个普通的递归吗,直接取两个点,然后不断取横坐标中点,然后中点纵坐标取随机数不就行吗,代码如下
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); }
大功告成
加载全部内容