这是一次长久的提交:

1. 应用界面增加了返回主页的按钮
2. 修复了gif渲染内存泄漏的严重bug
3. 将PetDao当中的cJSON API替换为cpp_json,完美通过测试
4. 整合已经实现的各种上层建筑,实现了一个宠物对话基本业务应用,用于样品测试展示用
5. 重构了音频播放类,使其更modern,更加便于移植和拓展
This commit is contained in:
Misaki
2025-10-16 11:36:45 +08:00
parent 801138631e
commit ba5e47bc77
38 changed files with 2487 additions and 2008 deletions
+108 -139
View File
@@ -47,48 +47,43 @@ PetDAO::PetDAO(SDFileManager* fileManager) : fileManager(fileManager) {
}
bool PetDAO::savePet(const std::shared_ptr<PetBase>& pet, const std::string& filename) {
// 转换为JSON
cJSON* json = petToJson(pet);
if (!json) {
try {
// 转换为JSON
cppjson::Json json = petToJson(pet);
// 序列化为字符串
std::string jsonStr = json.dump();
std::string fullPath = std::string(PET_DATA_DIR) + "/" + filename;
// 保存到文件
const bool success = fileManager->writeFileSync(fullPath.c_str(), jsonStr.c_str(), jsonStr.size(), "w");
return success;
} catch (const std::exception& e) {
std::cerr << "Save pet failed: " << e.what() << std::endl;
return false;
}
// 转换为字符串
char* jsonStr = cJSON_PrintUnformatted(json);
std::string fullPath = std::string(PET_DATA_DIR) + "/" + filename;
// 保存到文件
bool success = fileManager->writeFileSync(fullPath.c_str(), jsonStr);
// 清理资源
free(jsonStr);
cJSON_Delete(json);
return success;
}
std::shared_ptr<PetBase> PetDAO::loadPet(const std::string& filename) {
std::string fullPath = std::string(PET_DATA_DIR) + "/" + filename;
try {
std::string fullPath = std::string(PET_DATA_DIR) + "/" + filename;
// 读取文件内容
std::string content = fileManager->readFileSync(fullPath.c_str());
if (content.empty()) {
// 读取文件内容
std::string content = fileManager->readFileSync(fullPath.c_str());
if (content.empty()) {
return nullptr;
}
// 解析JSON
cppjson::Json json = cppjson::Json::parse(content);
// 创建宠物对象
return petFromJson(json);
} catch (const std::exception& e) {
std::cerr << "Load pet failed: " << e.what() << std::endl;
return nullptr;
}
// 解析JSON
cJSON* json = cJSON_Parse(content.c_str());
if (!json) {
return nullptr;
}
// 创建宠物对象
auto pet = petFromJson(json);
// 清理资源
cJSON_Delete(json);
return pet;
}
std::vector<std::string> PetDAO::listPetFiles() {
@@ -100,204 +95,178 @@ bool PetDAO::deletePetFile(const std::string& filename) {
return fileManager->rmCommand(fullPath.c_str(), false);
}
cJSON* PetDAO::petToJson(const std::shared_ptr<PetBase>& pet) {
cJSON* json = cJSON_CreateObject();
if (!json) return nullptr;
cppjson::Json PetDAO::petToJson(const std::shared_ptr<PetBase>& pet) {
auto json = cppjson::Json::object();
// 添加基本信息
cJSON_AddStringToObject(json, "name", pet->pet_info.pet_name.c_str());
cJSON_AddNumberToObject(json, "hp", pet->pet_info.pet_hp);
cJSON_AddNumberToObject(json, "density", pet->pet_info.pet_density);
cJSON_AddStringToObject(json, "identity", pet->pet_info.pet_identity.c_str());
json.set("name", cppjson::Json(pet->pet_info.pet_name))
.set("hp", cppjson::Json(pet->pet_info.pet_hp))
.set("density", cppjson::Json(pet->pet_info.pet_density))
.set("identity", cppjson::Json(pet->pet_info.pet_identity));
// 添加阶段策略
cJSON* stageJson = stageStrategyToJson(pet->pet_stage_strategy);
if (stageJson) {
cJSON_AddItemToObject(json, "stage_strategy", stageJson);
auto stageJson = stageStrategyToJson(pet->pet_stage_strategy);
if (!stageJson.isNull()) {
json.set("stage_strategy", stageJson);
}
// 添加动作策略
cJSON* actionJson = actionStrategyToJson(pet->pet_action_strategy);
if (actionJson) {
cJSON_AddItemToObject(json, "action_strategy", actionJson);
auto actionJson = actionStrategyToJson(pet->pet_action_strategy);
if (!actionJson.isNull()) {
json.set("action_strategy", actionJson);
}
return json;
}
std::shared_ptr<PetBase> PetDAO::petFromJson(cJSON* json) {
if (!json) return nullptr;
std::shared_ptr<PetBase> PetDAO::petFromJson(const cppjson::Json& json) {
if (json.isNull()) return nullptr;
// 创建宠物基本信息
PetBaseInfo info;
cJSON* nameItem = cJSON_GetObjectItemCaseSensitive(json, "name");
if (cJSON_IsString(nameItem)) {
info.pet_name = nameItem->valuestring;
if (json["name"].isString()) {
info.pet_name = json["name"].asString();
}
cJSON* hpItem = cJSON_GetObjectItemCaseSensitive(json, "hp");
if (cJSON_IsNumber(hpItem)) {
info.pet_hp = hpItem->valueint;
if (json["hp"].isNumber()) {
info.pet_hp = json["hp"].asInt();
}
cJSON* densityItem = cJSON_GetObjectItemCaseSensitive(json, "density");
if (cJSON_IsNumber(densityItem)) {
info.pet_density = densityItem->valueint;
if (json["density"].isNumber()) {
info.pet_density = json["density"].asInt();
}
cJSON* identityItem = cJSON_GetObjectItemCaseSensitive(json, "identity");
if (cJSON_IsString(identityItem)) {
info.pet_identity = identityItem->valuestring;
if (json["identity"].isString()) {
info.pet_identity = json["identity"].asString();
}
// 创建阶段策略
cJSON* stageJson = cJSON_GetObjectItemCaseSensitive(json, "stage_strategy");
auto stageStrategy = stageStrategyFromJson(stageJson);
auto stageStrategy = stageStrategyFromJson(json["stage_strategy"]);
// 创建动作策略
cJSON* actionJson = cJSON_GetObjectItemCaseSensitive(json, "action_strategy");
auto actionStrategy = actionStrategyFromJson(actionJson);
auto actionStrategy = actionStrategyFromJson(json["action_strategy"]);
// 创建宠物对象
return std::make_shared<PetBase>(info, stageStrategy, actionStrategy);
}
cJSON* PetDAO::stageStrategyToJson(const std::shared_ptr<PetStageStrategy>& strategy) {
if (!strategy) return nullptr;
cJSON* json = cJSON_CreateObject();
if (!json) return nullptr;
cppjson::Json PetDAO::stageStrategyToJson(const std::shared_ptr<PetStageStrategy>& strategy) {
if (!strategy) return {};
auto json = cppjson::Json::object();
// 添加当前阶段
cJSON_AddStringToObject(json, "current_stage",
stageTypeToString(strategy->getCurrentStageType()).c_str());
json.set("current_stage", cppjson::Json(stageTypeToString(strategy->getCurrentStageType())));
// 添加阶段模型映射
cJSON* modelMap = cJSON_CreateObject();
auto modelMap = cppjson::Json::object();
for (const auto& pair : strategy->getStageModelMap()) {
cJSON_AddStringToObject(modelMap,
stageTypeToString(pair.first).c_str(),
pair.second.c_str());
modelMap.set(stageTypeToString(pair.first), cppjson::Json(pair.second));
}
cJSON_AddItemToObject(json, "stage_model_map", modelMap);
json.set("stage_model_map", modelMap);
// 添加阶段音频映射
cJSON* audioMap = cJSON_CreateObject();
auto audioMap = cppjson::Json::object();
for (const auto& pair : strategy->getStageAudioMap()) {
cJSON_AddStringToObject(audioMap,
stageTypeToString(pair.first).c_str(),
pair.second.c_str());
audioMap.set(stageTypeToString(pair.first), cppjson::Json(pair.second));
}
cJSON_AddItemToObject(json, "stage_audio_map", audioMap);
json.set("stage_audio_map", audioMap);
return json;
}
std::shared_ptr<PetStageStrategy> PetDAO::stageStrategyFromJson(cJSON* json) {
if (!json) return nullptr;
std::shared_ptr<PetStageStrategy> PetDAO::stageStrategyFromJson(const cppjson::Json& json) {
if (json.isNull()) return nullptr;
auto strategy = std::make_shared<PetStageStrategy>();
// 获取当前阶段
cJSON* currentStageItem = cJSON_GetObjectItemCaseSensitive(json, "current_stage");
if (cJSON_IsString(currentStageItem)) {
strategy->current_stage = stringToStageType(currentStageItem->valuestring);
if (json["current_stage"].isString()) {
strategy->current_stage = stringToStageType(json["current_stage"].asString());
}
// 获取阶段模型映射
cJSON* modelMapItem = cJSON_GetObjectItemCaseSensitive(json, "stage_model_map");
if (cJSON_IsObject(modelMapItem)) {
cJSON* child = modelMapItem->child;
while (child) {
if (cJSON_IsString(child)) {
PetStageType stage = stringToStageType(child->string);
strategy->stage_model_map[stage] = child->valuestring;
auto modelMapJson = json["stage_model_map"];
if (modelMapJson.isObject()) {
for (const auto& item : modelMapJson.items()) {
if (item.second.isString()) {
PetStageType stage = stringToStageType(item.first);
strategy->stage_model_map[stage] = item.second.asString();
}
child = child->next;
}
}
// 获取阶段音频映射
cJSON* audioMapItem = cJSON_GetObjectItemCaseSensitive(json, "stage_audio_map");
if (cJSON_IsObject(audioMapItem)) {
cJSON* child = audioMapItem->child;
while (child) {
if (cJSON_IsString(child)) {
PetStageType stage = stringToStageType(child->string);
strategy->stage_audio_map[stage] = child->valuestring;
auto audioMapJson = json["stage_audio_map"];
if (audioMapJson.isObject()) {
for (const auto& item : audioMapJson.items()) {
if (item.second.isString()) {
PetStageType stage = stringToStageType(item.first);
strategy->stage_audio_map[stage] = item.second.asString();
}
child = child->next;
}
}
return strategy;
}
cJSON* PetDAO::actionStrategyToJson(const std::shared_ptr<PetActionStrategy>& strategy) {
if (!strategy) return nullptr;
cppjson::Json PetDAO::actionStrategyToJson(const std::shared_ptr<PetActionStrategy>& strategy) {
if (!strategy) return {};
cJSON* json = cJSON_CreateObject();
if (!json) return nullptr;
auto json = cppjson::Json::object();
// 添加当前动作
cJSON_AddStringToObject(json, "current_action",
actionTypeToString(strategy->getCurrentActionType()).c_str());
json.set("current_action", cppjson::Json(actionTypeToString(strategy->getCurrentActionType())));
// 添加动作模型映射
cJSON* modelMap = cJSON_CreateObject();
auto modelMap = cppjson::Json::object();
for (const auto& pair : strategy->getActionModelMap()) {
cJSON_AddStringToObject(modelMap,
actionTypeToString(pair.first).c_str(),
pair.second.c_str());
modelMap.set(actionTypeToString(pair.first), cppjson::Json(pair.second));
}
cJSON_AddItemToObject(json, "action_model_map", modelMap);
json.set("action_model_map", modelMap);
// 添加动作音频映射
cJSON* audioMap = cJSON_CreateObject();
auto audioMap = cppjson::Json::object();
for (const auto& pair : strategy->getActionAudioMap()) {
cJSON_AddStringToObject(audioMap,
actionTypeToString(pair.first).c_str(),
pair.second.c_str());
audioMap.set(actionTypeToString(pair.first), cppjson::Json(pair.second));
}
cJSON_AddItemToObject(json, "action_audio_map", audioMap);
json.set("action_audio_map", audioMap);
return json;
}
std::shared_ptr<PetActionStrategy> PetDAO::actionStrategyFromJson(cJSON* json) {
if (!json) return nullptr;
std::shared_ptr<PetActionStrategy> PetDAO::actionStrategyFromJson(const cppjson::Json& json) {
if (json.isNull()) return nullptr;
auto strategy = std::make_shared<PetActionStrategy>();
// 获取当前动作
cJSON* currentActionItem = cJSON_GetObjectItemCaseSensitive(json, "current_action");
if (cJSON_IsString(currentActionItem)) {
strategy->current_action = stringToActionType(currentActionItem->valuestring);
if (json["current_action"].isString()) {
strategy->current_action = stringToActionType(json["current_action"].asString());
}
// 获取动作模型映射
cJSON* modelMapItem = cJSON_GetObjectItemCaseSensitive(json, "action_model_map");
if (cJSON_IsObject(modelMapItem)) {
cJSON* child = modelMapItem->child;
while (child) {
if (cJSON_IsString(child)) {
PetActionType action = stringToActionType(child->string);
strategy->action_model_map[action] = child->valuestring;
auto modelMapJson = json["action_model_map"];
if (modelMapJson.isObject()) {
for (const auto& item : modelMapJson.items()) {
if (item.second.isString()) {
PetActionType action = stringToActionType(item.first);
strategy->action_model_map[action] = item.second.asString();
}
child = child->next;
}
}
// 获取动作音频映射
cJSON* audioMapItem = cJSON_GetObjectItemCaseSensitive(json, "action_audio_map");
if (cJSON_IsObject(audioMapItem)) {
cJSON* child = audioMapItem->child;
while (child) {
if (cJSON_IsString(child)) {
PetActionType action = stringToActionType(child->string);
strategy->action_audio_map[action] = child->valuestring;
auto audioMapJson = json["action_audio_map"];
if (audioMapJson.isObject()) {
for (const auto& item : audioMapJson.items()) {
if (item.second.isString()) {
PetActionType action = stringToActionType(item.first);
strategy->action_audio_map[action] = item.second.asString();
}
child = child->next;
}
}
+16 -17
View File
@@ -5,62 +5,61 @@
#include "PetBaseClass.h"
#include "SDFileManager.h"
#include "cJSON.h"
#include "cpp_json.h"
#include <string>
// 辅助函数:枚举类型与字符串的转换
namespace PetEnumConverter {
// PetStageType 转换
std::string stageTypeToString(PetStageType stage);
PetStageType stringToStageType(const std::string& str);
PetStageType stringToStageType(const std::string &str);
// PetActionType 转换
std::string actionTypeToString(PetActionType action);
PetActionType stringToActionType(const std::string& str);
PetActionType stringToActionType(const std::string &str);
}
// PetDAO 类 - 负责宠物的数据持久化
class PetDAO {
public:
// 构造函数,需要SDFileManager实例
explicit PetDAO(SDFileManager* fileManager);
explicit PetDAO(SDFileManager *fileManager);
// 保存宠物数据到文件
bool savePet(const std::shared_ptr<PetBase>& pet, const std::string& filename);
bool savePet(const std::shared_ptr<PetBase> &pet, const std::string &filename);
// 从文件加载宠物数据
std::shared_ptr<PetBase> loadPet(const std::string& filename);
std::shared_ptr<PetBase> loadPet(const std::string &filename);
// 获取所有保存的宠物文件列表
std::vector<std::string> listPetFiles();
// 删除宠物文件
bool deletePetFile(const std::string& filename);
bool deletePetFile(const std::string &filename);
private:
// 将宠物数据转换为JSON对象
cJSON* petToJson(const std::shared_ptr<PetBase>& pet);
cppjson::Json petToJson(const std::shared_ptr<PetBase> &pet); // 返回 cppjson::Json
// 从JSON对象创建宠物
std::shared_ptr<PetBase> petFromJson(cJSON* json);
std::shared_ptr<PetBase> petFromJson(const cppjson::Json &json); // 参数改为 cppjson::Json
// 将阶段策略转换为JSON对象
cJSON* stageStrategyToJson(const std::shared_ptr<PetStageStrategy>& strategy);
cppjson::Json stageStrategyToJson(const std::shared_ptr<PetStageStrategy> &strategy);
// 从JSON对象创建阶段策略
std::shared_ptr<PetStageStrategy> stageStrategyFromJson(cJSON* json);
std::shared_ptr<PetStageStrategy> stageStrategyFromJson(const cppjson::Json &json);
// 将动作策略转换为JSON对象
cJSON* actionStrategyToJson(const std::shared_ptr<PetActionStrategy>& strategy);
cppjson::Json actionStrategyToJson(const std::shared_ptr<PetActionStrategy> &strategy);
// 从JSON对象创建动作策略
std::shared_ptr<PetActionStrategy> actionStrategyFromJson(cJSON* json);
std::shared_ptr<PetActionStrategy> actionStrategyFromJson(const cppjson::Json &json);
// 文件管理器实例
SDFileManager* fileManager;
SDFileManager *fileManager;
// 宠物数据存储目录
static constexpr const char* PET_DATA_DIR = "/sdcard/pet_data";
static constexpr const char *PET_DATA_DIR = "/sdcard/pet_data";
};
/**
@@ -105,4 +104,4 @@ private:
}
}
}
*/
*/
+14 -11
View File
@@ -3,10 +3,13 @@
//
#pragma once
#include "PetInterface.h"
// 用于回调函数传递回调类型,以区分回调的是宠物动作还是宠物阶段
enum class PetType : uint8_t {Action, Stage};
// 宠物音频播放观察者类,继承自宠物观察者
class PetAudioStrategy : public PetObserver, public std::enable_shared_from_this<PetAudioStrategy> {
public:
using AudioCallback = std::function<void(const std::string&)>;
using AudioCallback = std::function<void(PetType petType, const std::string&)>;
/**
* 构造时候就将“事件→音频”两张表填好
* @param actionAudios 动作→音频
@@ -66,7 +69,7 @@ public:
if (!audio_callback) return;
auto it = action_audio.find(action);
if (it != action_audio.end()) {
audio_callback(it->second); // 播放对应音频
audio_callback(PetType::Action, it->second); // 播放对应音频
}
}
/**
@@ -79,7 +82,7 @@ public:
if (!audio_callback) return;
auto it = stage_audio.find(newStage); // 注意:播“新阶段”的音频
if (it != stage_audio.end()) {
audio_callback(it->second);
audio_callback(PetType::Stage, it->second);
}
}
private:
@@ -95,7 +98,7 @@ private:
// 渲染器观察者类,继承自PetObserver
class PetRendererStrategy : public PetObserver, public std::enable_shared_from_this<PetRendererStrategy> {
public:
using RenderCallback = std::function<void(const std::string&)>;
using RenderCallback = std::function<void(PetType petType, const std::string&)>;
/**
* 构造函数,可以传入动作到模型路径和阶段到模型路径的映射表
* @param actionModels 动作→模型路径映射
@@ -120,7 +123,7 @@ public:
}
~PetRendererStrategy() override {
// 自动取消注册
if (auto subject = pet_subject.lock()) {
if (const auto subject = pet_subject.lock()) {
subject->removeObserver(shared_from_this());
}
}
@@ -148,11 +151,11 @@ public:
* 宠物动作时触发[Observer接口实现]
* @param action 动作类型
*/
void onPetAction(PetActionType action) override {
void onPetAction(const PetActionType action) override {
if (!render_callback) return;
auto it = action_models.find(action);
const auto it = action_models.find(action);
if (it != action_models.end()) {
render_callback(it->second); // 渲染对应动作模型
render_callback(PetType::Action, it->second); // 渲染对应动作模型
}
}
/**
@@ -160,11 +163,11 @@ public:
* @param oldStage 旧阶段
* @param newStage 新阶段
*/
void onPetStageChange(PetStageType oldStage, PetStageType newStage) override {
void onPetStageChange(PetStageType oldStage, const PetStageType newStage) override {
if (!render_callback) return;
auto it = stage_models.find(newStage); // 注意:渲染"新阶段"的模型
const auto it = stage_models.find(newStage); // 注意:渲染"新阶段"的模型,实际上并没有使用到旧阶段,但还是保留,留一手
if (it != stage_models.end()) {
render_callback(it->second);
render_callback(PetType::Stage, it->second);
}
}
/**