문제

I am making a fairly simple 2D Game Engine in Java using the Slick2D Library, and am trying to load levels (tile maps) from a text file. I want to be able to load in multiple different tilesets, and therefore don't want to assign each number to a tile like this:

    1 1 1 1 1
    1 0 0 0 1
    1 0 0 0 1
    1 0 0 0 1
    1 1 1 1 1

    (Where 1 is a wall and 0 is a floor)

instead, I would like to be able to use x and y coordinates in the tilemap to represent how many tiles across and down the tile is located at on the tileset, like this:

    0,0 0,0 0,0
    0,0 1,0 0,0
    0,0 0,0 0,0

    (0,0 is the tile in the upper left hand corner of the tileset, 1,0 is the second tile in the tileset)

The main problem I am having with this is reading the text file and storing the integer in front of the comma as Pos1 (the X value) and everything after the comma but in front of the space as Pos2 (the Y value).

How would I go about this? Would I use a regular file reader, a buffered reader, or a scanner?

Also, by the way, I am aware that Slick2D has built in capability of reading Tiled Map (.tmx) files, but since my game engine will have a built in tile map editor, I would like to use regular text files.

도움이 되었습니까?

해결책

If you need your files to be in that format so that you can open them in a text editor then I would use a BufferedReader to read the file then read in each line as a string and split the line first at each space then at each comma, then parse the string to return your number.

try(BufferedReader in = new BufferedReader(new FileReader("file"))){
    String line;
    while((line=in.readLine())!=null){
        String[] values = line.split(" ");
        for(String v:values){
            String[] coords = v.split(",");
            int x = Integer.parseInt(coords[0]);
            int y = Integer.parseInt(coords[1]);
}

However an easier way to do this may be to simply write the int values directly from your map editor instead of converting them to strings. If you do this then you would save space and all you would need to do to read the data is:

try(DataInputStream in= new DataInputStream(new BufferedInputStream(new FileInputStream(new File("file"))))){
    int numValues=in.readInt();
    for(int i=0;i<numValues;i++){
        int x = in.readInt();
        int y = in.readInt();
    }
}

And in your map editor to save the map you would just write the number of tiles to the file and then each of the tiles' x and y coordinates with writeInt() and a DataOutputStream.

You may also want to write the width and height of the map to the file so that you can reconstruct it if those are not constant, or the coordinates of the tile on the map.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top