尝试在C ++

时间:2018-10-02 15:59:19

标签: c++ sdl-2 sdl-ttf

这是我的.cpp文件:

#include  <iostream>
#include  <SDL2/SDL.h>
#include  <SDL2/SDL_ttf.h>

bool runningOnEmpty = false;
const char* title;
int xpos, ypos, width, height;
bool fullscreen = false;
SDL_Window *window;
SDL_Renderer *renderer;

void init(){
  int flags = 0;
  if(fullscreen){
    flags = SDL_WINDOW_FULLSCREEN;
  }

  if(!SDL_Init(SDL_INIT_EVERYTHING)){
    std::cout << "Sdl initialised!!\n";

    window = SDL_CreateWindow(title, xpos, ypos, width, height, flags);
    if(window){
      std::cout << "window created!!\n";
    }

    renderer = SDL_CreateRenderer(window, -1, 0);
    if(renderer){
      std::cout << "renderer created!!\n";

      SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    }

    runningOnEmpty = true;
  } else {
    runningOnEmpty = false;
  }
  if(TTF_Init()==-1) {
    std::cout << "cannot init TTF: " << TTF_GetError() << "\n";
  } else {
    std::cout << "TTF initialized!" << "\n";
  }
}

void render(){
  SDL_RenderClear(renderer);
  TTF_Font* rFont = TTF_OpenFont("./fonts/roboto.ttf", 20);
  if(!rFont){
    std::cout << "Cannot open font: " << TTF_GetError() << "\n";
  }
  SDL_Color White = {0, 0, 0};
  SDL_Surface* surfaceMessage = TTF_RenderText_Solid(rFont, "Score: ", White);

  if(surfaceMessage == NULL)
    std::cout << "Cannot make surface!" << SDL_GetError() << "\n";

  SDL_Texture* Message = SDL_CreateTextureFromSurface(renderer, surfaceMessage);

  SDL_Rect mr;
  mr.x = 50, mr.y = 50, mr.w = 100, mr.h = 100;

  if(Message = NULL)
    std::cout << "Cannot make texture!" << SDL_GetError() << "\n";

  if(SDL_RenderCopy(renderer, Message, NULL, &mr))
    std::cout << "Cannot render text!" << SDL_GetError() << "\n";

  SDL_FreeSurface(surfaceMessage);
  SDL_RenderPresent(renderer);
}

void clean(){
  SDL_DestroyWindow(window);
  SDL_DestroyRenderer(renderer);
  SDL_Quit();
  std::cout << "Game cleaned!\n";
}

void handleEvents(){
  SDL_Event event;
  SDL_PollEvent(&event);
  switch(event.type){
  case SDL_QUIT:
    runningOnEmpty = false;
    break;

  default:
    break;
  }
}

int main(){
  title = "Test";
  xpos  = SDL_WINDOWPOS_CENTERED;
  ypos  = SDL_WINDOWPOS_CENTERED;

  width = 800, height = 900;
  fullscreen = false;

  init();
  render();

  while(runningOnEmpty){
    handleEvents();
  }

  clean();

  return 0;
}

它编译时没有错误,当我运行该可执行文件时,它会呈现一个白色的窗口,上面没有文本(即使它应该有一些文本)。

当我尝试使用SDL_RenderCopy时出现错误,并且正如我使用SDL_Error()所确认的那样,显然纹理是无效的,即使我在使用它之前对其进行了检查。

这是我在运行代码时在控制台中得到的确切内容:

Sdl initialised!!
window created!!
renderer created!!
TTF initialized!
Cannot render text!Invalid texture
Game cleaned!

1 个答案:

答案 0 :(得分:5)

if(Message = NULL)是一个赋值,而不是比较,因此您先前的Message值将丢失,之后为NULL,该结果将用作逻辑值({{1 }} == NULL == 0。启用编译器警告应会产生一条消息,指出该特定问题,例如false代表gcc给予

-Wall

要比较值,请使用warning: suggest parentheses around assignment used as truth value [-Wparentheses] if(Message = NULL) 运算符。

如果没有DestroyTexture,纹理也会超出范围,这显然是资源泄漏。