【问题标题】:How can I create a Java multidemensional array when trying to create a map for a game?尝试为游戏创建地图时如何创建 Java 多维数组?
【发布时间】:2021-09-03 18:30:15
【问题描述】:

我正在开发一款游戏以了解更多 Java 的基本概念,并且我想创建一个游戏地图。所以我已经创建了我的类、字段、构造函数,我想开始使用多维数组创建一个简单的地图。

这是我目前所拥有的:

public class GridSquare {
    public int x;
    public int y;
    public Character character;
    public boolean isWall;
    public Item item;
    public Shop shop;
    
    public GridSquare(int gridRow, int gridColumn, Character gridCharacter, boolean isWall, Item gridItem, Shop gridShop) {
        this.y = gridRow;
        this.x = gridColumn;
        this.character = gridCharacter;
        this.isWall = isWall;
        this.item = gridItem;
        this.shop = gridShop;
        
    }
}

这个想法是角色可以在地图中导航,并且在导航时他们可以遇到某些事物,例如物品和商店。我有点卡在我可以从这里去的地方,因为我没有太多使用多维阵列的经验,但我想学习。如果可以的话,请随时向我指出一些有用的资源。

【问题讨论】:

    标签: java arrays multidimensional-array


    【解决方案1】:

    您似乎想要创建一个由正方形组成的 2D 网格,其中每个正方形由一个 GridSquare 实例表示。您可以按如下方式创建和初始化这样的数组:

    int width = ...;
    int height = ...;
    GridSquare[][] gridSquares = new GridSquare[width][height];
    for(int x = 0; x < width; x++) {
        for(int y = 0; y < height; y++) {
            gridSquares[x][y] = new GridSquare(x, y, ...);
        }
    }
    

    您可以随时使用以下方法在任何位置获得正方形:

    GridSquare gridSquare = gridSquares[x][y];
    

    我希望这能回答你的问题。

    【讨论】:

    • 谢谢。你能解释一下 gridSquares[x][y] = new GridSquare(x, y, ...);在第二个 for 循环内做什么?
    • 该语句正在为二维数组中的某个位置赋值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    相关资源
    最近更新 更多