C++游戏循环示例

Dav*_*vid 3 c++ sdl game-loop

有人可以为一个只有"游戏循环"的程序编写一个源代码,这个循环只会循环,直到你按下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;

}
Run Code Online (Sandbox Code Playgroud)

我只想让程序打开,直到我按下Esc.我知道循环是如何工作的,我只是不知道我是在main()函数内部实现还是在函数内部实现.我试过了两次,两次都失败了.如果你能帮助我,那就太棒了:P

小智 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;

}
Run Code Online (Sandbox Code Playgroud)