Make a tilemap based off of text file?

So I have a text file like this:
1 0 1 1 1 1 0 1
1 0 1 1 1 1 0 1
1 0 1 1 1 1 0 1
1 0 1 1 1 1 0 1
1 0 1 1 1 1 0 1
1 0 1 1 1 1 0 1
1 0 1 1 1 1 0 1
1 0 1 1 1 1 0 1

And I want to get the following from this file:
The number of lines
A double array of all values (i.e. In this file, tiles[2][2] = 0)

So should I use scanner, or what? I tried scanner, but cannot figure out how to get this info.

http://lmgtfy.com/?q=java+read+a+text+file
http://lmgtfy.com/?q=java+find+number+of+lines+in+a+text+file
Use google, guys! This has been asked so many times on so many different forums.



public int[] readMap(Scanner scanner)
{
    // storage for the raw lines
    Vector<String[]> lines = new Vector<String[]>();
    
    // width and height of the map
    int width = 0;
    int height = 0;
    
    // read all lines from scanner
    
    while(scanner.hasNextLine()){
        String[] str_tiles = scannet.nextLine().split(" ");
        
        if(str_tiles.length > width)
                width = str_tiles.length;
        
        lines.add(str_tiles);
        height++;
    }
    
    // we are done reading
    
    // create map array
    int[][] map = new int[height][width];
    
    int yCount = 0;
    for(String[] strAry : lines){
        
        for(int xCount = 0; xCount < strAry.length; xCount++){
            map[yCount][xCount] = Integer.parseInt(strAry[xCount]);
        }
        
        yCount++;
    }
    
    return map;
}


Just some simple code on how to read a map.
Note that this code is really inefficient and won’t work for map’s that are very big (like 1000x1000 tiles).

  • Longor1996

There is a reason the xCount/yCount are used this way.
Reason: Images (too) are saved in a PIXEL[y][x] way.
And since tile-map’s are just image’s in my opinion, im using it this way.
An even better way to do the whole thing would be to just use a int[index] array.


int[] map = new int[width * height];

// input: x, y, value
map[x + y * width] = value;


This is:

  • Memory efficient
  • A bit faster

Have a nice day!

  • Longor1996