use gameapp to control game

This commit is contained in:
2025-12-06 10:36:03 +08:00
parent 392fde06e9
commit f4131698b0
3 changed files with 19 additions and 27 deletions

View File

@@ -6,9 +6,9 @@ GameApplication::GameApplication() {
}
void GameApplication::initialize() {
bool GameApplication::initialize() {
m_gameSession->initialize();
return true;
}
SDL_AppResult GameApplication::handleInputEvent(SDL_Event* event) {

View File

@@ -1,6 +1,6 @@
#pragma once
#include "core/GameSession.h"
#include "game/GameSession.h"
#include "input/InputManager.h"
#include "utils/Config.h"
@@ -17,7 +17,7 @@ private:
public:
GameApplication();
~GameApplication();
void initialize();
bool initialize();
SDL_AppResult handleInputEvent(SDL_Event* event);
void run();

View File

@@ -1,16 +1,10 @@
#define SDL_MAIN_USE_CALLBACKS 1 // 启用回调函数模式
#include <SDL3/SDL.h>
#include <SDL3/SDL_main.h>
#include "core/Game.h"
#include "ui/Render.h"
#include "input/InputManager.h"
#include "core/GameApplication.h"
//使用SDL3的appstate进行隔离避免全局变量
struct AppState {
std::unique_ptr<Game> g_game;
std::unique_ptr<Renderer> g_renderer;
std::unique_ptr<InputManager> g_input;
};
@@ -30,45 +24,43 @@ SDL_AppResult SDL_AppInit(void **appstate, int argc, char *argv[]) {
}
// 创建游戏实例
auto state = new AppState();
state->g_game = std::make_unique<Game>();
state->g_renderer = std::make_unique<Renderer>(WIDTH, HEIGHT);
state->g_input = std::make_unique<InputManager>();
auto gameapp = new GameApplication();
if (!state->g_game->initialize() || !state->g_renderer->initialize()) {
if (!gameapp->initialize()) {
SDL_Log("游戏初始化失败!");
delete state;
delete gameapp;
return SDL_APP_FAILURE;
}
*appstate = state;
*appstate = gameapp;
return SDL_APP_CONTINUE;
}
// 2. 事件处理回调
SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event) {
auto s = static_cast<AppState*>(appstate);
auto gameapp = static_cast<GameApplication*>(appstate);
auto result = s->g_input->handleInputEvent(event, s->g_renderer.get(), s->g_game.get());
auto result = gameapp->handleInputEvent(event);
return result;
}
// 3. 主循环迭代回调(每帧调用)
SDL_AppResult SDL_AppIterate(void *appstate) {
auto s = static_cast<AppState*>(appstate);
if (s) { //防止空指针
// 更新游戏逻辑
auto gameapp = static_cast<GameApplication*>(appstate);
if (gameapp) { //防止空指针
gameapp->run();
// 渲染帧
s->g_renderer->render();
}
return SDL_APP_CONTINUE;
}
// 4. 应用退出回调(清理资源)
void SDL_AppQuit(void *appstate, SDL_AppResult result) {
delete static_cast<AppState*>(appstate);
delete static_cast<GameApplication*>(appstate);
SDL_Quit();
}