首先,需要定义一个二维数组来表示地图,例如:

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

上面的二维数组表示一个大小为10x10的地图,其中 1 表示墙,0 表示空地。

然后,在 Swing 中创建一个 JPanel 来表示地图,可以使用 GridLayout 布局来将地图拆分为多个小方格,并根据二维数组中的值来设置每个小方格的背景色,例如:

public class MapPanel extends JPanel {
    private int[][] map;

    public MapPanel(int[][] map) {
        this.map = map;
        int rows = map.length;
        int cols = map[0].length;
        setLayout(new GridLayout(rows, cols));
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                JPanel cell = new JPanel();
                cell.setBackground(map[i][j] == 1 ? Color.BLACK : Color.WHITE);
                add(cell);
            }
        }
    }
}

这样就可以通过 MapPanel 来显示地图了。

Swing 坦克大战地图构建:使用二维数组创建游戏地图

原文地址: https://www.cveoy.top/t/topic/lR3U 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录