0
\$\begingroup\$

I'm making a game in C using SDL library and I want to display a score. I have 9 photos with numbers from 0-9 and I want to know if I can use them somehow to display score, if my score is 2679 the game should use the photos 2 6 7 and 9 and display them realtime, can this be possible? Or how should I display the score?

\$\endgroup\$
1
  • \$\begingroup\$ Nothing till now..Im trying to understand how to use sdl ttf...Im making the game for a collage project... And I have to use only clean C , not C++..most of the tutorials are in c++ using clasess..damn :D \$\endgroup\$
    – FIREHIVE
    Commented Jan 3, 2017 at 0:16

1 Answer 1

0
\$\begingroup\$

There are a few ways to do this. What I would personally do is to use the SDL_TTF library to load a font and use it to render your score. You also get full text rendering support at the same time, so instead of only rendering the score ("2679") you can add a title to it ("Score: 2679").

If you are set on using your own digit sprites, you need to load the images and split the score to individual digits. My C is a little rusty but something like the following should work for mapping the digits:

SDL_Texture* textures[10];

char filename[16];
for (int i = 0; i < 10; i++)
{
    sprintf(filename, "image_%d.png", i);
    textures[i] = SDL_CreateTextureFromSurface(IMG_Load(filename));
}

The code loads images from the root folder in the format of "image_number.png".

Now all is left is to render the score number:

int score = 2679;

SDL_Rect dest;
dest.x = 500;
dest.y = 0;
dest.w = 16;
dest.h = 24;

while (score)
{
    int digit = score % 10;
    score /= 10;

    // Renders the digit.
    SDL_RenderCopy(renderer, textures[digit], NULL, &dest);

    // Moves so that the next digit will be at the correct position.
    dest.x -= dest.w;
}

The way of iterating over the digits in the number is from this SO answer. The code above iterates over the digits, and renders the corresponding texture to the correct spot, and then moves to the number left to the previous number. You can yourself add some padding there.

As you can perhaps see, the way of manually rendering the digits requires more work and currently only gives you support for some digits (with the idea I've shared). SDL_TTF gives you all this, and more.

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .