Search code examples
c++sdlsdl-ttf

SDL: Making Static Text Variables


I am making Minesweeper using SDL and thus I have to use text to label each tile with a number representing how many mines are around that tile. I'll be using the numbers 1-4 for now, and the way each number is displayed is constant, as each number always has the same text, font, size, and color. The color differs among each of the numbers 1-4, but the number 1, for example, will always be blue, and the number 2 will always be green. I would like to have a static variable for each of the numbers 1-4, so that I can easily set the value of a tile. Here is what I have done:

std::map<std::string, Text> Text::numbers; // statically defined

Text::Text(...) {
    ...
    initNumbers();
}

void Text::initNumbers() {
    numbers["1"] = Text("res/arial.ttf", 20, "1", { 0, 0, 255, 255 });
    numbers["2"] = Text("res/arial.ttf", 20, "2", { 0, 255, 0, 255 });
    numbers["3"] = Text("res/arial.ttf", 20, "3", { 255, 0, 0, 255 });
    numbers["4"] = Text("res/arial.ttf", 20, "4", { 0, 0, 150, 255 });
}

The Text class is just for making text and putting it on the screen. Anyway, I have made an std::map called numbers which I can access as follows: Text::numbers["2"] and that will a return a Text object which will display as the number 2 in this case. I initialize the map by calling initNumbers() in the constructor of the Text class.

In the tile class, there is a member variable Text number, which is used to display the number (1-4) of mines that are around that tile object. When I initialize it to Text::numbers["2"], for example, the number doesn't get displayed onto the screen. When I manually initialize it to Text("res/arial.ttf", 20, "2", { 0, 255, 0, 255 }), the number does get displayed.

I can't figure out what the problem is or how to fix this. Maybe it has to do with when TTF_Init() gets called; i.e. it gets called after std::map<...> numbers gets initialized (which would be bad because the text needs to be initialized after the library gets initialized). Although I essentially call TTF_Init() in the beginning of main and I only start making tile objects afterwards. Any suggestions? Thanks.


Solution

  • initNumbers gets called when a Text object is constructed. If you never create a Text object that uses that constructor, your initialization of numbers will not occur.

    Text::initNumbers should be called from elsewhere, alongside other application initialization code.