TaskManager任务缓存处理,完善保险期间,读取失败走本地缓存方法

This commit is contained in:
YiHan0621
2025-09-09 10:55:14 +08:00
parent f550a87d81
commit 601ec86256

View File

@@ -18,6 +18,7 @@ namespace TcgEngine.Gameplay
[Header("Player Data")]
public List<PlayerTask> playerTasks = new List<PlayerTask>();
public bool isClearPlayerTasks = false;
public long lastDailyTaskAssigned = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
public int maxTasks = 5; // 玩家最多持有任务数
@@ -30,6 +31,9 @@ namespace TcgEngine.Gameplay
private GameClient gameClient;
public string userID;
// 任务缓存处
public Dictionary<string,TaskData> taskConfigs = new Dictionary<string,TaskData>();
private void Awake()
{
@@ -130,7 +134,6 @@ namespace TcgEngine.Gameplay
// 从服务器API获取任务配置
string url = ApiClient.ServerURL + "/api/tasks";
WebResponse res = await ApiClient.Get().SendGetRequest(url);
Debug.Log($"<color=red>LoadTasksFromServer:{url}</color>");
Debug.LogError("从服务器API获取任务配置" + res.data + res.status);
Debug.LogError(res.success);
if (res.success)
@@ -138,14 +141,22 @@ namespace TcgEngine.Gameplay
// 解析任务配置数据
try
{
TaskDataResponse[] taskResponses = ApiTool.JsonToObject<TaskDataResponse[]>(res.data);
Debug.Log("<color=red>Loaded </color>" + taskResponses.Length + " tasks from server");
TaskDataResponse[] taskResponses = ApiTool.JsonToArray<TaskDataResponse>(res.data);
// 在实际项目中这里应该将服务器数据转换为TaskData对象并存储在内存中
// 供后续使用而不是每次都从Resources加载
foreach (var item in taskResponses)
{
Debug.Log($"<color=pink>{item.id}</color>");
Debug.Log($"缓存ID处<color=pink>{item.id}</color>");
taskConfigs[item.id] =
CreateFromResponse(item);
}
Debug.Log("共储存:" + taskConfigs.Count + "条信息");
foreach (var kvp in taskConfigs)
{
TaskData task = kvp.Value;
Debug.Log($"分别为 <color=red>{task.id}</color>");
}
}
catch (Exception e)
@@ -156,12 +167,43 @@ namespace TcgEngine.Gameplay
else
{
Debug.LogWarning("Failed to load tasks from server: " + res.error);
// 如果无法从服务器加载则使用本地Resources作为后备
TaskData[] localTasks = Resources.LoadAll<TaskData>("Tasks");
Debug.Log("Loaded " + localTasks.Length + " tasks from local resources as fallback");
}
}
// 如果无法从服务器加载则使用本地Resources作为后备
TaskData[] localTasks = Resources.LoadAll<TaskData>("Tasks");
Debug.Log("Loaded " + localTasks.Length + " tasks from local resources as fallback");
}
// 服务器下发的缓存存储处
public TaskData CreateFromResponse(TaskDataResponse response)
{
TaskData task = ScriptableObject.CreateInstance<TaskData>();
task.id = response.id;
task.name = response.name;
task.desc = response.desc;
task.condition = (TaskConditionType)response.condition;
task.value1 = response.value1;
task.value2 = response.value2;
task.value3 = response.value3;
if (response.rewardTypes != null)
{
task.rewardTypes = new TaskRewardType[response.rewardTypes.Length];
for (int i = 0; i < response.rewardTypes.Length; i++)
{
task.rewardTypes[i] = (TaskRewardType)response.rewardTypes[i];
}
}
else
{
task.rewardTypes = new TaskRewardType[0];
}
task.rewardNums = response.rewardNums != null ? response.rewardNums : new int[0];
task.isDailyTask = response.isDailyTask;
task.durationHours = response.durationHours;
return task;
}
private async void LoadPlayerData()
@@ -178,7 +220,7 @@ namespace TcgEngine.Gameplay
string url = ApiClient.ServerURL + $"/api/tasks/"+ApiClient.Get().UserID;
WebResponse res = await ApiClient.Get().SendGetRequest(url);
Debug.Log($"<color=red>LoadPlayerTasksFromServer:{url}</color>");
// Debug.Log($"<color=red>LoadPlayerTasksFromServer:{url}</color>");
Debug.LogWarning($"从服务器获取玩家任务数据res_data--:{res.data},{res.status}");
if (res.success)
{
@@ -211,12 +253,6 @@ namespace TcgEngine.Gameplay
Debug.LogWarning("Failed to load player tasks from server: " + res.error);
}
}
// 简化处理,首次登录时分配任务
if (playerTasks.Count == 0)
{
AssignDailyTaskIfNeeded();
}
}
public async void SavePlayerData()
@@ -233,7 +269,7 @@ namespace TcgEngine.Gameplay
taskResponses[i] = playerTasks[i].ToResponse();
Debug.Log($"数据[{i}]:{taskResponses[i].taskId}");
}
foreach (PlayerTaskResponse item in taskResponses)
{
Debug.Log($"<color=red>id:{item.taskId}" +
@@ -244,12 +280,12 @@ namespace TcgEngine.Gameplay
$"</color>");
}
Debug.Log($"<color=red>{taskResponses.Length}</color>");
saveData.tasks = taskResponses;
saveData.lastDailyTaskAssigned = lastDailyTaskAssigned;
Debug.Log($"saveData.tasks---{saveData.tasks.Length}");
string json = ApiTool.ToJson(saveData);
@@ -259,6 +295,11 @@ namespace TcgEngine.Gameplay
Debug.Log(json);
Debug.Log($"<color=red>SavePlayerData:{url}</color>");
if (isClearPlayerTasks)
{
Debug.Log($"数据清除后<color=red>SavePlayerData:{url}</color>");
isClearPlayerTasks = false;
}
if (res.success)
{
@@ -271,6 +312,27 @@ namespace TcgEngine.Gameplay
}
}
private void Update()
{
if (isClearPlayerTasks)
{
ClearAllSaveData();
}
}
private void ClearAllSaveData()
{
if (!isClearPlayerTasks)
{
Debug.LogWarning("清除失败");
return;
}
playerTasks.Clear();
SavePlayerData();
Debug.Log("清除成功");
}
// 每日任务分配
public void AssignDailyTaskIfNeeded()
{
@@ -287,17 +349,29 @@ namespace TcgEngine.Gameplay
if (playerTasks.Count >= maxTasks)
return;
// 获取所有每日任务
TaskData[] allTasks = Resources.LoadAll<TaskData>("Tasks");
TaskData[] allTasks;
if (taskConfigs.Count!=0)
{
// 从缓存中取 Value 部分TaskData转成数组
allTasks = taskConfigs.Values.ToArray();
Debug.Log("读取任务缓存成功!");
}
else
{
// 如果缓存没有任务采用本地任务
allTasks = Resources.LoadAll<TaskData>("Tasks");
Debug.LogError("读取任务缓存失败,采用本地任务");
}
var dailyTasks = allTasks
.Where(t => t.isDailyTask &&
t.condition != 0 &&
!string.IsNullOrEmpty(t.id))
t.condition != 0 &&
!string.IsNullOrEmpty(t.id))
.ToArray();
if (dailyTasks.Length == 0)
return;
// 避免重复分配相同任务
int maxRetries = 3;
TaskData selectedTask = null;
@@ -573,6 +647,11 @@ namespace TcgEngine.Gameplay
{
AssignLoginTask();
}
else
{
// 如过有就随机分配一个新任务
AssignDailyTaskIfNeeded();
}
// 登录任务完成
UpdateTaskProgress(TaskConditionType.LoginGame);
@@ -580,8 +659,7 @@ namespace TcgEngine.Gameplay
// 检查是否有任务完成并自动领取奖励
CheckAndClaimCompletedTasks();
// 分配每日任务(如果需要)
AssignDailyTaskIfNeeded();
}
/// <summary>
@@ -625,12 +703,4 @@ namespace TcgEngine.Gameplay
return playerTasks;
}
}
// 玩家任务保存数据结构
[Serializable]
public struct PlayerTaskSaveData
{
public PlayerTask[] tasks;
public DateTime lastDailyTaskAssigned;
}
}