Programmer02293
Programmer02293

Reputation: 1

Making an Object with Positional Brackets Similar to an Array

I am trying to create an object that has brackets, much like an array, but I want it to be an object so that I can have methods such as hasLocation or returnMap. The array that I want to be an object is called Map. My code before I created the Map object is below:

public class Main {
public static void main(String[] args) {
    gamePreset();
}
public static void gamePreset(){
    /**
     * Creating Locations
     * It is important to note that the yPos starts in the left corner of the map and increases southward.
     * (0,0)|(1,0)|(2,0)
     * -----------------
     * (0,1)|(1,1)|(2,1)
     * -----------------
     * (0,2)|(1,2)|(2,2)
     */
    Location location00 = new Location(0,0,entities00,"This is location 00. Welcome to the map.");
    Location location01 = new Location(0,1,entities01,"This is location 01. You are south of location 00.");
    Location location11 = new Location(1,1,entities01,"This is location 11. You are southeast of location 00.");
    Location location10 = new Location(1,0,entities01,"This is location 10. You are east of location 00.");

    //Adding Locations to the Map Array
    Location[][] map = new Location[2][2];
    map[0][0] = location00;
    map[0][1] = location01;
    map[1][1] = location11;
    map[1][0] = location10;

    System.out.println(returnMap(map));
}

public static String returnMap(Location[][] map){
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < map.length; i++){
            for(int j = 0; j < map[i].length; j++){
                sb.append("(" + map[i][j].getXPos() + "," + map[i][j].getYPos() + ")");
                sb.append(" ");
            }
            sb.append("\n");
        }
        return sb.toString();
    }

public static boolean hasLocation(Location[][] map, int xPos, int yPos){
    if(map[xPos][yPos]!=null){
        return true;
    }
    return false;
}

Location holds an xPosition, a yPosition, a message, and a list of objects at that location. What I want is an object that still has the bracketed positions like my array: Location[][] map = new Location[2][2]; Is this possible? Is there a better way to go about it? I tried to make a constructor but I am unsure about how to proceed:

public class Map {
    public Location[][] map;
    Map(int xHeight, int yHeight, String mapName){
        Location[][] mapName = new Location[xHeight][yHeight];
    }
    .....methods like returnMap.....
}

If all went my way my code would look like:

Map newMap = new Map(2,2,"map00");
newMap[1][1] = location00;

Upvotes: 0

Views: 55

Answers (1)

Frazer
Frazer

Reputation: 56

just do:

Map newMap = new Map(2,2,"map00");
newMap.map[1][1] = location00;

Upvotes: 1

Related Questions