将文本文件(地图)加载到 int 数组中

Loading a text file (map) in to an int array

我需要遍历一个类似于下面示例的地图,并获取它的宽度和高度以及文件每个点的编号。然后,我向该位置添加一个瓦片(乘以大小)宽度参数 (x, y, width, height, id)。 “id”是文本文件中的当前数字。以下是该文件的示例:

2 0 0 0 0 0 0 0 0 2
2 0 0 0 0 0 0 0 0 2
2 0 0 0 0 0 0 0 0 2
1 1 1 1 1 1 1 1 1 1

我试图在地图上的相应位置添加一个新的图块,但 mapWidth 和 mapHeight return 是文件第一个位置的实际数据(在本例中为 2)。我怎样才能 return 这个文本文件数据的宽度和高度,以便我可以向数组中添加一个图块?这是我试过的代码:

try {
    Tile[][] tiles;
    int mapWidth, mapHeight;
    int size = 64;
    //variables in same scop to save you time :)

    FileHandle file = Gdx.files.internal(s);

    BufferedReader br = new BufferedReader(file.reader());

    mapWidth = Integer.parseInt(br.readLine());
    mapHeight = Integer.parseInt(br.readLine());

    System.out.println(mapWidth);

    int[][] map = new int[mapWidth][mapHeight];
    tiles = new Tile[mapWidth][mapHeight];

    for(int i = 0; i < tiles.length; i++) {
        for(int j = 0; j < tiles[i].length; j++) {
            tiles[i][j] = new Tile(i * size, j * size, size, map[j][i]);
        }
    }

    br.close();         
} catch(Exception e) { e.printStackTrace(); }

看来问题出在您解析文件的方式上。对于这个问题的性质,需要逐行解析,然后在行内,逐项解析。

这是一个如何解析数据的一般示例(我正在使用 List 和 ArrayList,这样我就不需要处理数组的大小......如果你想使用物理数组您可以先将整个文件读入内存 List<String> lines = new ArrayList();,然后缓冲的 reader 可以插入到此 List 中,您可以遍历它以添加项目的每个子数组。

数据:

$ cat Tiles.dat 
2 0 0 0 0 0 0 0 0 2
2 0 0 0 0 0 0 0 0 2
2 0 0 0 0 0 0 0 0 2
1 1 1 1 1 1 1 1 1 1

脚本(解析文件的示例):

$ cat Tiles.java 
import java.io.*;
import java.util.*;

class MainApp {
    public static void main(final String[] args) {
        final String fileName = "Tiles.dat";
        try {
            File file = new File(fileName);
            FileReader fileReader = new FileReader(file);
            BufferedReader br = new BufferedReader(fileReader);

            List<List<Integer>> map = new ArrayList<List<Integer>>();

            String line = null;
            while ((line = br.readLine()) != null) {
                String[] items = line.split(" ");
                ArrayList<Integer> intItems = new ArrayList<Integer>();
                for (String item : items) {
                    int intItem = Integer.parseInt(item);
                    intItems.add(intItem);
                }

                map.add(intItems);
            }
            br.close();

            System.out.println("map: '" + String.valueOf(map) + "'.");
            for (List<Integer> intItems : map) {
                System.out.println("intItems: '" + String.valueOf(intItems) + "'.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

输出:

$ javac Tiles.java 
$ java MainApp 
map: '[[2, 0, 0, 0, 0, 0, 0, 0, 0, 2], [2, 0, 0, 0, 0, 0, 0, 0, 0, 2], [2, 0, 0, 0, 0, 0, 0, 0, 0, 2], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]'.
intItems: '[2, 0, 0, 0, 0, 0, 0, 0, 0, 2]'.
intItems: '[2, 0, 0, 0, 0, 0, 0, 0, 0, 2]'.
intItems: '[2, 0, 0, 0, 0, 0, 0, 0, 0, 2]'.
intItems: '[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]'.

希望对您有所帮助!