我正在使用SDL 1.2库开展一个小sokoban游戏。这个程序最有趣的可能性是在地图上移动一个角色。但是,我面临一些奇怪的减速问题,我找不到原因。
我简化了代码,因此它不会太长。
这是让角色移动的循环:
以下对应于游戏的块(地图的每个案例)及其在屏幕上的位置。例如,bloc[3]
是指向与第4个地图相对应的曲面的指针。
SDL_Surface *bloc[256] = {NULL};
SDL_Rect pos_bloc[256];
while (on == 1)
{
SDL_WaitEvent(&event);
switch (event.type)
{
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
case SDLK_ESCAPE:
on = game_menu(screen);
refresh_screen(screen, bloc, pos_bloc, zone);
break;
case SDLK_UP:
if (zone[m - 16] == ' ') // m is the position of the character on
// the map. As the map is 16 blocks large,
// and the position in the map is registered
// in a string, m - 16 means: 1 case up.
// m + 16 means: 1 case down.
m = swap_2blocs(screen, bloc, pos_bloc, zone, m, -16, "up.bmp");
break;
case SDLK_DOWN:
if (zone[m + 16] == ' ')
m = swap_2blocs(screen, bloc, pos_bloc, zone, m, 16, "down.bmp");
break;
default:;
}
default:;
}
SDL_Flip(screen);
}
无论何时按下向上或向下键,它都会调用一个交换2个表面的函数:它释放所有相关的SDL_Surface
指针,然后为另一个表面重新分配一些内存:
int swap_2blocs(SDL_Surface *screen, SDL_Surface *bloc[256], SDL_Rect pos_bloc[256], char zone[257], int m, int n, char *character)
{
SDL_FreeSurface(bloc[m]); // The surface pointed to by `bloc[m]` is freed
bloc[m] = SDL_LoadBMP("empty_space.bmp"); // `bloc[m]` now points to another surface
SDL_BlitSurface(bloc[m], NULL, screen, &pos_bloc[m]);
zone[m] = ' '; // zone is the string that contains informations about each map block
// ' ' stands for an empty space, 'M' stands for the character
m += n;
zone[m] = 'M';
SDL_FreeSurface(bloc[m]); // The surface pointed to by `bloc[m]` is freed
bloc[m] = SDL_LoadBMP(character); // `bloc[m]` now points to another surface
SDL_BlitSurface(bloc[m], NULL, screen, &pos_bloc[m]);
return m;
}
有几件事要知道:
bloc
中包含的每个指针所指向的所有表面)并开始新游戏并不会重置速度。游戏。要重置它,必须退出程序然后重新启动。我想了解这种神秘的行为:它来自哪里?发生了什么事?