YejiHuntGameMode_OnlinePK.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using Newtonsoft.Json;
  6. public class YejiHuntGameMode_OnlinePK : YejiHuntGameMode, ChallengeGameModeLocalPK
  7. {
  8. public int currentPlayerIndex = 0; // 双人0和1
  9. float singleShootReadyTime = 30f;
  10. float singleShootReadyTimeMax = 30f;
  11. public YejiHuntGameMode_OnlinePK(GameMgr gameMgr) : base(gameMgr) {
  12. onlineHelper = new OnlineHelper(this);
  13. hunterGamePlayerScoreCounter = new HunterGamePlayerScoreCounter(this);
  14. }
  15. public override void Start()
  16. {
  17. onlineHelper.InitSocketPlayer(OnStart);
  18. }
  19. private void OnStart() {
  20. banCreateAnimal = onlineHelper.IsCopyHost();
  21. banOnBowArrowShootOut = onlineHelper.IsCopyHost();
  22. Yeji.InitPreHeights();
  23. SetLevel(5);
  24. AddHuntGameView();
  25. this.gameMgr.transform.Find("HunterGameView_LocalPK").gameObject.SetActive(true);
  26. }
  27. public override void onBowShoot() {
  28. if (onlineHelper.IsCopyHost()) {
  29. onlineHelper.socketPlayer.UploadPKGameData("onBowShoot", "");
  30. }
  31. }
  32. public override bool DoNextShoot() {
  33. if (onlineHelper.IsCopyHost()) {
  34. onlineHelper.socketPlayer.UploadPKGameData("DoNextShoot", "");
  35. return false;
  36. }
  37. foreach (var item in Yeji.yejiSet) {
  38. if (item.onlineHandler.onDoNextShootWillDestroy) {
  39. GameObject.Destroy(item.gameObject);
  40. }
  41. }
  42. bool canDo = base.DoNextShoot();
  43. if (canDo) {
  44. NextPlayerFinal();
  45. }
  46. return canDo;
  47. }
  48. void AddReadyView()
  49. {
  50. GameObject view = Resources.Load<GameObject>("Prefabs/Views/PKGameReadyView_Challenge");
  51. GameObject o = GameObject.Instantiate(view);
  52. PKGameReadyView_Challenge script = o.GetComponent<PKGameReadyView_Challenge>();
  53. script.currentPlayerIndex = currentPlayerIndex;
  54. }
  55. void NextPlayerFinal() {
  56. NextPlayer();
  57. }
  58. void NextPlayer() {
  59. currentPlayerIndex++;
  60. currentPlayerIndex %= 2;
  61. singleShootReadyTime = singleShootReadyTimeMax;
  62. onlineHelper.roundID++;
  63. }
  64. public override void Update() {
  65. if (!onlineHelper.IsMyPlayerInited()) return;
  66. if (!onlineHelper.IsMainHost()) return;
  67. if (!onlineHelper.IsMyPlayerRunning()) return;
  68. OnUpdate(Time.deltaTime, pauseTimeCounting);
  69. }
  70. void OnUpdate(float dt, bool _pauseTimeCounting) {
  71. if (gameMgr.gameOver || _pauseTimeCounting) return;
  72. if (this.time > 0) {
  73. this.time -= dt;
  74. } else {
  75. this.time = 0;
  76. AnnounceGameOver();
  77. }
  78. if (gameMgr.gameOver || _pauseTimeCounting) return;
  79. singleShootReadyTime -= dt;
  80. if (singleShootReadyTime <= 0) {
  81. //切换玩家
  82. ArmBow.ins.readyShoot();
  83. NextPlayerFinal();
  84. }
  85. }
  86. public override void FrameUpdate() {
  87. onlineHelper.OnFrameUpdate();
  88. }
  89. //localPK interface
  90. public int GetCurrentPlayIndex() {
  91. return currentPlayerIndex;
  92. }
  93. public (float, float) GetSingleShootReadyTime() {
  94. return (singleShootReadyTime, singleShootReadyTimeMax);
  95. }
  96. HunterGamePlayerScoreCounter hunterGamePlayerScoreCounter;
  97. public HunterGamePlayerScoreCounter getHunterGamePlayerScoreCounter() {
  98. return hunterGamePlayerScoreCounter;
  99. }
  100. //###------------
  101. //### 联机部分
  102. //###------------
  103. public class SyncLogicData {
  104. public int roundID;
  105. public int currentPlayerIndex;
  106. public float singleShootReadyTime;
  107. public int animalCount = 0;
  108. public int arrowCount = 0;
  109. public float time = 60;
  110. public int[] hitScores;
  111. public bool gameEnd = false;
  112. public SyncLogicData Input(YejiHuntGameMode_OnlinePK src) {
  113. roundID = src.onlineHelper.roundID;
  114. currentPlayerIndex = src.currentPlayerIndex;
  115. singleShootReadyTime = src.singleShootReadyTime;
  116. animalCount = src.animalCount;
  117. arrowCount = src.arrowCount;
  118. time = src.time;
  119. hitScores = src.getHunterGamePlayerScoreCounter().hitScores;
  120. gameEnd = src.gameMgr.gameOver;
  121. return this;
  122. }
  123. public void Output(YejiHuntGameMode_OnlinePK dest) {
  124. dest.onlineHelper.roundID = roundID;
  125. dest.currentPlayerIndex = currentPlayerIndex;
  126. dest.singleShootReadyTime = singleShootReadyTime;
  127. dest.animalCount = animalCount;
  128. dest.arrowCount = arrowCount;
  129. dest.time = time;
  130. dest.getHunterGamePlayerScoreCounter().hitScores = hitScores;
  131. dest.onlineHelper.gameEnd = gameEnd;
  132. }
  133. }
  134. OnlineHelper onlineHelper;
  135. public class OnlineHelper {
  136. YejiHuntGameMode_OnlinePK gameMode;
  137. public OnlineHelper(YejiHuntGameMode_OnlinePK gameMode) {
  138. this.gameMode = gameMode;
  139. }
  140. public SocketPlayer socketPlayer;
  141. public int myPlayerIndex = -1;
  142. public bool IsMyPlayerInited() {
  143. return myPlayerIndex >= 0;
  144. }
  145. public bool IsMyPlayerRunning() {
  146. return myPlayerIndex == gameMode.currentPlayerIndex;
  147. }
  148. public bool IsMainHost() {
  149. return myPlayerIndex == 0;
  150. }
  151. public bool IsCopyHost() {
  152. return myPlayerIndex > 0;
  153. }
  154. public int roundID = 0;
  155. public bool gameEnd = false;
  156. public void InitSocketPlayer(Action successCallback) {
  157. if (GameObject.Find("SocketPlayer") == null) {
  158. PKMatchingView.MoniMatchForTestInGameScene(() => {
  159. myPlayerIndex = GlobalData.playerIndexInRoom;
  160. if (successCallback != null) successCallback();
  161. });
  162. } else {
  163. myPlayerIndex = GlobalData.playerIndexInRoom;
  164. if (successCallback != null) successCallback();
  165. }
  166. socketPlayer = GameObject.Find("SocketPlayer").GetComponent<SocketPlayer>();
  167. socketPlayer.onReceivePKGameData = onReceivePKGameData;
  168. AutoSwitchBanUserControlBow();
  169. JC.Unity.CoroutineStarter.Start(CheckAndUpload());
  170. }
  171. bool IsCanUpload() {
  172. return GameMgr.ins == gameMode.gameMgr && gameMode.gameMgr;
  173. }
  174. WaitForSecondsRealtime uploadOnceTime = new WaitForSecondsRealtime(0.033f);
  175. IEnumerator CheckAndUpload() {
  176. Debug.Log("协程-同步数据-开始");
  177. while (IsCanUpload()) {
  178. try
  179. {
  180. Upload();
  181. }
  182. catch (System.Exception e)
  183. {
  184. Debug.LogError(e.Message);
  185. Debug.LogError(e.StackTrace);
  186. }
  187. yield return uploadOnceTime;
  188. }
  189. Debug.Log("协程-同步数据-停止");
  190. }
  191. Quaternion bowTargetQua;
  192. bool hasBowTargBtQua;
  193. void onReceivePKGameData(string key, string data) {
  194. if (!IsMyPlayerInited()) return;
  195. if (key == "logic") {
  196. SyncLogicData syncLogicData = JsonConvert.DeserializeObject<SyncLogicData>(data);
  197. syncLogicData.Output(this.gameMode);
  198. AutoSwitchBanUserControlBow();
  199. }
  200. if (key == "bow") {
  201. if (!IsMyPlayerRunning()) {
  202. string[] quaStr = data.Split(',');
  203. if (quaStr.Length == 6) {
  204. bowTargetQua.x = float.Parse(quaStr[0]);
  205. bowTargetQua.y = float.Parse(quaStr[1]);
  206. bowTargetQua.z = float.Parse(quaStr[2]);
  207. bowTargetQua.w = float.Parse(quaStr[3]);
  208. hasBowTargBtQua = true;
  209. ArmBow.ins.phase = int.Parse(quaStr[4]);
  210. GameAssistUI.ins.playerScaleAimValue_OnlinePK = int.Parse(quaStr[5]);
  211. }
  212. }
  213. }
  214. if (key == "arrow") {
  215. List<ArrowSync.SyncData> arrowSyncDataList = JsonConvert.DeserializeObject<List<ArrowSync.SyncData>>(data);
  216. foreach (var item in arrowSyncMap) {
  217. item.Value.hasSetSyncData = false;
  218. }
  219. GameObject arrowPrefab = ArmBow.ins.arrow;
  220. foreach (var item in arrowSyncDataList) {
  221. ArrowSync arrowSync;
  222. arrowSyncMap.TryGetValue(item.id, out arrowSync);
  223. if (arrowSync == null) {
  224. GameObject arrowObj = GameObject.Instantiate(arrowPrefab);
  225. arrowSync = arrowObj.AddComponent<ArrowSync>();
  226. arrowSync.SetSyncData(item, true);
  227. arrowSyncMap[item.id] = arrowSync;
  228. } else {
  229. arrowSync.SetSyncData(item);
  230. }
  231. arrowSync.hasSetSyncData = true;
  232. }
  233. List<int> removeIDs = null;
  234. foreach (var item in arrowSyncMap) {
  235. if (!item.Value.hasSetSyncData) {
  236. if (removeIDs == null) removeIDs = new List<int>();
  237. removeIDs.Add(item.Key);
  238. }
  239. }
  240. if (removeIDs != null) {
  241. foreach (var id in removeIDs) {
  242. ArrowSync arrowSync = arrowSyncMap[id];
  243. arrowSyncMap.Remove(id);
  244. if (arrowSync && arrowSync.gameObject) {
  245. GameObject.Destroy(arrowSync.gameObject);
  246. }
  247. }
  248. }
  249. }
  250. if (key == "onBowShoot") {
  251. GameEventCenter.ins.onBowArrowShootOut?.Invoke(null, null);
  252. }
  253. if (key == "DoNextShoot") {
  254. gameMode.DoNextShoot();
  255. }
  256. if (key == "animals") {
  257. List<YejiSyncData> syncDataList = JsonConvert.DeserializeObject<List<YejiSyncData>>(data);
  258. foreach (var item in animalSyncMap) {
  259. item.Value.onlineHandler.isInvalid = true;
  260. }
  261. foreach (var item in syncDataList) {
  262. Yeji animalSync;
  263. animalSyncMap.TryGetValue(item.id, out animalSync);
  264. if (animalSync == null) {
  265. GameObject animalObject = GameObject.Instantiate(gameMode.animalPrefab, Vector3.zero, Quaternion.identity, gameMode.animalsBaseT);
  266. animalSync = animalObject.GetComponent<Yeji>();
  267. animalSync.onlineHandler.isMirror = true;
  268. animalSync.onlineHandler.inputSyncData = item;
  269. animalObject.SetActive(true);
  270. animalSyncMap[item.id] = animalSync;
  271. } else {
  272. animalSync.onlineHandler.inputSyncData = item;
  273. }
  274. animalSync.onlineHandler.isInvalid = false;
  275. }
  276. List<int> removeIDs = null;
  277. foreach (var item in animalSyncMap) {
  278. if (item.Value.onlineHandler.isInvalid) {
  279. if (removeIDs == null) removeIDs = new List<int>();
  280. removeIDs.Add(item.Key);
  281. }
  282. }
  283. if (removeIDs != null) {
  284. foreach (var id in removeIDs) {
  285. Yeji animalSync = animalSyncMap[id];
  286. animalSyncMap.Remove(id);
  287. if (animalSync && animalSync.gameObject) {
  288. GameObject.Destroy(animalSync.gameObject);
  289. }
  290. }
  291. }
  292. }
  293. if (key == "RUpdate") {
  294. if (int.Parse(data) == roundID) {
  295. gameMode.OnUpdate(uploadOnceTime.waitTime, false);
  296. }
  297. }
  298. if (key == "OnHit") {
  299. string[] dataSplits = data.Split(',');
  300. int uid = int.Parse(dataSplits[0]);
  301. string partName = dataSplits[1];
  302. foreach (var item in Yeji.yejiSet) {
  303. if (item.onlineHandler.uid == uid) {
  304. item.OnHitLogic(null, partName);
  305. break; //一定要break,原因1:这是唯一ID,后续也没必要检测了,原因2:这里可能会触发死亡,死亡会触发下个动物生成,Set集合的元素+1,继续遍历会出现modifyException
  306. }
  307. }
  308. }
  309. }
  310. public void AutoSwitchBanUserControlBow() {
  311. BowCamera.ins.banLogic = ArmBow.ins.banLogic = !IsMyPlayerRunning();
  312. }
  313. int lastRoundID = -1;
  314. public void OnFrameUpdate() {
  315. if (!IsMyPlayerInited()) return;
  316. AutoSwitchBanUserControlBow();
  317. if (!IsMyPlayerRunning() && hasBowTargBtQua) {
  318. BowCamera.ins.transform.rotation = Quaternion.Lerp(BowCamera.ins.transform.rotation, bowTargetQua, Time.deltaTime * 12);
  319. }
  320. if (roundID > lastRoundID) {
  321. lastRoundID = roundID;
  322. gameMode.BanBowReady();
  323. gameMode.AddReadyView();
  324. }
  325. if (gameEnd && !gameMode.gameMgr.gameOver) {
  326. gameMode.AnnounceGameOver();
  327. }
  328. }
  329. void Upload() {
  330. if (!IsMyPlayerInited()) return;
  331. UploadLogic();
  332. UploadBow();
  333. UploadArrows();
  334. UploadAnimals();
  335. UploadRequestUpdate();
  336. UploadOnHit();
  337. }
  338. void UploadLogic() {
  339. if (!IsMainHost()) return;
  340. SyncLogicData data = new SyncLogicData().Input(this.gameMode);
  341. socketPlayer.UploadPKGameData("logic", data);
  342. }
  343. void UploadBow() {
  344. if (!IsMyPlayerRunning()) return;
  345. Quaternion qua = BowCamera.ins.transform.rotation;
  346. int aimScaleValue = GameAssistUI.ins.aimScaleValue;
  347. if (!GameAssistUI.ins.scaleAimOn) aimScaleValue = 0;
  348. socketPlayer.UploadPKGameData("bow", qua.x + "," + qua.y + "," + qua.z + "," + qua.w + "," + ArmBow.ins.phase + "," + aimScaleValue);
  349. }
  350. Dictionary<int, ArrowSync> arrowSyncMap = new Dictionary<int, ArrowSync>();
  351. void UploadArrows() {
  352. List<ArrowSync.SyncData> arrowSyncDataList = new List<ArrowSync.SyncData>();
  353. foreach (var item in Arrow.arrowSet) {
  354. if (item.outputSyncData == null || !item.outputSyncData.inited) continue;
  355. arrowSyncDataList.Add(item.outputSyncData);
  356. }
  357. socketPlayer.UploadPKGameData("arrow", arrowSyncDataList);
  358. }
  359. Dictionary<int, Yeji> animalSyncMap = new Dictionary<int, Yeji>();
  360. void UploadAnimals() {
  361. if (!IsMainHost()) return;
  362. List<YejiSyncData> syncDataList = new List<YejiSyncData>();
  363. foreach (var item in Yeji.yejiSet) {
  364. if (item.onlineHandler.outputSyncData == null) continue;
  365. syncDataList.Add(item.onlineHandler.outputSyncData);
  366. }
  367. socketPlayer.UploadPKGameData("animals", syncDataList);
  368. }
  369. void UploadRequestUpdate() {
  370. if (!IsCopyHost()) return;
  371. if (!IsMyPlayerRunning()) return;
  372. if (gameMode.pauseTimeCounting) return;
  373. socketPlayer.UploadPKGameData("RUpdate", this.roundID.ToString());
  374. }
  375. void UploadOnHit() {
  376. foreach (var item in Yeji.yejiSet) {
  377. if (item.onlineHandler.onHitData != null) {
  378. socketPlayer.UploadPKGameData("OnHit", item.onlineHandler.onHitData);
  379. item.onlineHandler.onHitData = null;
  380. }
  381. }
  382. }
  383. }
  384. }