有人能为一个只有一个“游戏循环”的程序写一个源代码吗?这个循环会一直循环下去,直到你按下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()
函数内部还是外部实现。我都试过了,两次都失败了。如果你能帮我,那就太好了。
发布于 2010-06-12 17:51:00
尝试过类似这样的东西
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 )。
发布于 2010-06-12 18:03:33
下面是一个完整的工作示例。除了使用帧时间调节之外,您还可以使用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;
}
发布于 2010-06-12 17:49:53
由于您已经在使用SDL,因此可以使用SDL_PollEvent
function运行event loop,检查按键事件是否为ESC。看起来这和mySDL_Event.key.keysym.sym == SDLK_ESCAPE
差不多。
https://stackoverflow.com/questions/3029545
复制