Public Group

#### Archived

This topic is now archived and is closed to further replies.

# What's the best way to use 2d arrays for maps?

This topic is 5244 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I''m a beginner using 2d arrays for C++. I''m wondering if there''s a better way for player control in where he wants to go. I was thinking his movements can be done by functions, but lemme know what you think.
#include <iostream>

int main()
{
// 9 = Player
// 1 = Tree
// 0 = Grass

int Forest[5][5] = {
{ 1, 1, 1, 1, 1},
{ 1, 1, 1, 1, 1},
{ 1, 0, 0, 9, 0},
{ 1, 0, 0, 0, 1},
{ 1, 1, 1, 1, 1}  };

if (Forest[2][2] == 0)
{
std::cout << "You walk east." << std::endl;
std::cout << Forest[2][2] << std::endl;
}
else
{
std::cout << "You can''t walk that way." << std::endl;
}

return 0;
}


##### Share on other sites
The storage you use depends on the problem. Yes, for this program you can use an array to represent the map of the arrea. You can also create a structure called position with two variables (x and y) to represent the current possition of the player. then you need a loop, in which you will be asking the player where he wants to go(eg. 1-north 2-east 3-south 4-west 0-quit). you ''ll get players input, and update his position, as well as display a message like "you moved east, you are at position 2,4". don''t forget to check that the player''s input is valid before you querry your array. if you go out of bounds, you''ll get awkward results.

Good luck!
VStrider.

1. 1
Rutin
25
2. 2
3. 3
4. 4
5. 5

• 10
• 13
• 19
• 14
• 9
• ### Forum Statistics

• Total Topics
632943
• Total Posts
3009347
• ### Who's Online (See full list)

There are no registered users currently online

×