From 16259f095d89f07ff26e1340c5aedb86e1c821d7 Mon Sep 17 00:00:00 2001 From: tianfenghan Date: Fri, 8 May 2026 20:39:23 +0800 Subject: [PATCH] =?UTF-8?q?fix(game):=20=E4=BF=AE=E5=A4=8D=E4=BF=84?= =?UTF-8?q?=E7=BD=97=E6=96=AF=E6=96=B9=E5=9D=97=E6=B8=B8=E6=88=8F=E7=9A=84?= =?UTF-8?q?SDL=E8=B5=84=E6=BA=90=E7=AE=A1=E7=90=86=E5=92=8C=E9=80=80?= =?UTF-8?q?=E5=87=BA=E6=9C=BA=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加sdlInitialized标志跟踪SDL初始化状态 - 实现cleanup方法确保窗口和渲染器正确释放 - 使用SDL_PushEvent替代SDL_Quit解决退出冲突 - 修复析构函数中的资源清理逻辑 --- examples/tetris-sdl/cpp-src/tetris.cc | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/examples/tetris-sdl/cpp-src/tetris.cc b/examples/tetris-sdl/cpp-src/tetris.cc index 39427b00..be98e0ed 100644 --- a/examples/tetris-sdl/cpp-src/tetris.cc +++ b/examples/tetris-sdl/cpp-src/tetris.cc @@ -146,23 +146,33 @@ public: int board[BOARD_HEIGHT][BOARD_WIDTH]; int score; bool gameOver; + bool sdlInitialized; SDL_Window* window; 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)); printf("[C++] TetrisBox constructor called\n"); } - ~TetrisBox() { + ~TetrisBox() override { printf("[C++] TetrisBox destructor called\n"); + cleanup(); + } + + void cleanup() { if (renderer) { SDL_DestroyRenderer(renderer); + renderer = nullptr; } if (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) { printf("[C++] SDL Init Error: %s\n", SDL_GetError()); } else { + box->sdlInitialized = true; box->window = SDL_CreateWindow( "俄罗斯方块 - PHP版", SDL_WINDOWPOS_UNDEFINED, @@ -333,7 +344,10 @@ void php_tetris_handle_key(var box, Int keyCode) { // Post quit message 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