Possible to save 2D array and load it?

Im making a game. im confused, because i dont know how i could make it better.

the variables terrainwidth and terrainheight can be any value and that cant be ignored!

the code that saves it can be modified, please help

void saveGame() {
  if (keyPressed && key == 'p') {
    String[] lines = new String[terrainwidth+1];
    lines[0] = "Do not modify; Only Terrain;";
    for (int i = 0; i < terrainwidth; i++) {
      lines[i+1] = "";
    }
    for (int i = 0; i < terrainwidth; i++) {
      for (int ix = 0; ix < terrainheight; ix++) {
        lines[i+1] += terrainbase[i][ix]+",";
      }
    }
    saveStrings(path+"worlds/world.txt", lines);
  }
}

void loadGame() {
  if(keyPressed && key == 't') {
    String[] lines1 = loadStrings(path+"worlds/grass-piramide.txt");
    String[] lines2 = new String[terrainwidth+1];
    String s1;
    for(int i = 0; i < terrainwidth+1; i++) {
      s1 = lines1[i];
      lines2 = split(s1, ",");
      for(int ix = 0; ix < terrainheight+1; i++) {
        terrainbase[i][ix] = Integer.parseInt(lines2[ix+1]);
      }
    }
  }
}

You are storing your data as text strings which has a nice advantage in that you can look at the file with a text editor and even make changes to the data outside of your game. However, in comparison to binary data files, they take up much more space and are slower to generate and to write and read from disk.

My favorite way to store 2D arrays in binary is a bit of a hack, but quite convenient in Processing which is to store the data as a PNG image and use PImage save() and load(). Create the image as ARGB, then loadPixels(), pixels[ j*terrainWidth+i ] = terrainbase[j][i], updatePixels(), and save(). You are never displaying the image, you’re just using it as an integer array. If you save it as a PNG, it will save compressed taking up even less disk space. (Don’t save as JPG since that will compress lossily, changing and losing some of your data in meaningless ways.)

If you want multiple values per cell, just make your image twice (or more) as wide and write multiple “pixels” per array value. You can also save and load float values using int bits = Float.floatToIntBits(f); to write and Float.intBitsToFloat() to read from your pixels[] array.

5 Likes

thats a great idea, i just wonder if it works for words like “50000 x 512”…

I’m not sure what the single dimension limit is. You might need to make that 12500 x 2048 to fit. But try it to find out. Just make some blank images the sizes you want and save them.