fix(game): 修复俄罗斯方块游戏的SDL资源管理和退出机制

- 添加sdlInitialized标志跟踪SDL初始化状态
- 实现cleanup方法确保窗口和渲染器正确释放
- 使用SDL_PushEvent替代SDL_Quit解决退出冲突
- 修复析构函数中的资源清理逻辑
pull/1/head
韩天峰 4 months ago
parent 9186d04da4
commit 16259f095d
  1. 22
      examples/tetris-sdl/cpp-src/tetris.cc

@ -146,23 +146,33 @@ public:
int board[BOARD_HEIGHT][BOARD_WIDTH]; int board[BOARD_HEIGHT][BOARD_WIDTH];
int score; int score;
bool gameOver; bool gameOver;
bool sdlInitialized;
SDL_Window* window; SDL_Window* window;
SDL_Renderer* renderer; SDL_Renderer* renderer;
TetrisBox() : score(0), gameOver(false), window(nullptr), renderer(nullptr) { TetrisBox() : score(0), gameOver(false), sdlInitialized(false), window(nullptr), renderer(nullptr) {
memset(board, 0, sizeof(board)); memset(board, 0, sizeof(board));
printf("[C++] TetrisBox constructor called\n"); printf("[C++] TetrisBox constructor called\n");
} }
~TetrisBox() { ~TetrisBox() override {
printf("[C++] TetrisBox destructor called\n"); printf("[C++] TetrisBox destructor called\n");
cleanup();
}
void cleanup() {
if (renderer) { if (renderer) {
SDL_DestroyRenderer(renderer); SDL_DestroyRenderer(renderer);
renderer = nullptr;
} }
if (window) { if (window) {
SDL_DestroyWindow(window); SDL_DestroyWindow(window);
window = nullptr;
}
if (sdlInitialized) {
SDL_QuitSubSystem(SDL_INIT_VIDEO);
sdlInitialized = false;
} }
SDL_Quit();
} }
}; };
@ -175,6 +185,7 @@ var php_tetris_new() {
if (SDL_Init(SDL_INIT_VIDEO) < 0) { if (SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("[C++] SDL Init Error: %s\n", SDL_GetError()); printf("[C++] SDL Init Error: %s\n", SDL_GetError());
} else { } else {
box->sdlInitialized = true;
box->window = SDL_CreateWindow( box->window = SDL_CreateWindow(
"俄罗斯方块 - PHP版", "俄罗斯方块 - PHP版",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
@ -333,7 +344,10 @@ void php_tetris_handle_key(var box, Int keyCode) {
// Post quit message // Post quit message
void php_tetris_post_quit(Int exitCode) { void php_tetris_post_quit(Int exitCode) {
SDL_Quit(); SDL_Event event;
memset(&event, 0, sizeof(event));
event.type = SDL_QUIT;
SDL_PushEvent(&event);
} }
// Show message box with UTF-8 support // Show message box with UTF-8 support

Loading…
Cancel
Save