输入ASCII世界地图中的Java [英] Import ascii world map in Java

查看:182
本文介绍了输入ASCII世界地图中的Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要导入为ASCII地图为我的Java游戏设定的世界,你将能够在走动。

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

例如

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

其中#是墙壁G是黄金E是出口和。是空白空格上移动。我现在有这样一个.txt文件。我需要创建的地图导入到2D 的char [] [] 阵列。

如何将这项工作。最新最好的方式做到这一点。我还没有对二维数组任何工作还没有,所以这是我的新。

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.

谢谢,夏兰。

推荐答案

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

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

这篇关于输入ASCII世界地图中的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆