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

Started by
0 comments, last by phil05 19 years, 10 months ago
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;
}
 
Advertisement
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.
___________________________________________________VRAM_Strider."This is the same damn ship that blows panels everytime it is shot, gets stolen on numerous occasions, has next to no security on any of its computer systems, allows almost anyone into the heart of the ship, and places the bridge and all the exec offices on the top of the ship?That enterprise?"

This topic is closed to new replies.

Advertisement