MapComponent.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. using FL.Battle;
  2. using FL.Data;
  3. using FL.FGUI;
  4. using FL.Map;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using UnityEngine;
  8. using XGame;
  9. using XGame.Database;
  10. using XGame.Framework.Interfaces;
  11. using XGame.Framework.Map;
  12. using XGame.Framework.Nodes;
  13. using XGame.Framework.Time;
  14. namespace FL.Nodes.GameMain
  15. {
  16. public class MapComponent : NodeComponent, IUpdate
  17. {
  18. private int _chapterId;
  19. private EMapSchedule _schedule;
  20. private ITimer _monsterTimer;
  21. /// <summary>
  22. /// boss战斗倒计时
  23. /// </summary>
  24. private ITimer _bossTimer;
  25. private PlayerEntity _player;
  26. /// <summary>
  27. /// 怪物坐标相对出生点的偏移值
  28. /// 怪物最多13个,分两排排列,索引如下
  29. /// 二排 9 5 1 2 6 10
  30. /// 一排 11 7 3 0 4 8 12
  31. /// 0的左边偏移值为负数
  32. /// </summary>
  33. private Vector3 _monsterOffset = new Vector3(0.8f, 1.5f, 0);
  34. /// <summary>
  35. /// 空闲的怪物位置索引
  36. /// </summary>
  37. private List<int> _unusedIndexs;
  38. /// <summary>
  39. /// 怪物的实例对象
  40. /// </summary>
  41. private Dictionary<long, MonsterEntity> _monsterMap;
  42. /// <summary>
  43. /// 伙伴的实例对象
  44. /// </summary>
  45. private Dictionary<long, PartnerEntity> _partnerMap;
  46. private MapKey _currentMap;
  47. public override void OnEnable(object intent)
  48. {
  49. EventSingle.Instance.AddListener(EventDefine.GameMainMapRemoveEntity, OnRemoveEntity);
  50. EventSingle.Instance.AddListener(EventDefine.GameMainMapEndMask, OnMapEndMask);
  51. EventSingle.Instance.AddListener(EventDefine.PartnerDown, OnPartnerDown);
  52. EventSingle.Instance.AddListener(EventDefine.PartnerUp, OnPartnerUp);
  53. InitMonsters();
  54. StartMap(PlayerData.Instance.chapterId);
  55. }
  56. public override void OnDisable()
  57. {
  58. EventSingle.Instance.RemoveListener(EventDefine.GameMainMapRemoveEntity, OnRemoveEntity);
  59. EventSingle.Instance.RemoveListener(EventDefine.GameMainMapEndMask, OnMapEndMask);
  60. EventSingle.Instance.RemoveListener(EventDefine.PartnerDown, OnPartnerDown);
  61. EventSingle.Instance.RemoveListener(EventDefine.PartnerUp, OnPartnerUp);
  62. _player = null;
  63. _partnerMap?.Clear();
  64. _monsterTimer?.Cancel();
  65. _monsterTimer = null;
  66. _bossTimer?.Cancel();
  67. _bossTimer = null;
  68. _monsterMap?.Clear();
  69. _unusedIndexs?.Clear();
  70. Context.Map.Close(_currentMap);
  71. _currentMap = null;
  72. }
  73. void IUpdate.Update(int millisecond)
  74. {
  75. if (_player == null)
  76. return;
  77. }
  78. private void InitMonsters()
  79. {
  80. if (_unusedIndexs == null)
  81. _unusedIndexs = new List<int>();
  82. else
  83. _unusedIndexs.Clear();
  84. for (var i = 0; i < 13; i++)
  85. {
  86. _unusedIndexs.Add(i);
  87. }
  88. }
  89. private void StartMap(int chapterId)
  90. {
  91. _chapterId = chapterId;
  92. _schedule = EMapSchedule.LoadingMap;
  93. var chapter = ChapterTableRepo.Get(_chapterId);
  94. var map = MapTableRepo.Get(chapter.Map);
  95. var mapKey = MapKeys.NameToKey(map.AssetName);
  96. if (mapKey == _currentMap)
  97. { // 是同一个地图
  98. StartChapter(true, false);
  99. }
  100. else
  101. {
  102. // 关闭当前地图
  103. Context.Map.Close(_currentMap);
  104. _currentMap = mapKey;
  105. // 加载新地图
  106. var mapAsync = Context.Map.RunAsync(mapKey);
  107. mapAsync.On(_ =>
  108. {
  109. StartChapter(true, true);
  110. });
  111. }
  112. }
  113. private void StartChapter(bool isChapterChanged, bool isMapChanged)
  114. {
  115. _schedule = EMapSchedule.Monster1;
  116. var chapter = ChapterTableRepo.Get(_chapterId);
  117. var map = MapTableRepo.Get(chapter.Map);
  118. var dto = new LoadEntitiesDto();
  119. dto.chapterId = _chapterId;
  120. dto.isChapterChanged = isChapterChanged;
  121. dto.isBossPart = chapter.Part_type == 1;
  122. dto.isPlayerMove = true;
  123. //战斗位置
  124. dto.battlePosition = GetBattlePosition(map, chapter.Part);// map.BattlePositions[chapter.Part - 1].ToVector3();
  125. var isGenPlayer = _player == null;
  126. if (isGenPlayer)
  127. {
  128. _player = GenPlayer(map.PlayerBirth.ToVector3());
  129. //玩家
  130. dto.player = _player;
  131. //伙伴
  132. var partners = GenPartners(_player.BirthPosition);
  133. AddPartners(partners);
  134. dto.partners = partners;
  135. }
  136. else if (isMapChanged)
  137. {
  138. //玩家
  139. dto.player = _player;
  140. //伙伴
  141. dto.partners = _partnerMap.Values.ToArray();
  142. }
  143. if (isChapterChanged || dto.isBossPart)
  144. {
  145. // 重置玩家血量
  146. _player.Attr.Dynamic.Clear();
  147. _player.Attr.ResetHp();
  148. }
  149. if (isChapterChanged)
  150. {
  151. // 随从可能有替换过,重置随从的出生点
  152. var birthPosition = _player.BirthPosition;
  153. foreach (var partner in _partnerMap.Values)
  154. {
  155. partner.BirthPosition = birthPosition + PartnersData.Instance.GetPartnerOffset(partner.Attr.UID);
  156. }
  157. }
  158. //怪物数据
  159. var monsters = GenMonsters();
  160. AddMonsters(monsters);
  161. dto.monsters = monsters;
  162. dto.monsterMoveDistance = map.MonsterBirth.Y - map.BattleFirst.Y;// map.MonsterPositions[chapter.Part - 1].ToVector3().y - dto.battlePosition.y;
  163. //定时器
  164. if (!dto.isBossPart)
  165. { // 普通节点,增加定时器
  166. dto.monsterMoveDelay = 0;
  167. _monsterTimer = Context.Time.AddDelayLooperTimer(chapter.Interval * 6, chapter.Interval * 6, OnLoopGenMonsters);
  168. }
  169. else
  170. { // boss关卡,直接到最后
  171. dto.monsterMoveDelay = 1000;
  172. _schedule = EMapSchedule.Monster5;
  173. Context.UI.OpenAsync(UIKeys.MainBossLaiXi);
  174. Context.Time.AddDelayTimer(1000, () =>
  175. { //1秒后自动关闭
  176. Context.UI.Close(UIKeys.MainBossLaiXi);
  177. if (chapter.Time > 0)
  178. {// boss战斗倒计时
  179. _bossTimer = Context.Time.AddDelayTimer(chapter.Time, CombatFailed);
  180. EventSingle.Instance.Notify(EventDefine.GameMainMapBossStart, chapter.Id);
  181. }
  182. });
  183. }
  184. EventSingle.Instance.Notify(EventDefine.GameMainMapLoadEntities, dto);
  185. }
  186. private void OnLoopGenMonsters(int times)
  187. {
  188. _schedule += 1;
  189. if (_schedule == EMapSchedule.Monster5)
  190. {
  191. _monsterTimer.Cancel();
  192. _monsterTimer = null;
  193. }
  194. var chapter = ChapterTableRepo.Get(_chapterId);
  195. var map = MapTableRepo.Get(chapter.Map);
  196. var dto = new LoadEntitiesDto();
  197. dto.chapterId = _chapterId;
  198. //战斗位置
  199. dto.battlePosition = GetBattlePosition(map, chapter.Part);// map.BattlePositions[chapter.Part - 1].ToVector3();
  200. //怪物数据
  201. var monsters = GenMonsters();
  202. AddMonsters(monsters);
  203. dto.monsters = monsters;
  204. dto.monsterMoveDistance = map.MonsterBirth.Y - map.BattleFirst.Y;// map.MonsterPositions[chapter.Part - 1].ToVector3().y - dto.battlePosition.y;
  205. EventSingle.Instance.Notify(EventDefine.GameMainMapLoadEntities, dto);
  206. }
  207. private PlayerEntity GenPlayer(Vector3 birth)
  208. {
  209. var playerData = PlayerData.Instance;
  210. var player = new PlayerEntity()
  211. {
  212. BirthPosition = birth//玩家出生点
  213. };
  214. var entityAttr = new EntityAttributes(0, playerData.UID)
  215. {
  216. Name = playerData.Name,
  217. Radius = 1,
  218. AttackCD = 2000,
  219. };
  220. entityAttr.CopyFrom(playerData.Attr);
  221. player.Init(UIDDefine.New(), entityAttr, playerData.skillIds);
  222. return player;
  223. }
  224. private PartnerEntity[] GenPartners(Vector3 targetPosition)
  225. {
  226. var goneUpMap = PartnersData.Instance.GoneUpMap;
  227. var count = goneUpMap.Count;
  228. var partners = new PartnerEntity[count];
  229. var index = 0;
  230. foreach (var partnerUID in goneUpMap.Keys)
  231. {
  232. partners[index++] = GenPartner(targetPosition, partnerUID);
  233. }
  234. return partners;
  235. }
  236. private PartnerEntity GenPartner(Vector3 targetPosition, long partnerId)
  237. {
  238. var partner = PartnersData.Instance.PartnersMap[partnerId];
  239. var entity = new PartnerEntity()
  240. {
  241. BirthPosition = targetPosition + PartnersData.Instance.GetPartnerOffset(partner.UID),
  242. EpigraphId = 20300,
  243. };
  244. var entityAttr = new EntityAttributes(partner.TableId, partner.UID)
  245. {
  246. Name = partner.Name,
  247. Radius = partner.Radius,
  248. AttackCD = 6000,
  249. };
  250. entityAttr.CopyFrom(partner.Attr);
  251. var table = PartnerTableRepo.Get(partner.TableId);
  252. entity.Init(UIDDefine.New(), entityAttr, new int[] { partner.SkillId });
  253. return entity;
  254. }
  255. private void AddPartners(PartnerEntity[] partners)
  256. {
  257. if (partners == null || partners.Length == 0) return;
  258. if (_partnerMap == null)
  259. {
  260. _partnerMap = new Dictionary<long, PartnerEntity>();
  261. }
  262. foreach (var partner in partners)
  263. {
  264. _partnerMap.Add(partner.EntityId, partner);
  265. }
  266. }
  267. /// <summary>
  268. /// 获取怪物的出生坐标和索引
  269. /// </summary>
  270. /// <param name="position"></param>
  271. /// <param name="positionIdx"></param>
  272. /// <returns></returns>
  273. private Vector3 GetMonsterBirth(Vector3 position, out int positionIdx)
  274. {
  275. if (_unusedIndexs.Count > 0)
  276. {
  277. positionIdx = _unusedIndexs[0];
  278. _unusedIndexs.RemoveAt(0);
  279. }
  280. else
  281. {
  282. positionIdx = 0;
  283. }
  284. if (positionIdx == 0)
  285. {
  286. return position;
  287. }
  288. var offset = Vector3.zero;
  289. var xMultiple = (positionIdx + 1) / 2;
  290. offset.x = _monsterOffset.x * xMultiple;
  291. if (positionIdx % 2 != 0)
  292. { // 索引为奇数的在左边
  293. offset.x = -offset.x;
  294. }
  295. if (xMultiple % 2 != 0)
  296. { // 倍数为奇数的在上面
  297. offset.y = _monsterOffset.y;
  298. }
  299. var target = position + offset;
  300. // 随机偏移xy(-0.2, 0.2)
  301. target.x += Random.Range(-0.25f, 0.25f);
  302. target.y += Random.Range(-0.25f, 0.25f);
  303. return target;
  304. }
  305. private void PushMonstPositionIdx(int positionIdx)
  306. {
  307. if (_unusedIndexs.Contains(positionIdx))
  308. return; // 避免重复记录
  309. for (var i = 0; i < _unusedIndexs.Count; i++)
  310. {
  311. if (positionIdx < _unusedIndexs[i] && (i == 0 || positionIdx > _unusedIndexs[i - 1]))
  312. { // 小于当前索引的值 且 大于(i - 1 )的值
  313. _unusedIndexs.Insert(i, positionIdx);
  314. return;
  315. }
  316. }
  317. _unusedIndexs.Add(positionIdx);
  318. }
  319. private MonsterEntity[] GenMonsters()
  320. {
  321. var chapter = ChapterTableRepo.Get(_chapterId);
  322. var map = MapTableRepo.Get(chapter.Map);
  323. Vector3 birthPosition = GetMonsterBirth(map, chapter.Part);// map.MonsterPositions[chapter.Part - 1].ToVector3();
  324. int[] monsterRefresh = null;
  325. switch (_schedule)
  326. {
  327. case EMapSchedule.Monster1:
  328. monsterRefresh = chapter.Monster_refresh1;
  329. break;
  330. case EMapSchedule.Monster2:
  331. monsterRefresh = chapter.Monster_refresh2;
  332. break;
  333. case EMapSchedule.Monster3:
  334. monsterRefresh = chapter.Monster_refresh3;
  335. break;
  336. case EMapSchedule.Monster4:
  337. monsterRefresh = chapter.Monster_refresh4;
  338. break;
  339. case EMapSchedule.Monster5:
  340. monsterRefresh = chapter.Monster_refresh5;
  341. break;
  342. default:
  343. break;
  344. }
  345. var monsterCount = (monsterRefresh != null && monsterRefresh.Length > 0) ? monsterRefresh[1] : 0;
  346. if (monsterCount > 0)
  347. { // 数量0-3
  348. var monsters = new MonsterEntity[monsterCount];
  349. for (var i = 0; i < monsterCount; i++)
  350. {
  351. var position = GetMonsterBirth(birthPosition, out var positionIdx);
  352. var monsterTab = MonsterTableRepo.Get(monsterRefresh[0]);
  353. var entityAttr = new EntityAttributes(monsterTab.Id, UIDDefine.New())
  354. {
  355. Name = monsterTab.Name,
  356. Radius = monsterTab.ModelSize * 0.5f,
  357. AttackCD = 3000,
  358. };
  359. entityAttr.Static.Hp = monsterTab.Hp;
  360. entityAttr.Static.HpLimit = monsterTab.Hp;
  361. entityAttr.Static.MoveSpeed = Mathf.RoundToInt(monsterTab.Speed);
  362. entityAttr.Static.Attack = monsterTab.Atk;
  363. entityAttr.CurrentHp = monsterTab.Hp;
  364. var entity = new MonsterEntity();
  365. entity.Init(UIDDefine.New(), entityAttr, monsterTab.Skills);
  366. entity.BirthPosition = position;
  367. entity.PositionIdx = positionIdx;
  368. monsters[i] = entity;
  369. }
  370. return monsters;
  371. }
  372. return null;
  373. }
  374. private void AddMonsters(MonsterEntity[] monsters)
  375. {
  376. if (monsters == null || monsters.Length == 0) return;
  377. if (_monsterMap == null)
  378. {
  379. _monsterMap = new Dictionary<long, MonsterEntity>();
  380. }
  381. foreach (var monsterInfo in monsters)
  382. {
  383. _monsterMap.Add(monsterInfo.EntityId, monsterInfo);
  384. }
  385. }
  386. #region 事件监听
  387. private void OnRemoveEntity(int eventId, object args)
  388. {
  389. var entityId = (long)args;
  390. if (_monsterMap.TryGetValue(entityId, out var entity))
  391. {
  392. _monsterMap.Remove(entityId);
  393. PushMonstPositionIdx(entity.PositionIdx);
  394. CheckMonsterAllDead();
  395. return;
  396. }
  397. if (_partnerMap.TryGetValue(entityId, out var partner))
  398. {
  399. _partnerMap.Remove(entityId);
  400. return;
  401. }
  402. if (entityId == _player.EntityId)
  403. {
  404. //TODO 失败结算
  405. CombatFailed();
  406. }
  407. }
  408. private void OnPartnerDown(int eventId, object args)
  409. {
  410. var partnerUID = (long)args;
  411. var entityId = GetPartnerEntityIdByUID(partnerUID);
  412. if (entityId == 0)
  413. return;
  414. EventSingle.Instance.Notify(EventDefine.GameMainMapRemoveEntity, entityId);
  415. }
  416. private void OnPartnerUp(int eventId, object args)
  417. {
  418. var partnerUID = (long)args;
  419. var entityId = GetPartnerEntityIdByUID(partnerUID);
  420. if (entityId != 0)
  421. return; // 已经有实例对象了
  422. var chapter = ChapterTableRepo.Get(_chapterId);
  423. var map = MapTableRepo.Get(chapter.Map);
  424. var dto = new LoadEntitiesDto();
  425. dto.chapterId = _chapterId;
  426. //战斗位置
  427. dto.battlePosition = GetBattlePosition(map, chapter.Part);// map.BattlePositions[chapter.Part - 1].ToVector3();
  428. var partner = GenPartner(dto.battlePosition, partnerUID);
  429. var partners = new PartnerEntity[] { partner };
  430. AddPartners(partners);
  431. dto.partners = partners;
  432. EventSingle.Instance.Notify(EventDefine.GameMainMapLoadEntities, dto);
  433. }
  434. //private void OnExchangePartner(int eventId, object args)
  435. //{
  436. // var addPartners = (List<int>)args;
  437. // var activePartnerIds = PartnersData.Instance.ActiveUIDs;
  438. // var count = addPartners.Count;
  439. // // 从后往前移除
  440. // for (var i = 0; i < count; i++)
  441. // {
  442. // var partnerId = activePartnerIds[activePartnerIds.Count - 1];
  443. // activePartnerIds.RemoveAt(activePartnerIds.Count - 1);
  444. // var EntityId = GetPartnerUIDByTableId(partnerId);
  445. // if (EntityId == 0)
  446. // continue;
  447. // EventSingle.Instance.Notify(EventDefine.GameMainMapRemoveEntity, EntityId);
  448. // }
  449. // activePartnerIds.AddRange(addPartners);
  450. // var chapter = ChapterTableRepo.Get(_chapterId);
  451. // var map = MapTableRepo.Get(chapter.Map);
  452. // var dto = new LoadEntitiesDto();
  453. // dto.chapterId = _chapterId;
  454. // //战斗位置
  455. // dto.battlePosition = map.BattlePositions[chapter.Part - 1].ToVector3();
  456. // var partners = GenPartners(dto.battlePosition, addPartners);
  457. // AddPartners(partners);
  458. // dto.partners = partners;
  459. // EventSingle.Instance.Notify(EventDefine.GameMainMapLoadEntities, dto);
  460. //}
  461. private void OnMapEndMask(int eventId, object args)
  462. {
  463. var isSuccess = (bool)args;
  464. var chapter = ChapterTableRepo.Get(_chapterId);
  465. int chapterId;
  466. if (isSuccess)
  467. {
  468. var nextChapter = ChapterTableRepo.Next(_chapterId);
  469. //没找到新关卡,重新开始
  470. if (nextChapter == null || nextChapter.Chapter != chapter.Chapter)
  471. { // 没有新关卡 || 章节id变化
  472. //TODO 章节切换
  473. }
  474. chapterId = nextChapter?.Id ?? PlayerData.Instance.chapterId;
  475. }
  476. //else if (chapter.Part_type == 1)
  477. //{ // boss节点失败,进入本关卡小怪节点循环
  478. // TODO
  479. //}
  480. else
  481. { // 普通节点失败,重置到本关卡第一个节点
  482. chapterId = _chapterId / 10 * 10 + 1;
  483. }
  484. StartMap(chapterId);
  485. }
  486. #endregion
  487. private void CheckMonsterAllDead()
  488. {
  489. if (_monsterMap.Count > 0) return;
  490. // 怪物全部死亡
  491. var chapter = ChapterTableRepo.Get(_chapterId);
  492. if (chapter.Part_type == 1)
  493. { //boss关卡
  494. //TODO 结算
  495. _bossTimer?.Cancel();
  496. _bossTimer = null;
  497. Context.UI.OpenAsync(UIKeys.MainBattleOverVictory);
  498. Context.Time.AddDelayTimer(2000, () =>
  499. { //2秒后自动关闭
  500. Context.UI.Close(UIKeys.MainBattleOverVictory);
  501. EventSingle.Instance.Notify(EventDefine.GameMainMapStartMask, true);
  502. });
  503. }
  504. else if (_schedule == EMapSchedule.Monster5)
  505. {
  506. _chapterId++;
  507. StartChapter(false, false);
  508. }
  509. }
  510. /// <summary>
  511. /// 战斗失败
  512. /// </summary>
  513. private void CombatFailed()
  514. {
  515. // 清空怪物数据
  516. foreach(var item in _monsterMap)
  517. {
  518. PushMonstPositionIdx(item.Value.PositionIdx);
  519. }
  520. _monsterMap.Clear();
  521. Context.UI.OpenAsync(UIKeys.MainBattleOverFail);
  522. EventSingle.Instance.Notify(EventDefine.GameMainMapStartMask, false);
  523. }
  524. private long GetPartnerEntityIdByUID(long uid)
  525. {
  526. foreach (var item in _partnerMap)
  527. {
  528. if (item.Value.Attr.UID == uid)
  529. return item.Key;
  530. }
  531. return 0;
  532. }
  533. private Vector3 GetBattlePosition(MapTable map, int mapPart)
  534. {
  535. return map.BattleFirst.ToVector3() + map.PartMove.ToVector3() * (mapPart - 1);
  536. }
  537. private Vector3 GetMonsterBirth(MapTable map, int mapPart)
  538. {
  539. return map.MonsterBirth.ToVector3() + map.PartMove.ToVector3() * (mapPart - 1);
  540. }
  541. }
  542. }