SDL2 事件驱动

参考:https://blog.csdn.net/qq_31024569/article/details/78118007

保持程序在运行状态的循环叫做主循环(main loop),也叫游戏循环(game loop)。它是所有游戏的核心部分。

主循环的顶部是事件循环,它的作用就是持续处理事件队列直到它为空。

当你按下一个按键,或者触摸触控屏,一个事件就同时被放进了事件队列中。

转自原作者

事件队列会立刻把它们(事件)按事件发生顺序存储起来,等你来处理它们。当你想要了解发生什么事件以便处理这些事件时,你可以通过调用SDL_PollEvent()来轮询事件队列以获取最新的事件。

SDL_PollEvent()的作用就是从事件队列中获取最先的事件并将从事件中获取的数据放进我们传递的参数中

转自原作者

SDL_PollEvent()会一直从队列中获取事件直到队列为空为止。当队列为空,SDL_PollEvent()会返回0。

如果获取到的事件为SDL_QUIT(用户点击窗口上的关闭按钮’X’),我们就将标志变量设定为true以退出程序。

 

全部程序:


#include <SDL2/SDL.h>
#include <stdio.h>

//Screen dimension constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

//Starts up SDL and creates window
bool init();

//Loads media
bool loadMedia();

//Frees media and shuts down SDL
void close();

//The window we'll be rendering to
SDL_Window* gWindow = NULL;
 
//The surface contained by the window
SDL_Surface* gScreenSurface = NULL;

//The image we will load and show on the screen
SDL_Surface* gXOut = NULL;

bool init()
{
 //Initialization flag
 bool success = true;

 //Initialize SDL
 if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
 {
  printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
  success = false;
 }
 else
 {
  //Create window
  gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
  if( gWindow == NULL )
  {
   printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
   success = false;
  }
  else
  {
   //Get window surface
   gScreenSurface = SDL_GetWindowSurface( gWindow );
  }
 }

 return success;
}

bool loadMedia()
{
 //Loading success flag
 bool success = true;

 //Load splash image
 gXOut = SDL_LoadBMP( "x.bmp" );
 if( gXOut == NULL )
 {
  printf( "Unable to load image %s! SDL Error: %s\n", "x.bmp", SDL_GetError() );
  success = false;
 }

 return success;
}

void close()
{
 //Deallocate surface
 SDL_FreeSurface( gXOut );
 gXOut = NULL;

 //Destroy window
 SDL_DestroyWindow( gWindow );
 gWindow = NULL;

 //Quit SDL subsystems
 SDL_Quit();
}

int main( int argc, char* args[] )
{
 //Start up SDL and create window
 if( !init() )
 {
  printf( "Failed to initialize!\n" );
 }
 else
 {
  //Load media
  if( !loadMedia() )
  {
   printf( "Failed to load media!\n" );
  }
  else
  {   
   //Main loop flag
   bool quit = false;

   //Event handler
   SDL_Event e;

   //While application is running
   while( !quit )
   {
    //Handle events on queue
    while( SDL_PollEvent( &e ) != 0 )
    {
     //User requests quit
     if( e.type == SDL_QUIT )
     {
      quit = true;
     }
    }

    //Apply the image
    SDL_BlitSurface( gXOut, NULL, gScreenSurface, NULL );
   
    //Update the surface
    SDL_UpdateWindowSurface( gWindow );
   }
  }
 }

 //Free resources and close SDL
 close();

 return 0;
}

 

posted @ 2019-05-07 17:10  HenryLiuY  阅读(298)  评论(0)    收藏  举报