In addition to what ApochPiQ mentioned, you should use an std::vector if you're going to have a large amount of data, because you're putting too much data on the stack which is why it crashes. This is called a
Stack Overflow, apparently (I never knew what it was called until just now
).
Using a std::vector puts the data on the heap instead, which won't crash your program with the amount of data you are using.
(Note: Just because std::vectors
are resizable, doesn't mean you have to use that. They are good as for constant sized arrays also. Infact, the new C++ standard even introduced a new type of container: A
non-resizable vector.
)
This code should give you a good boost-start:
#include <vector>
class Map
{
public:
Map(int width, int height) : width(width), height(height)
{
//Resize the vector to be the size we want (width * height).
this->tiles.resize((width * height), 0); //Initialize each tile to 0.
}
int Map::GetTile(int x, int y)
{
int index = _GetIndex(x,y);
//Make sure this is a valid index.
if(_IsValid(index))
{
return this->tiles[index];
}
return 0;
}
void Map::SetTile(int x, int y, int tileID)
{
int index = _GetIndex(x,y);
//Make sure this is a valid index.
if(_IsValid(index))
{
this->tiles[index] = tileID;
}
}
private:
int width, height;
std::vector<int> tiles;
//Converts from a two-dimensional x,y to a one-dimensional index into our vector.
int _GetIndex(int x, int y)
{
return (y * this->width) + x;
}
//Makes sure that we aren't going out of bounds, which will crash the program.
bool _IsValid(int index)
{
if(index < this->tiles.size())
return true;
return false;
}
};
int main()
{
const int NOTHING = 0;
const int GRASS = 1;
const int DIRT = 2;
const int DIFFERENT_DIRT = 3;
//...
const int WATER = 211;
const int LAVA = 300;
Map map(20, 20); //I want a map that's 20 by 20 tiles.
Map largeMap(2000, 5000); //I also want a map that's 2000 by 5000 tiles.
largeMap.SetTile(50, 100, DIRT) //Access tile X:50, Y:100, and set it to DIRT.
if(largeMap.GetTile(playerTileX, playerTileY) == LAVA)
{
//...damage the player.
}
}
If you have any questions about how it works, don't hesitate to ask.