0

我需要遍历一个类似于下面示例的地图,并获取它的宽度和高度以及文件每个点的数字。然后我在该位置添加一个平铺(乘以大小)宽度参数(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

我试图在地图上的相应位置添加一个新的 Tile,但 mapWidth 和 mapHeight 正在文件的第一个位置返回实际数据(在本例中为 2)。如何返回此文本文件数据的宽度和高度,以便向数组添加图块?这是我尝试过的代码:

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(); }
4

1 回答 1

0

看起来问题在于您如何解析文件。对于这个问题的性质,你需要逐行解析,然后在行内,你可以逐项解析。

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

数据:

$猫瓷砖.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]'.

希望有帮助!

于 2015-05-03T00:17:38.810 回答