How to blit Score on screen in SDL?

做~自己de王妃 提交于 2019-12-08 14:13:56

问题


I have been working on a Pong clone game. It's almost done, just when I thought everything is perfect. The SDL_ttf.h Library seems to be a pain.

I am going to give a general overview and not the whole code just to make things simple. I have used-

int PlayerScore=0;
int AIScore=0;

Here's the syntax to render text in SDL.

SDL_Surface *TTF_RenderText_Solid(TTF_Font *font, const char *text, SDL_Color fg);

Now, see that const char* text? That's where I need to give my PlayerScore/AIScore there. PlayerScore/AIScore are of integer type but they are supposed to be in const char* type. So after hours of browsing and research I found that there is this sstream library I can use to convert integer to const char*

I declare my surface as imgTxt;

SDL_Surface* imgTxt;
std::stringstream strm;
strm << PlayerScore;

...

imgTxt = TTF_RenderText_Solid( font, strm.str().c_str(), fColor );
SDL_BlitSurface(imgTxt,NULL,screen,null);

Guess what? The conversion is successful. But I faced a different problem, just when I blit the surface. It displays the score as 0000000000000000000000000000 and it keeps on going, after a while the font disappears and nothing happens. I've no idea why this is happening, maybe the string is being appended with the score in every loop? This is the screenshot.

Is there any solution to this as to why this is happening? Any help would be deeply appreciated. Thanks in advance.


回答1:


Without seeing the whole code, I cannot say. It certainly looks like it thought.

Are you creating the sstream every loop?

An alternative would be to use sprintf.

char buffer [50];
sprintf (buffer, "%d", PlayerScore);

and later

imgTxt = TTF_RenderText_Solid( font, buffer, fColor );
SDL_BlitSurface(imgTxt,NULL,screen,null);


来源:https://stackoverflow.com/questions/21282513/how-to-blit-score-on-screen-in-sdl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!