creating a level from an image :) im doing progress but i need help :P

hey guys i started working on a class that would take an image and turn it into a map and im progressing :smiley: i have converted all the pixels into hex color codes and stored them in array and everything is working fine :stuck_out_tongue: except when im trying to all the createMap method to actually create the tiles :confused: its throwing me a nullPointerException and i can’t seem to find the reason :stuck_out_tongue: any suggestions ?

code:

public class Level {
	
	public static BufferedImage createDataArray(BufferedImage level) {
		String[] pixels = new String[level.getHeight() * level.getWidth()];
		BufferedImage out = level;
		for(int x = 0;x < level.getHeight(); x++) {
			for(int y = 0; y < level.getWidth();y++) {
				int rgb = level.getRGB(x, y);
				String hex = Integer.toHexString(rgb & 0x00ffffff);
				pixels[x+y] = hex;
			}
		}
		createMap(pixels);
		return out;
	}
	
	public static void createMap(String[] pixels) {
		for(String s : pixels) {
			if(s.equals("000000")) {
				System.out.println("wall");
			}
			if(s.equals("06941a")) {
				System.out.println("grass");
			}
		}
	}
}

You’ve got your width and height variables mixed up. You should also be multiplying your y value by the width before adding the x - you’re getting the NPE because you’re missing loads of values out and allocating the same value lots of times instead. Something like this should be what you’re looking for (hopefully correct, not compiled).


int width = level.getWidth();
int height = level.getHeight();
for(int y = 0; y < height; y++) {
  for(int x = 0; x < width; x++) {
    int rgb = level.getRGB(x, y);
    String hex = Integer.toHexString(rgb & 0x00ffffff);
    pixels[(y * width) + x] = hex;
  }
}

I also recommend that you use a 2 Dimensional array. It’s essentially an array of arrays.


int width = 10, height = 5;
String[][] myArray = new String[width][height];

Then, when you want to retrieve a String, you can loop through it like…


for(int x=0; x<width; x++)
{
    for(int y=0; y<height; y++)
    {
        String element = myArray[x][y];      // You've accessed a particular string in the 2D Array.  Do whatever you want with it!
    }
}

Oh, one last thing…

pixels[x+y] = blah blah blah… Is unsafe.

If x is 5 and y is 10, you get pixels[15] = blah blah blah.
If x is 10 and y is 5, you STILL get pixels[15] = blah blah blah.

It won’t guarantee that you’ll be writing to an empty slot in the array. 2D arrays are the best!