为什么游戏窗口会在特定时间后关闭?

时间:2013-09-11 00:02:10

标签: c++ sdl-2

为什么SDL Game Library创建的窗口会在特定时间后自动关闭 我知道原因是SDL_Delay()函数,但如果没有使用该函数,游戏将出现运行时错误。

如何在不显示特定时间段的情况下创建一个连续工作的窗口?

我的代码(最简单的代码):

SDL_Window *window;
SDL_Renderer *render;

int main(int argc, char* args[]){

   if(SDL_Init(SDL_INIT_EVERYTHING) >= 0){
      window = SDL_CreateWindow("Simple game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN);
      if(window != 0){
         render = SDL_CreateRenderer(window, -1, 0);
      }

   }else{
      return 1;
   }

   SDL_SetRenderDrawColor(render, 0, 0, 0, 255);
   SDL_RenderClear(render);
   SDL_RenderPresent(render);

   SDL_Delay(3000);     
   SDL_Quit();

   return 0
}

1 个答案:

答案 0 :(得分:2)

您需要永久循环并调用SDL更新屏幕功能。阅读此处的LazyFoo教程:http://lazyfoo.net/SDL_tutorials

或者这是一个简短的代码,可以帮助您入门:

#include <iostream>
#include "SDL/SDL.h"                    // basic SDL
#include <string>

const int       SCREEN_WIDTH    = 640;
const int       SCREEN_HEIGHT   = 480;
const int       SCREEN_BBP      = 32;   // bits per-pixel

SDL_Surface*    screen          = NULL; // display screen 
SDL_Event       event;                  // grab events


using namespace std;

bool init() {

    // initialize SDL
    if(SDL_Init( SDL_INIT_EVERYTHING ) == -1)
        return false;

    //the screen image
    screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 
                              SCREEN_BBP, SDL_SWSURFACE );
    if(!screen) {
        cout << "error creating screen" << endl;
        return false;
    }
    //Set the window caption 
    SDL_WM_SetCaption("Event Test", NULL );

    return true;
}

int main(int argc, char* argv[]) 
{   
    try
    {
        // make sure the program waits for a quit
        bool quit = false;

        cout << "Starting SDL..." << endl; 

        // Start SDL 
        if(!init()) {
            cout << "initialize error" << endl;
            return false;
        }

        // main loop
        while( quit == false )  
        {
            if (SDL_PollEvent(&event))  
            {                       
                // The x button click
                if(event.type == SDL_QUIT)  
                {
                    //quit the program
                    quit = true;
                }

            }

            // Fill the screen white 
            SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( 
                screen->format, 0xFF, 0xFF, 0xFF ) );


            //Update screen
            if(SDL_Flip(screen) == -1)
                return -1;
        }
    }
    catch (exception& e)
    {
        cerr << "exception caught: " << e.what() << endl;
        return -1;
    }

    return 0;
}