2014-02-13 34 views
0

我需要导入为ASCII映射到我的Java游戏设置世界里,你将能够在走动。导入ASCII世界地图中的Java

例如。

################### 
#.................# 
#......G........E.# 
#.................# 
#..E..............# 
#..........G......# 
#.................# 
#.................# 
################### 

其中#是墙G是金E是退出和。是空白的空间来移动。我目前在.txt文件中有这个。我需要创建一个将地图导入2D char[][]阵列的方法。

这将如何工作。最好的办法是做到这一点。我还没有做2D数组的任何工作,所以这对我来说是新的。

谢谢,Ciaran。

+0

“我还没有做2D数组的任何工作,所以这对我来说是新的。” - 时间[阅读教程](http://docs.oracle.com/javase/tutorial/)。 – Maroun

+0

Java中没有“2D数组”这样的东西。这些只是其元素本身就是数组的数组。 – fge

+0

@fge:true,但通常也称为二维数组,与3维数组以及4和5一样... :) – GameDroids

回答

0

没有测试它,但这应该做的伎俩:

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); 
    } 
} 
0

只要有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++; 
    } 
} 

该地图将被创建。您需要为黄金,出口和墙壁添加功能。我建议使用枚举或抽象Tile类。

希望这个医治。

Joard。