RabbitHuntGameMode_OnlinePK.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. socketPlayer = SocketPlayer.NewInstance();
  157. socketPlayer.onRoomReadyComplete = () => {
  158. myPlayerIndex = GlobalData.playerIndexInRoom;
  159. if (successCallback != null) successCallback();
  160. };
  161. socketPlayer.onReceivePKGameData = onReceivePKGameData;
  162. AutoSwitchBanUserControlBow();
  163. JC.Unity.CoroutineStarter.Start(CheckAndUpload());
  164. }
  165. bool IsCanUpload() {
  166. return GameMgr.ins == gameMode.gameMgr && gameMode.gameMgr;
  167. }
  168. WaitForSecondsRealtime uploadOnceTime = new WaitForSecondsRealtime(0.033f);
  169. IEnumerator CheckAndUpload() {
  170. Debug.Log("协程-同步数据-开始");
  171. while (IsCanUpload()) {
  172. try
  173. {
  174. Upload();
  175. }
  176. catch (System.Exception e)
  177. {
  178. Debug.LogError(e.Message);
  179. Debug.LogError(e.StackTrace);
  180. }
  181. yield return uploadOnceTime;
  182. }
  183. Debug.Log("协程-同步数据-停止");
  184. }
  185. Quaternion bowTargetQua;
  186. bool hasBowTargBtQua;
  187. void onReceivePKGameData(string key, string data) {
  188. if (!IsMyPlayerInited()) return;
  189. if (key == "logic") {
  190. SyncLogicData syncLogicData = JsonConvert.DeserializeObject<SyncLogicData>(data);
  191. syncLogicData.Output(this.gameMode);
  192. AutoSwitchBanUserControlBow();
  193. }
  194. if (key == "bow") {
  195. if (!IsMyPlayerRunning()) {
  196. string[] quaStr = data.Split(',');
  197. if (quaStr.Length == 6) {
  198. bowTargetQua.x = float.Parse(quaStr[0]);
  199. bowTargetQua.y = float.Parse(quaStr[1]);
  200. bowTargetQua.z = float.Parse(quaStr[2]);
  201. bowTargetQua.w = float.Parse(quaStr[3]);
  202. hasBowTargBtQua = true;
  203. ArmBow.ins.phase = int.Parse(quaStr[4]);
  204. GameAssistUI.ins.playerScaleAimValue_OnlinePK = int.Parse(quaStr[5]);
  205. }
  206. }
  207. }
  208. if (key == "arrow") {
  209. List<ArrowSync.SyncData> arrowSyncDataList = JsonConvert.DeserializeObject<List<ArrowSync.SyncData>>(data);
  210. foreach (var item in arrowSyncMap) {
  211. item.Value.hasSetSyncData = false;
  212. }
  213. GameObject arrowPrefab = ArmBow.ins.arrow;
  214. foreach (var item in arrowSyncDataList) {
  215. ArrowSync arrowSync;
  216. arrowSyncMap.TryGetValue(item.id, out arrowSync);
  217. if (arrowSync == null) {
  218. GameObject arrowObj = GameObject.Instantiate(arrowPrefab);
  219. arrowSync = arrowObj.AddComponent<ArrowSync>();
  220. arrowSync.SetSyncData(item, true);
  221. arrowSyncMap[item.id] = arrowSync;
  222. } else {
  223. arrowSync.SetSyncData(item);
  224. }
  225. arrowSync.hasSetSyncData = true;
  226. }
  227. List<int> removeIDs = null;
  228. foreach (var item in arrowSyncMap) {
  229. if (!item.Value.hasSetSyncData) {
  230. if (removeIDs == null) removeIDs = new List<int>();
  231. removeIDs.Add(item.Key);
  232. }
  233. }
  234. if (removeIDs != null) {
  235. foreach (var id in removeIDs) {
  236. ArrowSync arrowSync = arrowSyncMap[id];
  237. arrowSyncMap.Remove(id);
  238. if (arrowSync && arrowSync.gameObject) {
  239. GameObject.Destroy(arrowSync.gameObject);
  240. }
  241. }
  242. }
  243. }
  244. if (key == "onBowShoot") {
  245. GameEventCenter.ins.onBowArrowShootOut?.Invoke(null, null);
  246. }
  247. if (key == "DoNextShoot") {
  248. gameMode.DoNextShoot();
  249. }
  250. if (key == "animals") {
  251. List<RabbitSyncData> syncDataList = JsonConvert.DeserializeObject<List<RabbitSyncData>>(data);
  252. foreach (var item in animalSyncMap) {
  253. item.Value.isInvalid = true;
  254. }
  255. foreach (var item in syncDataList) {
  256. Rabbit animalSync;
  257. animalSyncMap.TryGetValue(item.id, out animalSync);
  258. if (animalSync == null) {
  259. GameObject animalObject = GameObject.Instantiate(gameMode.animalPrefab, Vector3.zero, Quaternion.identity, gameMode.animalsBaseT);
  260. animalSync = animalObject.GetComponent<Rabbit>();
  261. animalSync.isMirror = true;
  262. animalSync.inputSyncData = item;
  263. animalObject.SetActive(true);
  264. animalSyncMap[item.id] = animalSync;
  265. } else {
  266. animalSync.inputSyncData = item;
  267. }
  268. animalSync.isInvalid = false;
  269. }
  270. List<int> removeIDs = null;
  271. foreach (var item in animalSyncMap) {
  272. if (item.Value.isInvalid) {
  273. if (removeIDs == null) removeIDs = new List<int>();
  274. removeIDs.Add(item.Key);
  275. }
  276. }
  277. if (removeIDs != null) {
  278. foreach (var id in removeIDs) {
  279. Rabbit animalSync = animalSyncMap[id];
  280. animalSyncMap.Remove(id);
  281. if (animalSync && animalSync.gameObject) {
  282. GameObject.Destroy(animalSync.gameObject);
  283. }
  284. }
  285. }
  286. }
  287. if (key == "RUpdate") {
  288. if (int.Parse(data) == roundID) {
  289. gameMode.OnUpdate(uploadOnceTime.waitTime, false);
  290. }
  291. }
  292. if (key == "OnHit") {
  293. string[] dataSplits = data.Split(',');
  294. int uid = int.Parse(dataSplits[0]);
  295. string partName = dataSplits[1];
  296. foreach (var item in Rabbit.rabbitSet) {
  297. if (item.uid == uid) {
  298. item.OnHitLogic(null, partName);
  299. break; //一定要break,原因1:这是唯一ID,后续也没必要检测了,原因2:这里可能会触发死亡,死亡会触发下个动物生成,Set集合的元素+1,继续遍历会出现modifyException
  300. }
  301. }
  302. }
  303. }
  304. public void AutoSwitchBanUserControlBow() {
  305. BowCamera.ins.banLogic = ArmBow.ins.banLogic = !IsMyPlayerRunning();
  306. }
  307. int lastRoundID = -1;
  308. public void OnFrameUpdate() {
  309. if (!IsMyPlayerInited()) return;
  310. AutoSwitchBanUserControlBow();
  311. if (!IsMyPlayerRunning() && hasBowTargBtQua) {
  312. BowCamera.ins.transform.rotation = Quaternion.Lerp(BowCamera.ins.transform.rotation, bowTargetQua, Time.deltaTime * 12);
  313. }
  314. if (roundID > lastRoundID) {
  315. lastRoundID = roundID;
  316. gameMode.BanBowReady();
  317. gameMode.AddReadyView();
  318. }
  319. if (gameEnd && !gameMode.gameMgr.gameOver) {
  320. gameMode.AnnounceGameOver();
  321. }
  322. }
  323. void Upload() {
  324. if (!IsMyPlayerInited()) return;
  325. UploadLogic();
  326. UploadBow();
  327. UploadArrows();
  328. UploadAnimals();
  329. UploadRequestUpdate();
  330. UploadOnHit();
  331. }
  332. void UploadLogic() {
  333. if (!IsMainHost()) return;
  334. SyncLogicData data = new SyncLogicData().Input(this.gameMode);
  335. socketPlayer.UploadPKGameData("logic", data);
  336. }
  337. void UploadBow() {
  338. if (!IsMyPlayerRunning()) return;
  339. Quaternion qua = BowCamera.ins.transform.rotation;
  340. int aimScaleValue = GameAssistUI.ins.aimScaleValue;
  341. if (!GameAssistUI.ins.scaleAimOn) aimScaleValue = 0;
  342. socketPlayer.UploadPKGameData("bow", qua.x + "," + qua.y + "," + qua.z + "," + qua.w + "," + ArmBow.ins.phase + "," + aimScaleValue);
  343. }
  344. Dictionary<int, ArrowSync> arrowSyncMap = new Dictionary<int, ArrowSync>();
  345. void UploadArrows() {
  346. List<ArrowSync.SyncData> arrowSyncDataList = new List<ArrowSync.SyncData>();
  347. foreach (var item in Arrow.arrowSet) {
  348. if (item.outputSyncData == null || !item.outputSyncData.inited) continue;
  349. arrowSyncDataList.Add(item.outputSyncData);
  350. }
  351. socketPlayer.UploadPKGameData("arrow", arrowSyncDataList);
  352. }
  353. Dictionary<int, Rabbit> animalSyncMap = new Dictionary<int, Rabbit>();
  354. void UploadAnimals() {
  355. if (!IsMainHost()) return;
  356. List<RabbitSyncData> syncDataList = new List<RabbitSyncData>();
  357. foreach (var item in Rabbit.rabbitSet) {
  358. if (item.outputSyncData == null) continue;
  359. syncDataList.Add(item.outputSyncData);
  360. }
  361. socketPlayer.UploadPKGameData("animals", syncDataList);
  362. }
  363. void UploadRequestUpdate() {
  364. if (!IsCopyHost()) return;
  365. if (!IsMyPlayerRunning()) return;
  366. if (gameMode.pauseTimeCounting) return;
  367. socketPlayer.UploadPKGameData("RUpdate", this.roundID.ToString());
  368. }
  369. void UploadOnHit() {
  370. foreach (var item in Rabbit.rabbitSet) {
  371. if (item.onHitData != null) {
  372. socketPlayer.UploadPKGameData("OnHit", item.onHitData);
  373. item.onHitData = null;
  374. }
  375. }
  376. }
  377. }
  378. }