PetConfig.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System.Text.Json;
  2. using System.Text.Json.Serialization;
  3. namespace XafPet.Desktop.PetEngine;
  4. [JsonConverter(typeof(JsonStringEnumConverter))]
  5. public enum PetType { Animal, Human, Custom }
  6. /// <summary>宠物形象配置(pet-config.json)</summary>
  7. public sealed class PetConfig
  8. {
  9. [JsonPropertyName("version")]
  10. public string Version { get; set; } = "1.0";
  11. [JsonPropertyName("type")]
  12. public PetType Type { get; set; } = PetType.Custom;
  13. [JsonPropertyName("species")]
  14. public string Species { get; set; } = "other";
  15. [JsonPropertyName("gender")]
  16. public string Gender { get; set; } = "neutral";
  17. [JsonPropertyName("image_base_url")]
  18. public string ImageBaseUrl { get; set; } = "";
  19. [JsonPropertyName("default_image")]
  20. public string DefaultImage { get; set; } = "standing.png";
  21. [JsonPropertyName("actions")]
  22. public Dictionary<string, string> Actions { get; set; } = new();
  23. [JsonPropertyName("sounds")]
  24. public Dictionary<string, string> Sounds { get; set; } = new();
  25. [JsonPropertyName("parameters")]
  26. public PetParameters Parameters { get; set; } = new();
  27. [JsonIgnore]
  28. public int CustomStateCount => Actions.Keys.Count(k => k.StartsWith("custom_state_"));
  29. /// <summary>解析 JSON 字符串;缺省 actions 时补默认映射(key=value)</summary>
  30. public static PetConfig Parse(string json)
  31. {
  32. var config = JsonSerializer.Deserialize<PetConfig>(json)
  33. ?? throw new JsonException("pet-config.json 反序列化结果为 null");
  34. if (config.Actions.Count == 0)
  35. {
  36. config.Actions = new Dictionary<string, string>
  37. {
  38. ["idle"] = "idle",
  39. ["happy"] = "happy",
  40. ["busy"] = "busy",
  41. ["sleeping"] = "sleeping"
  42. };
  43. }
  44. return config;
  45. }
  46. public string GetActionForState(string stateName)
  47. => Actions.TryGetValue(stateName, out var v) ? v : stateName;
  48. }
  49. public sealed class PetParameters
  50. {
  51. [JsonPropertyName("move_distance")]
  52. public int MoveDistance { get; set; } = 15;
  53. [JsonPropertyName("animation_speed")]
  54. public double AnimationSpeed { get; set; } = 1.0;
  55. [JsonPropertyName("interaction_timeout")]
  56. public int InteractionTimeout { get; set; } = 300; // 秒
  57. }