Diamond square algorithm

后端 未结 4 1565
栀梦
栀梦 2020-12-04 12:44

I\'m trying to write the Diamond-Square algorithm in Java to generate a random map but can\'t figure out the implementation...

Anyone with some Java code (or other l

4条回答
  •  失恋的感觉
    2020-12-04 13:09

    This is an interesting algorithm for generating values. Here is an implementation that I have created based on the explanation give at this page in the references from the wikipedia article. It will create "spherical values" (wrapped at all the edges). There are notes in the comments for how to change it to generate new values on the edges instead of wrapping (though the meaning of average for the edges isn't really correct in these cases).

    //size of grid to generate, note this must be a
    //value 2^n+1
    final int DATA_SIZE = 9;
    //an initial seed value for the corners of the data
    final double SEED = 1000.0;
    double[][] data = new double[DATA_SIZE][DATA_SIZE];
    //seed the data
    data[0][0] = data[0][DATA_SIZE-1] = data[DATA_SIZE-1][0] = 
      data[DATA_SIZE-1][DATA_SIZE-1] = SEED;
    
    double h = 500.0;//the range (-h -> +h) for the average offset
    Random r = new Random();//for the new value in range of h
    //side length is distance of a single square side
    //or distance of diagonal in diamond
    for(int sideLength = DATA_SIZE-1;
        //side length must be >= 2 so we always have
        //a new value (if its 1 we overwrite existing values
        //on the last iteration)
        sideLength >= 2;
        //each iteration we are looking at smaller squares
        //diamonds, and we decrease the variation of the offset
        sideLength /=2, h/= 2.0){
      //half the length of the side of a square
      //or distance from diamond center to one corner
      //(just to make calcs below a little clearer)
      int halfSide = sideLength/2;
    
      //generate the new square values
      for(int x=0;x

提交回复
热议问题