美文网首页
SDL 教程 03 : 事件驱动编程

SDL 教程 03 : 事件驱动编程

作者: wjundong | 来源:发表于2020-02-18 23:30 被阅读0次

示例代码

#include <SDL2/SDL.h>

const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;


int main(int argc, char const *argv[])
{

    SDL_Window *window = NULL;
    SDL_Surface *screenSurface;

    // 初始化 SDL, 创建窗口
    if(SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
        exit(-1);
    }
    else
    {
        window = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, 
            SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
        if(window == NULL)
        {
            printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
            exit(-1);
        }
        else
        {
            screenSurface = SDL_GetWindowSurface( window );
        }
    }

    // SDL_Event 是一些类似按键、鼠标移动、快捷键按下的事件
    SDL_Event event;
    bool quit = false;
    int index = 0;

    while (quit == false)
    {
        /** 事件队列将按照事件发生的顺序存储它们,等待你处理它们。
         * 当你想要找出发生了什么事件以便可以处理它们时,可以通过调用
         * SDL_PollEvent 来轮询事件队列以, 将事件中的数据放入我们传递给函数的 SDL_Event 中 
         * 
         * SDL_PollEvent 将不断从队列中删除事件,直到它为空。当队列为空时,
         * SDL_PollEvent 将返回0。因此,这段代码的作用是不断轮询, 将事件从队列中取出
         * 直到它队列为空。如果事件队列中的事件是SDL_QUIT事件(当用户X退出窗口时的事件)
         * 我们将QUIT标志设置为TRUE,这样我们就可以退出应用程序
         */ 
        
        while(SDL_PollEvent(&event) != 0)
        {
            printf("event index %d\n", index++);
            
            if(event.type == SDL_QUIT)
            {
                quit = true;
            }
        }
        // 充填颜色
        SDL_FillRect( screenSurface, NULL, SDL_MapRGB( screenSurface->format, 0x00, 0xE0, 0xFF ) );
        SDL_UpdateWindowSurface( window );
    }

    SDL_DestroyWindow( window );
    SDL_Quit();
    return 0;
}

运行结果


运行结果.png

相关文章

网友评论

      本文标题:SDL 教程 03 : 事件驱动编程

      本文链接:https://www.haomeiwen.com/subject/bscofhtx.html