简体   繁体   English

数组中Java的平铺地图

[英]tiled map in java from array

I am attempting to iterate through a 2D array of integers to generate a tiled map using Java's Graphics2D. 我试图遍历2D整数数组以使用Java的Graphics2D生成平铺的地图。

    int[][] mapArray = {{1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 0, 0, 0, 0, 0, 0, 1},
                    {1, 0, 0, 0, 0, 0, 0, 1},
                    {1, 0, 0, 0, 0, 0, 0, 1},
                    {1, 0, 0, 0, 0, 0, 0, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1}};

    public void draw(Graphics2D g2d){
    for(int y = 0; y < mapArray.length; y++){
        for(int x = 0; x < mapArray[0].length; x++){
            if(mapArray[x][y] == 1){
                 ImageIcon ic = new ImageIcon("/Textures/stone.jpg");
                 g2d.drawImage(ic.getImage(), x, y, null);
            }
            else if(mapArray[x][y] == 0){
                 ImageIcon ic = new ImageIcon("/Textures/water.jpg");
                 g2d.drawImage(ic.getImage(), x, y, null);
            }

I just can't seem to wrap my head around the logic of iterating a 2D array. 我只是似乎无法绕过2D数组迭代的逻辑。 Ideally, each 0 would represent a water tile while each 1 would represent a stone tile. 理想情况下,每个0代表一个水砖,而每个1代表一个石砖。 Every time I run this I get a NullPointerException . 每次运行此命令时,我都会收到NullPointerException

x and y are wrong way around x和y错误的方法

public void draw(Graphics2D g2d){
    for(int y = 0; y < mapArray.length; y++){
        for(int x = 0; x < mapArray[y].length; x++){ //you want to use y here not 0
            if(mapArray[y][x] == 1){                 //first box is outer array second is inner one
                ImageIcon ic = new ImageIcon("/Textures/stone.jpg");
                g2d.drawImage(ic.getImage(), x, y, null);
            } else if(mapArray[y][x] == 0){
                ImageIcon ic = new ImageIcon("/Textures/water.jpg");
                g2d.drawImage(ic.getImage(), x, y, null);
            }
        }
    }
}

I could see potentially two big issues in your code, in your code "y" represents rows and "x" represents columns but in your if statement you are picking [column][row] and while having a dry run you are probabily counting [row][column] and secondly you are always counting columns that are present in first row. 我可能会在您的代码中看到潜在的两个大问题,在您的代码中,“ y”代表行,“ x”代表列,但是在if语句中,您正在选择[column] [row],而在空运行时,您可能在计算[ row] [column],然后您总是要计算第一行中存在的列。 if your data structure is always nXn in such case it will work but in any other case you would have different results and you might encounter ArrayIndexOutofBound exception. 如果在这种情况下您的数据结构始终为nXn,则它将起作用,但在任何其他情况下,您将得到不同的结果,并且可能会遇到ArrayIndexOutofBound异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM