DisasterConverter.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace App\Module\AppGame\Proto;
  3. use Uraus\Kku\Common\LandDisaster;
  4. /**
  5. * 灾害转换辅助类
  6. *
  7. * 负责将Farm模块的灾害数组转换为Protobuf的LandDisaster对象数组
  8. */
  9. class DisasterConverter
  10. {
  11. /**
  12. * 将灾害数组转换为LandDisaster对象数组
  13. *
  14. * @param array $disasters 灾害数组
  15. * @return LandDisaster[] LandDisaster对象数组
  16. */
  17. public static function convertToLandDisasters(array $disasters): array
  18. {
  19. $landDisasters = [];
  20. foreach ($disasters as $disaster) {
  21. if (!isset($disaster['type'])) {
  22. continue;
  23. }
  24. $landDisaster = new LandDisaster();
  25. $landDisaster->setType($disaster['type']);
  26. // 设置灾害是否活跃,默认为活跃状态
  27. $isActive = ($disaster['status'] ?? 'active') === 'active';
  28. $landDisaster->setActive($isActive);
  29. $landDisasters[] = $landDisaster;
  30. }
  31. return $landDisasters;
  32. }
  33. /**
  34. * 设置DataLand的向后兼容灾害标志
  35. *
  36. * 为了保持向后兼容性,根据灾害类型设置对应的布尔值标志
  37. *
  38. * @param \Uraus\Kku\Common\DataLand $dataLand DataLand对象
  39. * @param array $disasters 灾害数组
  40. * @return void
  41. */
  42. public static function setCompatibilityFlags(\Uraus\Kku\Common\DataLand $dataLand, array $disasters): void
  43. {
  44. foreach ($disasters as $disaster) {
  45. if (isset($disaster['type']) && ($disaster['status'] ?? 'active') === 'active') {
  46. switch ($disaster['type']) {
  47. case 3: // 杂草 (WEED)
  48. $dataLand->setNeedWeed(true);
  49. break;
  50. case 2: // 虫害 (PEST)
  51. $dataLand->setNeedPestControl(true);
  52. break;
  53. case 1: // 干旱 (DROUGHT)
  54. $dataLand->setNeedWatering(true);
  55. break;
  56. }
  57. }
  58. }
  59. }
  60. /**
  61. * 处理DataLand的灾害信息
  62. *
  63. * 统一处理灾害信息的设置,包括新的disasters属性和向后兼容的布尔值标志
  64. *
  65. * @param \Uraus\Kku\Common\DataLand $dataLand DataLand对象
  66. * @param array $disasters 灾害数组
  67. * @return void
  68. */
  69. public static function processDisasters(\Uraus\Kku\Common\DataLand $dataLand, array $disasters): void
  70. {
  71. if (!empty($disasters)) {
  72. // 设置新的disasters属性
  73. $landDisasters = self::convertToLandDisasters($disasters);
  74. $dataLand->setDisasters($landDisasters);
  75. // 设置向后兼容的布尔值标志
  76. self::setCompatibilityFlags($dataLand, $disasters);
  77. } else {
  78. // 没有灾害时设置空数组
  79. $dataLand->setDisasters([]);
  80. }
  81. }
  82. }