RabbitHuntGameMode_OnlinePK.cs 16 KB

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