gpt4 book ai didi

java - 绘制递归雪花

转载 作者:行者123 更新时间:2023-12-01 11:47:21 25 4
gpt4 key购买 nike

我遇到这个问题,我必须绘制一个递归雪花,使得雪花有 6 条来自中心点的线,每条线彼此相距 60 度,然后每条线的端点就是中心点另一片。每次它 fork 成另一片时,长度就会减半。长度定义为薄片的一侧。这种递归不断发生,直到长度减小到 20 像素之类的距离,此时您将无法再区分不同的薄片。

我知道递归只是一种调用自身的方法,但我只是很难设置这个问题。到目前为止,我所掌握的是绘制初始薄片的数学知识,但我只是不知道如何设置递归来绘制薄片。

这是我到目前为止所拥有的。

import java.awt.*;
import java.util.Random;
import javax.swing.*;

public class SnowFlake extends JPanel {

private MainWindow panel;
private int x1OfFlake = 400;
private int y1OfFlake = 400;
private int maxLength = 200; // this is length of, 1 0f 6 branches for each individual flake

public SnowFlake() {
// generateRandCoodinatesLength();
}

public void generateRandCoodinatesLength() {
Random rn = new Random();
maxLength = rn.nextInt(200) + 100;
x1OfFlake = rn.nextInt(700) + 100;
y1OfFlake = rn.nextInt(700) + 100;
}


public void paint(Graphics g) {
drawFlake(levels, x1OfFlake, y1OfFlake, g); // x1, y1, x2, y2
}

public void drawFlake(int level, int x1, int y1, Graphics g){
//below was just how I made sure my picture was correct
/*
g.drawLine(x1, y1, 600, 400); //1
g.drawLine(x1, y1, 500, 227); //2
g.drawLine(x1, y1, 300, 227); //3
g.drawLine(x1, y1, 200, 400); //4
g.drawLine(x1, y1, 300, 573); //5
g.drawLine(x1, y1, 500, 573); //6
*/
g.drawLine(x1, y1, x1 + maxLength, y1); // 1
g.drawLine(x1, y1, x1 + (maxLength / 2), y1 - ((int) ((maxLength / 2) * Math.sqrt(3)))); // 2
g.drawLine(x1, y1, x1 - (maxLength / 2), y1 - ((int) ((maxLength / 2) * Math.sqrt(3)))); // 3
g.drawLine(x1, y1, x1 - maxLength, y1); // 4
g.drawLine(x1, y1, x1 - (maxLength / 2), y1 + ((int) ((maxLength / 2) * Math.sqrt(3)))); // 5
g.drawLine(x1, y1, x1 + (maxLength / 2), y1 + ((int) ((maxLength / 2) * Math.sqrt(3)))); // 6
}
}

这就是最终结果应该是什么样的,除了绘制了更多分支。

picture

最佳答案

这可以让你更接近你想要的

public void drawFlake(int level, float angleDegrees, Graphics g) {
/*
* Exit condition
* If the max number of levels has been reached,
* or the maxLength is no longer visible when drawn
*/
if (level >= MAX_LEVEL || maxLength == 0) {
return;
}

/*
* Secondary condition, increment the level if we've gone around the
* circle once
*/
if (angleDegrees >= 360) {
maxLength *= .9;
drawFlake(level + 1, 0, g);
return;
}

g.drawLine(
centerX,
centerY,
centerX + (int) (maxLength * Math.sin(Math.toRadians(angleDegrees))),
centerY + (int) (maxLength * Math.cos(Math.toRadians(angleDegrees))));

int currentLevelAngleIncrement = 60 / (level + 1);
drawFlake(level, angleDegrees + currentLevelAngleIncrement, g);
}

结果是这样的.. enter image description here

关于java - 绘制递归雪花,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29054272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com