# Best way to store map?

I am trying to make a simple game that simulates ants inside a colony, in the Java language. They can move around the paths randomly, go outside to eat leaves, etc. The game is meant to be more of an exercise in programming logic, than an actual game, so I want to try to stay away from graphics, if at all possible. The idea I currently have is to use a 2D array, perhaps like:

public class Map {
int mapArray[][] = new int[5][5];

public static void main(String[] args) {
Map m = new Map();
}

public map() {
//Create the map
for(int x = 0; x < 5; x++) {
for(int y = 0; y < 5; y++) {
mapArray[y][x] = 0;
}
}

//Print the map
for(int x = 0; x < 5; x++) {
for(int y = 0; y < 5; y++) {
System.out.print(mapArray[x][y]);
}
System.out.println();
}
}
}


I would then do my logic based on the values at different positions in the array.

Is this the best way, or is there a different method that would work better than this one?

• There's rarely one best way for all situations. Try your idea and see what happens. If something goes wrong, then go back and change it. Most of the time it doesn't matter and it's not worth worrying about. – amitp Oct 6 '16 at 1:03

Yep, this is a good tactic for learning!

Focusing on the goal you actually want to achieve and not getting lost in the things you don't care about achieving right now (graphics) means you'll reach your goal faster and can move on to the next thing.

As far as this technique specifically of having a simple 2D text grid for your game/simulation, yeah that works great.

That's how I started, using QBasic and later C++ to make text games that used text for graphics. I am self taught and now I'm a professional game programmer so it worked out pretty well for me.

A 2D array is definitely the right way to go, if you want the ants to be limited to a flat surface. (This makes sense if you have, say, an ant terrarium.) Keep in mind, though, that if you want your ants to be walking around in 3D space, you will need a 3D array.

I do a lot of Java programming professionally, and I have a lot of suggestions to make your code a bit more advanced, but I don't want to overwhelm you, and I think that this is a really good start if you don't want to get into things like ArrayList<Integer> and enum (enumerated types) just yet.

You do need to decide what the different int values mean in your map. Is 0 a wall? Is 1 sand? Is 2 leafy growth? That's something you'll need to plan as you go, and where enum would come in handy.

Then you can model an ant's position with its (x,y) coordinate, and you should be good to go.

Good luck!! Programming is a lot of fun, and Java and Python are both great languages to start in.

Your on the right track and I would use nested for loops for the x and y, just like you, except unless I'm missing something, I think you can store the grid coordinates and print them to the screen in the same loop.