0

I am trying to create an array that contains several different things, so that I can display a sort of maze in the command line. I am trying to use '*' as the walls, and ' ' as empty spaces, but I would also like to add references to different objects, such as piles of gold, and little traps that are represented by characters like 'g' for gold, and 't' for trap.

All of the objects in the maze are going to be subclasses of a MazeObject class. So my question is whether I make the array out of chars, and how would I put object instances into the array, or should I make it a MazeObject array, but how do I include the '*' as walls, and ' ' as spaces. Or is there some way to have a MazeObject array of chars?

MazeObject maze[][] = new MazeObject[rows][columns]

or

char maze[][] = new char[rows][columns]

or polymorphism?

MazeObject[][] maze = new char[rows][columns]
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
bob
  • 135
  • 1
  • 4
  • 14
  • I would say make an array of MazeObjects with each one having a "physical representation" as a char member. – Leifingson Dec 13 '13 at 06:00
  • @Leifingson how would I go about adding the '*' and ' '? should I create separate objects for those? – bob Dec 13 '13 at 06:05
  • @bob Do you really need a two dimensional array? –  Dec 13 '13 at 06:23
  • @FunctionR I am trying to create a 2d game board. I am not sure how else to do this? – bob Dec 13 '13 at 06:27
  • @bob I would assign coordinates to each object using a Vector2d, which gives you **x** and **y** for each object. Check my answer. –  Dec 13 '13 at 06:31
  • @FunctionR This seems like a much better answer, but unfortunately my teacher is asking us to implement this file explicitly using 2d arrays. My main problem was that he never described which kind. – bob Dec 13 '13 at 06:36
  • @bob Ok I added exactly what you need to my answer. Now you have all the tools needed to fill a 2-D array. Good luck. –  Dec 13 '13 at 06:55

1 Answers1

1

I would define the MazeObject like the code below. Notice that char representation is really just a name or a character representation of your object. Then Object actualObj will be the physical object that you want in the maze.

public class MazeObject
{
    private char representation;
    private Object actualObj;

    public MazeObject(char r)
    {
        representation = r;
    } 

    public char getRepresentation()
    {
        return representation;
    }
}

Then you can make a list out of those by doing this:

int row = 5;
int col = 5;
MazeObject [][] list = new MazeObject [row] [col]; 

How do you populate a two dimensional array?

Answer, but still that answer is for ints. You are using MazeObjects so keep that in mind.

Solution

    MazeObject [][] list = new MazeObject [5] [5];

    list[0][0] = new MazeObject('a');

    System.out.println(list[0][0].getRepresentation());

Good luck with the rest, now you have all the tools needed to fill your 2-D array.

Community
  • 1
  • 1