切片地图加载问题



在我制作的平台游戏中,我需要加载瓷砖才能创建关卡,但在下面的代码中我似乎遇到了问题。它说我在这一部分有一个错误:

String[] skips = skip.split(" ");

但这对我来说似乎很好,而且以前总是有效。有人可以给我一些关于为什么这不起作用的见解吗?

地牢.java

package ScreenContents;
import java.awt.Color;
import java.awt.Graphics;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class Dungeon {

private static int width;
private static int height;
private static final int tileSize = 32;
private int[][] map;
public void readMap(String location){
    URL url = getClass().getResource(location);
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        width = Integer.parseInt(reader.readLine());
        height = Integer.parseInt(reader.readLine());
        map = new int[height][width];
        for (int y = 0; y < height; y++){
            String skip = reader.readLine();
            String[] skips = skip.split(" ");
            for (int x = 0; x < width; x++){
                map[y][x] = Integer.parseInt(skips[x]);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
public void renderMap(Graphics g){
    for (int y = 0; y < height; y++){
        for (int x = 0; x < width; x++){
            int newMapPos = map[y][x];
            if (newMapPos == 0){
                g.setColor(Color.black);
            }
            if  (newMapPos == 1){
                g.setColor(Color.white);
            }
            g.fillRect(x * tileSize, y * tileSize, tileSize, tileSize);
        }
    }
}
}

行:String[] skips = skip.split(" "); 跳过设置为 null。

这是因为reader.readLine();返回 null。

查看文档"包含行内容的字符串,不包括任何行终止字符,如果已到达流的末尾,则为 null"。

您基本上从文件中读取了太多行,这意味着文件中的高度与文件中实际的行数不匹配。

最新更新