读书人

调整sdl的定时器及事件机制的样例

发布时间: 2012-09-28 00:03:35 作者: rapoo

整合sdl的定时器及事件机制的样例
SDL(Simple DirectMedia Layer)是一套开放源代码的跨平台多媒体开发库.有利于多媒体及游戏的开发,具体详见维基百科:http://zh.wikipedia.org/wiki/SDL
此样例是对sdl事件机制和定时器的简单整合, 自ffmpeg的tutorial04.c了解的

你需要先安装sdl
编译,生成: gcc -o testevent2 testevent2.c `sdl-config --cflags --libs`

#include "SDL.h"#include <stdio.h>#include <time.h>#define FF_0_EVENT   (SDL_USEREVENT)#define FF_1_EVENT (SDL_USEREVENT + 1)#define FF_2_EVENT (SDL_USEREVENT + 2)#define FF_3_EVENT (SDL_USEREVENT + 3)#define FF_4_EVENT (SDL_USEREVENT + 4)#define random(x) (rand()%x)static Uint32 sdl_refresh_timer_cb(Uint32 interval, void *opaque) {SDL_Event event;srand((int)time(0));int ffrand;ffrand = random(5);printf("ffrand = %d \n", ffrand);switch (ffrand) {case 0:    event.type = FF_0_EVENT;break;case 1:event.type = FF_1_EVENT;break;case 2:event.type = FF_2_EVENT;break;case 3:event.type = FF_3_EVENT;break;case 4:event.type = FF_4_EVENT;break;default:break;}SDL_PushEvent(&event);return interval; /* 0 means stop timer */}static void schedule_refresh(int delay) {SDL_AddTimer(delay, sdl_refresh_timer_cb, NULL);}int main(int argc, char *argv[]) {SDL_Event       event;if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());exit(1);}schedule_refresh(1000);while(1) {SDL_WaitEvent(&event);switch(event.type) {case FF_0_EVENT:printf("0 \n");break;case FF_1_EVENT:printf("1 \n");break;case FF_2_EVENT:printf("2 \n");break;case FF_3_EVENT:printf("3 \n");SDL_Quit();return 0;break;case FF_4_EVENT:printf("4 \n");break;default:break;}}return 0;}


notice:
1, SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)
sdl初始化一定要全部初始化,如果仅仅初始化SDL_INIT_TIMER, 事件机制将不起任何作用
因为sdl_event的有mouse,key等界面元素

读书人网 >移动开发

热点推荐