# Having problems with 2d arrays

• 01-04-2004
newy100
Having problems with 2d arrays
Hi

I am making a simple text based game, basically, it is a 20x20 board and i am keeping track of the player with 2 integers (x and y). I describe the terrain at each turn using a 20x20 character array (M for mountains, W for water etc)

Now i have to add enemies to the game and keep track of what enemies are in each square using a 2d array and randomly assign monsters to each square (lots of the squares will be empty, but some may have up to 3 monsters)

I am totally confused how to do this, i was thinking of having a 2d character array to keep track of the type of enemy in each square (O for orcs etc) but they have to be random and vary in number for each square and i am unsure how to keep track of all this information...

Not sure if thats making much sense....

• 01-04-2004
-=SoKrA=-
Create a struct to hold all the data you might need for a square, and crate the 2D array of that square. eg.
Code:

```struct square {         /*This will hold the number of enemies we         *assign to this particular square         */         int NumberOfEnemies;         /*         *enemy_t would be a user-defined type with         *all the data needed for the enemy. It's a         *pointer as we will use it to create a         *dynamically-sized array with all the         *enemies         */         enemy_t* enemy;         /*         *GroundType will tell us if it's water, mountain         *or whichever type we want to use.         *It would probably be better to use an enum         *for this job.         */         char GroundType; };```
• 01-04-2004
gustavosserra
In my opinion, this might seem complicated for beginners. But try this:
Build a matrix of the stl vector. Vector is easy to use once that you got how it works:
Code:

`  vector<int> board[20][20];`
You could use integers to represent everthing in your world:
1 - Water
2 - Mountain
3 - Orc
4 - Elf
So on...
• 01-04-2004
newy100
Thanks for the replies, much appreciated
Im a newbie to c++ and so havent done vectors, pointers yet, just the basics and 2d and 3d arrays...covered structs a little bit but not in much detail
will read up on structs to see if i can understand it more
thx again
• 01-04-2004
Salem
```vector<square> board[20][20]; ... board[0][0].GroundType = 1;```