Optimized the structure

This commit is contained in:
2025-11-23 15:13:28 +08:00
parent 5100aa799f
commit ff2ddc6fd4
7 changed files with 28 additions and 29 deletions

View File

@@ -2,10 +2,7 @@
#include "Game.h"
Game::Game(int g_width, int g_heith)
: Width(g_width),
Height(g_heith),
m_render(std::make_unique<Renderer>())
Game::Game()
{
}
@@ -22,9 +19,7 @@ void Game::cleanup() {
bool Game::initialize() {
if (!m_render->initialize()) {
return false;
}
@@ -35,6 +30,4 @@ bool Game::initialize() {
}
void Game::render() {
m_render->Renderhello();
}

View File

@@ -3,22 +3,21 @@
#include <SDL3/SDL.h>
#include <memory>
//#include "Board.h"
#include "ui/Render.h"
class Game {
private:
std::unique_ptr<Renderer> m_render;
int Width;
int Height;
public:
Game(int g_width, int g_heith);
Game();
~Game();
void cleanup();
bool initialize();
void render();
};

View File

@@ -2,11 +2,12 @@
#include <SDL3/SDL.h>
#include <SDL3/SDL_main.h>
#include "core/Game.h"
#include "ui/Render.h"
//使用SDL3的appstate进行隔离避免全局变量
struct AppState {
std::unique_ptr<Game> game;
std::unique_ptr<Game> g_game;
std::unique_ptr<Renderer> g_renderer;
};
@@ -18,25 +19,27 @@ static const int HEIGHT = 900;
// 1. 应用程序初始化回调
SDL_AppResult SDL_AppInit(void **appstate, int argc, char *argv[]) {
// 设置应用元数据[8](@ref)
SDL_SetAppMetadata("孢子棋", "1.0.0", "com.zhenyan121.sporechess");
SDL_SetAppMetadata("孢子棋", "1.0.0", "com.zhenyan121.sporebgconid");
// 初始化SDL视频子系统[6,7](@ref)
if (!SDL_Init(SDL_INIT_VIDEO)) {
SDL_Log("SDL初始化失败: %s", SDL_GetError());
return SDL_APP_FAILURE;
}
// 创建游戏实例
auto state = new AppState();
state->game = std::make_unique<Game>(WIDTH, HEIGHT);
state->g_game = std::make_unique<Game>();
state->g_renderer = std::make_unique<Renderer>(WIDTH, HEIGHT);
if (!state->game->initialize()) {
if (!state->g_game->initialize() || !state->g_renderer->initialize()) {
SDL_Log("游戏初始化失败!");
delete state;
return SDL_APP_FAILURE;
}
*appstate = state;
return SDL_APP_CONTINUE;
}
@@ -55,12 +58,12 @@ SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event) {
// 3. 主循环迭代回调(每帧调用)
SDL_AppResult SDL_AppIterate(void *appstate) {
auto s = static_cast<AppState*>(appstate);
if (s->game) { //防止空指针
if (s) { //防止空指针
// 更新游戏逻辑
// 渲染帧
s->game->render();
s->g_renderer->render();
}
return SDL_APP_CONTINUE;
}

View File

@@ -50,4 +50,9 @@ void Renderer::Renderhello() {
SDL_RenderClear(m_renderer);
SDL_SetRenderDrawColor(m_renderer, 255, 255, 255, 255);
SDL_RenderPresent(m_renderer);
}
void Renderer::render() {
Renderhello();
}

View File

@@ -13,6 +13,7 @@ public:
Renderer(int WIDTH, int HEIGHT);
Renderer();
~Renderer();
void render();
bool initialize();
void Renderhello();
};