2014-02-13 37 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。