Search code examples
javalwjgl

Java 2D Terrain Generation Using Seeds


I am trying to make a 2D game in LWJGL. I am having a problem with terrain generation.
I currently have an algorithm to generate terrain but it is always random and I can never get that same world again I would like to make an algorithm that generates a x and y coordinates based on a given number.

My current world generation looks like this:

     final float STEP_MAX = 1f;
     final float STEP_CHANGE = 1;
     final int HEIGHT_MAX = 100;

     double height = HEIGHT_MAX;
     double slope = STEP_MAX;

     for (int x = -WORLDSIZE; x < WORLDSIZE; x++) {
          height += slope;
          slope += (Math.random() * STEP_CHANGE) * 2 - STEP_CHANGE;

          if (slope > STEP_MAX)  slope = STEP_MAX;
          if (slope < -STEP_MAX) slope = -STEP_MAX;

          if (height > HEIGHT_MAX) { 
              height = HEIGHT_MAX;
              slope *= -1;
          }
          if (height < 0) { 
              height = 0;
              slope *= -1;
          }
          Tile newTile = new Tile(x*25,(int)height*25,25,25,TileType.Grass);
          tiles.add(newTile);

Thank you in advance for your help.


Solution

  • If you create your random number generator yourself (rather than letting Math.random() do so for you), you can specify a seed:

    Random random = new Random(yourSeed);
    random.nextDouble();
    

    the Random class also has many useful methods you might want to look at.

    More info: https://docs.oracle.com/javase/8/docs/api/java/util/Random.html