feat: read network config from JSON

This commit is contained in:
2025-12-28 16:44:54 +08:00
parent 2d43b73e57
commit 19698996cd
6 changed files with 46 additions and 8 deletions

View File

@@ -80,7 +80,14 @@ struct Viewport {
SDL_FRect dst{};
};
struct NetworkConfig {
int port = 12345;
int maxPlayers = 2;
std::string serverIP = "127.0.0.1";
};
struct Config {
WindowConfig window;
RenderConfig render;
NetworkConfig network;
};

View File

@@ -29,6 +29,20 @@ static void loadRender(const json& j, RenderConfig& render) {
get("logical_height", render.logicalHeight);
}
static void loadNetwork(const json& j, NetworkConfig& network) {
auto get = [&](const char* key, auto& out) {
if (j.contains(key))
j.at(key).get_to(out);
else {
std::cout << "Unkonw key " << key << "\n";
}
};
get("port", network.port);
get("max_players", network.maxPlayers);
get("server_ip", network.serverIP);
}
bool ConfigLoader::load(const std::string& path, Config& config) {
std::ifstream file(path);
@@ -53,7 +67,18 @@ bool ConfigLoader::load(const std::string& path, Config& config) {
if (j.contains("render")) {
loadRender(j["render"], config.render);
}
if (j.contains("network")) {
loadNetwork(j["network"], config.network);
}
std::cout << "load json success!\n";
return true;
}
Config ConfigLoader::load(const std::string& path) {
Config config;
if (!load(path, config)) {
std::cerr << "[ConfigLoader] Failed to load config from " << path << "\n";
}
return config;
}

View File

@@ -6,6 +6,6 @@
class ConfigLoader {
public:
static bool load(const std::string& path, Config& config);
static Config load(const std::string&path);
};