我目前正在尝试使用菱形和正方形算法制作分形地形生成器。我已经完成了算法(我想),但我不知道如何很好地使用JFrames
。
我该如何让它显示瓷砖?
package fractal.terrain;
import java.util.Random;
public class Main {
public int mapSize = 257;
public static void main(String[] args) {
Main m = new Main();
double tileData[][] = new double[m.mapSize][m.mapSize];
Random r = new Random();
final double seed = r.nextInt(10000 - 500 + 1);
System.out.println("The seed is " + seed);
tileData[0][0] = tileData[0][m.mapSize - 1] = tileData[m.mapSize - 1][0]
= tileData[m.mapSize - 1][m.mapSize - 1] = seed;
double h = 10000.0;
for (int sideLength = m.mapSize - 1; sideLength >= 2; sideLength /= 2) {
int halfSide = sideLength / 2;
for (int x = 0; x < m.mapSize - 1; x += sideLength) {
for (int y = 0; y < m.mapSize - 1; y += sideLength) {
double avg = tileData[x][y]
+ tileData[x + sideLength][y]
+ tileData[x][y + sideLength]
+ tileData[x + sideLength][y + sideLength];
avg /= 4.0;
tileData[x + halfSide][y + halfSide] = avg + (r.nextDouble() * 2 * h) - h;
}
}
for (int x = 0; x < m.mapSize - 1; x += halfSide) {
for (int y = (x + halfSide) % sideLength; y < m.mapSize - 1; y += sideLength) {
double avg = tileData[(x - halfSide + m.mapSize) % m.mapSize][y]
+ tileData[(x + halfSide) % m.mapSize][y]
+ tileData[x][(y + halfSide) % m.mapSize]
+ tileData[x][(y - halfSide + m.mapSize) % m.mapSize];
avg /= 4.0;
avg = avg + (r.nextDouble() * 2 * h) - h;
tileData[x][y] = avg;
if (x == 0) {
tileData[m.mapSize - 1][y] = avg;
}
if (y == 0) {
tileData[x][m.mapSize - 1] = avg;
}
}
}
}
}
}
覆盖JPanel上的draw方法,并在数组中循环为每个值绘制不同颜色的矩形。
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
for (int x = 0; x < m.mapSize; x++) {
for (int y = 0; y < m.mapSize; y++) {
//check each tile and assign in a color based on its value
if(tileData[x][y] == aCertainNumber){
g.setColor();
}
g.fillRect(x*10, y*10, 10, 10);
}
}
这应该显示每个瓦片10像素乘10像素的
你也可以用输出到图像
BufferedImage map = new BufferedImage(mapSize, mapSize,BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < mapSize; x++) {
for (int y = 0; y < mapSize; y++) {
if(mapData[x][y]==aCertainNumber)
map.setRGB(x, y, theColorYouWant.getRGB());
}
}