0

我不明白为什么我的代码会产生如下所示的内容。我希望瓷砖在窗口中对齐。窗口大小在主类中设置:

this.getContentPane().setPreferredSize(new Dimension(WINDOW_X, WINDOW_Y));

这是我的地图课。

public class Map1 {

int mapx = 19;
int mapy = 19;

int tileWidth = 600 / (mapx + 1);
int tileHeight = 500 / (mapy + 1);

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

public void drawLevel(Graphics g){
    g.setColor(Color.GREEN);

    for (int x = 0; x <= mapx; x++){

        for (int y = 0; y <= mapy; y++){

            int L = x * tileWidth;
            int U = y * tileHeight;
            int R =  tileWidth;
            int D =  tileHeight;

            if (map[y][x] == 1){
                //g.fillRect((x * tileWidth), (y * tileHeight), (x + tileWidth), (y + tileHeight));
                g.fillRect(L, U, R, D);
            }

            }

        }

    }

}

http://www.flickr.com/photos/88246499@N05/8067438151/

4

1 回答 1

0

在您的嵌套 for 循环中,drawLevel您使用变量y来索引瓦片地图的 x 坐标,并x索引 y 坐标。当您定义L并且U因为您与瓷砖的错误尺寸相乘时,就会出现问题。因为在你的循环里面x是一个沿着你必须写的高度的度量int U = x*tileHeight;int L = y*tileWidth.

我在下面的代码中交换了两个 for 循环,所以xy具有共同的含义。

for (int y = 0; y <= mapy; y++){
    for (int x = 0; x <= mapx; x++){
        int L = x * tileWidth;
        int U = y * tileHeight;
        int R =  tileWidth;
        int D =  tileHeight;
        if (map[x][y] == 1){
            g.fillRect(L, U, R, D);
        }
    }

}

我希望这能解决你的问题。

于 2012-10-08T16:48:06.357 回答