Import ascii world map in Java

2019-07-27 11:09发布

I need to import a as ascii map into my Java game to set the world you will be able to move around in.

For example.

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

Where the # are walls G is gold E is exit and the . are blanks spaces to move around on. I currently have this in a .txt file. I need to create a method to import the map into a 2D char[][] array.

How would this work. Whats the best way to do this. I haven't done any work with 2D arrays yet so this is new to me.

Thanks, Ciaran.

2条回答
不美不萌又怎样
2楼-- · 2019-07-27 11:21

Just have 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++;
  }
}

The map will be created. It is up to you to add in functionality for Gold, exits and walls. I suggest using enums or an abstract Tile class.

Hope this healped.

Jarod.

查看更多
Melony?
3楼-- · 2019-07-27 11:36

Haven't tested it but this should do the trick:

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);
    }
}
查看更多
登录 后发表回答