我需要将ascii地图导入到我的Java游戏中,以设置您可以移动的世界。
例如。
###################
#.................#
#......G........E.#
#.................#
#..E..............#
#..........G......#
#.................#
#.................#
###################
其中#是墙G是金E是退出而且。是空白的空间来移动。我目前在.txt文件中有这个。我需要创建一个方法将地图导入2D char[][]
数组。
这将如何运作?什么是最好的方法来做到这一点。我还没有完成2D阵列的任何工作,所以这对我来说是新的。
谢谢,Ciaran。
答案 0 :(得分:1)
没有测试过,但这应该可以解决问题:
public static void main(String[] args) {
// check what size your array should be
int numberOfLines = 0;
try {
LineNumberReader lineNumberReader = new LineNumberReader(new FileReader("map.txt")); // read the file
lineNumberReader.skip(Long.MAX_VALUE); // jump to end of file
numberOfLines = lineNumberReader.getLineNumber(); // return line number at end of file
} catch (IOException ex) {
Logger.getLogger(YouClass.class.getName()).log(Level.SEVERE, null, ex);
}
// create your array
char[][] map = new char[numberOfLines][]; // create a 2D char[][] with as many char[] as you have lines
// read the file line by line and put it in the array
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("map.txt"))) {
int i = 0;
String line = bufferedReader.readLine(); // read the first line
while (line != null) {
map[i++] = line.toCharArray(); // convert the read line to an array and put it in your char[][]
line = bufferedReader.readLine(); // read the next line
}
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
答案 1 :(得分:1)
只有2 Scanners?
public char [] [] map = new char [9] [19];
public void readMap() {
File f = new File("C:\Path/To/Your/Map.txt")
Scanner fScan = new Scanner(f);
int x;
int y;
while(fScan.hasNextLine()) {
String line = fScan.nextLine()
for(x = 0; x < line.length(); x++) {
char[x][y] = line.charAt(x, y);
}
y++;
}
}
将创建地图。您可以在Gold,exits和wall中添加功能。我建议使用枚举或抽象的瓷砖类。
希望这能愈合。
贾罗德。