有人可以为一个只有“游戏循环”的程序编写一个源代码,这个循环只会循环,直到你按下Esc,程序会显示一个基本的图像。这是我现在拥有的源代码,但我必须使用SDL_Delay(2000);
使程序保持活动状态2秒,在此期间程序被冻结。
#include "SDL.h"
int main(int argc, char* args[]) {
SDL_Surface* hello = NULL;
SDL_Surface* screen = NULL;
SDL_Init(SDL_INIT_EVERYTHING);
screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
hello = SDL_LoadBMP("hello.bmp");
SDL_BlitSurface(hello, NULL, screen, NULL);
SDL_Flip(screen);
SDL_Delay(2000);
SDL_FreeSurface(hello);
SDL_Quit();
return 0;
}
我只想让程序打开,直到我按下Esc。我知道循环是如何工作的,我只是不知道我是在main()
函数内部还是在函数之外实现的。我试过了两次,两次都失败了。如果你能帮助我,那就太棒了:P
答案 0 :(得分:5)
这是一个完整而有效的例子。您也可以使用SDL_WaitEvent。
,而不是使用帧时间规则#include <SDL/SDL.h>
#include <cstdlib>
#include <iostream>
using namespace std;
const Uint32 fps = 40;
const Uint32 minframetime = 1000 / fps;
int main (int argc, char *argv[])
{
if (SDL_Init (SDL_INIT_VIDEO) != 0)
{
cout << "Error initializing SDL: " << SDL_GetError () << endl;
return 1;
}
atexit (&SDL_Quit);
SDL_Surface *screen = SDL_SetVideoMode (640, 480, 32, SDL_DOUBLEBUF);
if (screen == NULL)
{
cout << "Error setting video mode: " << SDL_GetError () << endl;
return 1;
}
SDL_Surface *pic = SDL_LoadBMP ("hello.bmp");
if (pic == NULL)
{
cout << "Error loading image: " << SDL_GetError () << endl;
return 1;
}
bool running = true;
SDL_Event event;
Uint32 frametime;
while (running)
{
frametime = SDL_GetTicks ();
while (SDL_PollEvent (&event) != 0)
{
switch (event.type)
{
case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_ESCAPE)
running = false;
break;
}
}
if (SDL_GetTicks () - frametime < minframetime)
SDL_Delay (minframetime - (SDL_GetTicks () - frametime));
}
SDL_BlitSurface (pic, NULL, screen, NULL);
SDL_Flip (screen);
SDL_FreeSurface (pic);
SDL_Delay (2000);
return 0;
}
答案 1 :(得分:2)
由于您已经在使用SDL,因此可以使用SDL_PollEvent
function运行event loop,检查按键事件是否为ESC。看起来这将是mySDL_Event.key.keysym.sym == SDLK_ESCAPE
。
答案 2 :(得分:2)
尝试过像
这样的事情 SDL_Event e;
while( SDL_WaitEvent(&e) )
{
if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE) break;
}
?你可以在那里找到很多教程和例子;只需fast-search example。
添加了注释:WaitEvent“冻结”程序,因此您无法执行任何操作..您只需等待;可能需要其他等待技术(在初始化计时器后再次使用PollEvent或WaitEvent)。
答案 3 :(得分:-3)
#include <conio.h>
...
while (!kbhit())
{
hello = SDL_LoadBMP("hello.bmp");
SDL_BlitSurface(hello, NULL, screen, NULL);
SDL_Flip(screen);
}
...