gpt4 book ai didi

C++ 游戏循环示例

转载 作者:太空狗 更新时间:2023-10-29 20:31:59 26 4
gpt4 key购买 nike

有人可以为一个只有“游戏循环”的程序编写源代码吗,它会一直循环直到您按 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

最佳答案

这是一个完整的工作示例。除了使用帧时间规则,您还可以使用 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;

}

关于C++ 游戏循环示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3029545/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com