C ++ game example

Can someone write a source for a program that simply has a “game loop” that just continues the loop until you press Esc and the program displays the main image. This is the source that I have right now, but I have to use SDL_Delay(2000);it to save the program for 2 seconds, during which the program was frozen.

#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;

}

I just want the program to open until I press Esc. I know how the loop works, I just don’t know if I implement inside the function main()or outside of it. I tried both, and both times it failed. If you could help me, that would be great: P

+3
source share
4

-

  SDL_Event e;
  while( SDL_WaitEvent(&e) )
  {
    if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE) break;
  }

? ; .

​​: WaitEvent "" , . ; (, PollEvent WaitEvent ).

+2

. 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;

}
+5

SDL, SDL_PollEvent , , ESC. , mySDL_Event.key.keysym.sym == SDLK_ESCAPE.

+2
source
#include <conio.h>

...

while (!kbhit())
{
    hello = SDL_LoadBMP("hello.bmp");

    SDL_BlitSurface(hello, NULL, screen, NULL);

    SDL_Flip(screen);
}

...
-3
source

Source: https://habr.com/ru/post/1749754/


All Articles