PKGameMode_OnlinePK.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using DG.Tweening;
  6. using Newtonsoft.Json;
  7. /**双人PK模式 */
  8. public class PKGameMode_OnlinePK : GameMode {
  9. SocketPlayer socketPlayer;
  10. public int myPlayerIndex = -111;
  11. public bool IsMyPlayerInited() {
  12. return myPlayerIndex >= 0;
  13. }
  14. public bool IsMyPlayerRunning() {
  15. return myPlayerIndex == gameLogic.currentPlayerIndex;
  16. }
  17. public PKGameMode_OnlinePK(GameMgr gameMgr) : base(gameMgr) {
  18. GlobalData.pkMatchType = PKMatchType.OnlinePK;
  19. if (GameObject.Find("SocketPlayer") == null) {
  20. PKMatchingView.MoniMatchForTestInGameScene(() => {
  21. myPlayerIndex = GlobalData.playerIndexInRoom;
  22. });
  23. } else {
  24. myPlayerIndex = GlobalData.playerIndexInRoom;
  25. }
  26. gameLogic.InitAppearPlayerIndexes();
  27. gameLogic.SetCurrentPlayerIndexToNext();
  28. //记录可射击的靶子
  29. targetBody = GameObject.Find("GameArea/TargetObject/TargetBody").GetComponent<TargetBody>();
  30. GameObject.FindObjectOfType<ArmBow>().validTargets.Add(targetBody);
  31. //添加游戏界面
  32. GameObject view = Resources.Load<GameObject>("Prefabs/Views/PKGameView");
  33. GameObject.Instantiate(view);
  34. //禁止动作-相机和手臂
  35. BanBowReady();
  36. AutoSwitchBanUserControlBow();
  37. socketPlayer = GameObject.Find("SocketPlayer").GetComponent<SocketPlayer>();
  38. socketPlayer.onReceivePKGameData = onReceivePKGameData;
  39. }
  40. Quaternion bowTargetQua;
  41. bool hasBowTargBtQua;
  42. void onReceivePKGameData(string key, string data) {
  43. if (key == "logic") {
  44. GameLogic gameLogic = JsonConvert.DeserializeObject<GameLogic>(data);
  45. if (
  46. (gameLogic.nextPlayerExcuteID == this.gameLogic.nextPlayerExcuteID && myPlayerIndex != gameLogic.currentPlayerIndex) ||
  47. (gameLogic.nextPlayerExcuteID > this.gameLogic.nextPlayerExcuteID)
  48. ) {
  49. this.gameLogic = gameLogic;
  50. AutoSwitchBanUserControlBow();
  51. }
  52. }
  53. if (key == "bow") {
  54. if (!IsMyPlayerRunning()) {
  55. string[] quaStr = data.Split(',');
  56. if (quaStr.Length == 6) {
  57. bowTargetQua.x = float.Parse(quaStr[0]);
  58. bowTargetQua.y = float.Parse(quaStr[1]);
  59. bowTargetQua.z = float.Parse(quaStr[2]);
  60. bowTargetQua.w = float.Parse(quaStr[3]);
  61. hasBowTargBtQua = true;
  62. ArmBow.ins.phase = int.Parse(quaStr[4]);
  63. GameAssistUI.ins.playerScaleAimValue_OnlinePK = int.Parse(quaStr[5]);
  64. }
  65. }
  66. }
  67. if (key == "arrow") {
  68. List<ArrowSync.SyncData> arrowSyncDataList = JsonConvert.DeserializeObject<List<ArrowSync.SyncData>>(data);
  69. foreach (var item in arrowSyncMap) {
  70. item.Value.hasSetSyncData = false;
  71. }
  72. GameObject arrowPrefab = ArmBow.ins.arrow;
  73. foreach (var item in arrowSyncDataList) {
  74. ArrowSync arrowSync;
  75. arrowSyncMap.TryGetValue(item.id, out arrowSync);
  76. if (arrowSync == null) {
  77. GameObject arrowObj = GameObject.Instantiate(arrowPrefab);
  78. arrowSync = arrowObj.AddComponent<ArrowSync>();
  79. arrowSync.SetSyncData(item, true);
  80. arrowSyncMap[item.id] = arrowSync;
  81. } else {
  82. arrowSync.SetSyncData(item);
  83. }
  84. arrowSync.hasSetSyncData = true;
  85. }
  86. List<int> removeIDs = null;
  87. foreach (var item in arrowSyncMap) {
  88. if (!item.Value.hasSetSyncData) {
  89. if (removeIDs == null) removeIDs = new List<int>();
  90. removeIDs.Add(item.Key);
  91. }
  92. }
  93. if (removeIDs != null) {
  94. foreach (var id in removeIDs) {
  95. ArrowSync arrowSync = arrowSyncMap[id];
  96. arrowSyncMap.Remove(id);
  97. if (arrowSync && arrowSync.gameObject) {
  98. GameObject.Destroy(arrowSync.gameObject);
  99. }
  100. }
  101. }
  102. }
  103. if (key == "score") {
  104. HitTargetNumber.Create(float.Parse(data));
  105. }
  106. }
  107. void AutoSwitchBanUserControlBow() {
  108. BowCamera.ins.banLogic = ArmBow.ins.banLogic = !IsMyPlayerRunning();
  109. }
  110. //记录可射击的靶子
  111. TargetBody targetBody;
  112. bool hasStart = false;
  113. public override void Start() {
  114. hasStart = true;
  115. TargetView.ins.Show(true);
  116. }
  117. void AddReadyView()
  118. {
  119. GameObject view = Resources.Load<GameObject>("Prefabs/Views/PKGameReadyView");
  120. GameObject.Instantiate(view);
  121. }
  122. public override void HitTarget(float score) {
  123. gameLogic.HitTarget(score);
  124. HitTargetNumber.Create(score);
  125. scoreWillSend = score.ToString();
  126. }
  127. public override bool DoNextShoot() {
  128. return gameLogic.DoNextShoot(this);
  129. }
  130. public override object[] Settle() {
  131. return gameLogic.gameRes;
  132. }
  133. float uploadGameDataTime = 0;
  134. float uploadBowTime = 0;
  135. public override void Update() {
  136. if (!IsMyPlayerInited()) return;
  137. if (!hasStart) return;
  138. AutoSwitchBanUserControlBow();
  139. if (IsMyPlayerRunning()) {
  140. gameLogic.Update(this);
  141. upload1();
  142. }
  143. upload2();
  144. gameDisplay.Update(this);
  145. if (this.gameLogic.gameEnd) {
  146. socketPlayer.canBackHome = false;
  147. }
  148. }
  149. Dictionary<int, ArrowSync> arrowSyncMap = new Dictionary<int, ArrowSync>();
  150. void upload1() {
  151. uploadBowTime -= Time.deltaTime;
  152. if (uploadBowTime <= 0) {
  153. uploadBowTime = 0.033f;
  154. Quaternion qua = BowCamera.ins.transform.rotation;
  155. int aimScaleValue = GameAssistUI.ins.aimScaleValue;
  156. if (!GameAssistUI.ins.scaleAimOn) aimScaleValue = 0;
  157. socketPlayer.UploadPKGameData("bow", qua.x + "," + qua.y + "," + qua.z + "," + qua.w + "," + ArmBow.ins.phase + "," + aimScaleValue);
  158. }
  159. }
  160. string scoreWillSend = null;
  161. void upload2() {
  162. uploadGameDataTime -= Time.deltaTime;
  163. if (uploadGameDataTime <= 0) {
  164. uploadGameDataTime = 0.033f;
  165. socketPlayer.UploadPKGameData("logic", gameLogic);
  166. List<ArrowSync.SyncData> arrowSyncDataList = new List<ArrowSync.SyncData>();
  167. foreach (var item in Arrow.arrowSet) {
  168. if (item.outputSyncData == null || !item.outputSyncData.inited) continue;
  169. arrowSyncDataList.Add(item.outputSyncData);
  170. }
  171. socketPlayer.UploadPKGameData("arrow", arrowSyncDataList);
  172. if (scoreWillSend != null) {
  173. socketPlayer.UploadPKGameData("score", scoreWillSend);
  174. scoreWillSend = null;
  175. }
  176. }
  177. }
  178. public override void onBowReady() {
  179. if (!IsMyPlayerRunning()) return;
  180. gameLogic.singleShootReadyTime = gameLogic.singleShootReadyMaxTime;
  181. gameLogic.singleShootTimeRunning = true;
  182. }
  183. public override void onBowShoot() {
  184. if (!IsMyPlayerRunning()) return;
  185. gameLogic.singleShootTimeRunning = false;
  186. }
  187. //gamelogic-data
  188. public GameLogic gameLogic = new GameLogic();
  189. public class GameLogic {
  190. public int currentPlayerIndex = 0;
  191. public int[] totalScores = {0, 0};
  192. public float[] currentScores = {0, 0};
  193. public int round = 1;
  194. public int maxRound = 5;
  195. public int[] shootCount = {0, 0};
  196. public int maxShootCount = 3;
  197. public float singleShootReadyTime = 20;
  198. public float singleShootReadyMaxTime = 20;
  199. public bool singleShootTimeRunning = false;
  200. public string[] gameRes = {"平局", "平局"};
  201. public bool gameEnd = false;
  202. //玩家出场顺序
  203. public Queue<int> appearPlayerIndexes = new Queue<int>();
  204. public int[] sequencePlayerIndexes = new int[]{0, 1};
  205. public int nextPlayerExcuteID = 0;
  206. public void InitAppearPlayerIndexes()
  207. {
  208. if (round >= 2)
  209. {
  210. if (totalScores[0] < totalScores[1])
  211. {
  212. sequencePlayerIndexes = new int[]{0, 1};
  213. }
  214. else if (totalScores[1] < totalScores[0])
  215. {
  216. sequencePlayerIndexes = new int[]{1, 0};
  217. }
  218. }
  219. for (int i = 0; i < maxShootCount; i++) {
  220. appearPlayerIndexes.Enqueue(sequencePlayerIndexes[0]);
  221. appearPlayerIndexes.Enqueue(sequencePlayerIndexes[1]);
  222. }
  223. }
  224. public void SetCurrentPlayerIndexToNext() {
  225. currentPlayerIndex = appearPlayerIndexes.Dequeue();
  226. nextPlayerExcuteID++;
  227. }
  228. public void Update(PKGameMode_OnlinePK gm) {
  229. if (singleShootTimeRunning && !gm.pauseTimeCounting) {
  230. singleShootReadyTime -= Time.deltaTime;
  231. if (singleShootReadyTime <= 0) {
  232. singleShootReadyTime = 0;
  233. singleShootTimeRunning = false;
  234. HitTarget(0);
  235. // BanBowReady();
  236. // //超时显示
  237. // Text timeoutText = PKGameView.ins.transform.Find("TimeoutText").GetComponent<Text>();
  238. // Sequence seq = DOTween.Sequence();
  239. // seq.Append(timeoutText.DOFade(1, 0.5f));
  240. // seq.AppendInterval(1);
  241. // seq.Append(timeoutText.DOFade(0, 0.5f));
  242. // seq.AppendCallback(delegate(){
  243. // if (DoNextShoot()) {
  244. // UnbanBowReady();
  245. // }
  246. // });
  247. DoNextShoot(gm);
  248. }
  249. }
  250. }
  251. public void HitTarget(float score) {
  252. currentScores[currentPlayerIndex] += score;
  253. shootCount[currentPlayerIndex]++;
  254. }
  255. public bool DoNextShoot(PKGameMode_OnlinePK gm) {
  256. if (gm.gameMgr.gameOver) return false;
  257. bool nextRound = false;
  258. if (shootCount[0] == maxShootCount && shootCount[1] == maxShootCount ) {
  259. shootCount = new int[]{0, 0};
  260. nextRound = true;
  261. //更新总比分
  262. if (currentScores[0] == currentScores[1]) {
  263. totalScores[0] += 1;
  264. totalScores[1] += 1;
  265. } else if (currentScores[0] > currentScores[1]) {
  266. totalScores[0] += 2;
  267. } else if (currentScores[0] < currentScores[1]) {
  268. totalScores[1] += 2;
  269. }
  270. //根据总比分判断游戏是否结束
  271. if (totalScores[0] == totalScores[1]) {
  272. if (round == maxRound) {
  273. if (round == 5) {
  274. maxShootCount = 1;
  275. maxRound = 6;
  276. } else {
  277. gameEnd = true;
  278. gameRes = new string[]{"平局", "平局"};
  279. }
  280. }
  281. } else if (totalScores[0] >= 6 && totalScores[0] > totalScores[1]) {
  282. gameEnd = true;
  283. gameRes = new string[]{"胜利", "失败"};
  284. } else if (totalScores[1] >= 6 && totalScores[1] > totalScores[0]) {
  285. gameEnd = true;
  286. gameRes = new string[]{"失败", "胜利"};
  287. }
  288. }
  289. if (gameEnd) {
  290. return false;
  291. } else {
  292. //进入下一回合?
  293. if (nextRound) {
  294. round++;
  295. currentScores[0] = currentScores[1] = 0;
  296. InitAppearPlayerIndexes();
  297. }
  298. //本轮玩家登记
  299. SetCurrentPlayerIndexToNext();
  300. gm.BanBowReady();
  301. }
  302. return true;
  303. }
  304. }
  305. //game-display
  306. public GameDisplay gameDisplay = new GameDisplay();
  307. public class GameDisplay {
  308. readonly float[] targetDistancesOnRound = {10, 20, 30, 50, 70, 70};
  309. public int[] playerRoleIDs = {1, 2};
  310. public int showRoundValueOnReadyView = 0;
  311. #region 用于控制显示更新的变量
  312. int round = 0;
  313. int nextPlayerExcuteID = 0;
  314. bool gameEnd = false;
  315. #endregion
  316. public void Update(PKGameMode_OnlinePK gm) {
  317. if (round != gm.gameLogic.round) {
  318. round = gm.gameLogic.round;
  319. gm.targetBody.SetDistance(targetDistancesOnRound[round - 1]);
  320. }
  321. if (nextPlayerExcuteID != gm.gameLogic.nextPlayerExcuteID) {
  322. nextPlayerExcuteID = gm.gameLogic.nextPlayerExcuteID;
  323. gm.BanBowReady();
  324. gm.AddReadyView();
  325. //清除箭矢
  326. foreach (var arrow in Arrow.arrowSet) {
  327. try {
  328. GameObject.Destroy(arrow.gameObject);
  329. } catch (UnityException e) {
  330. Debug.Log("Delete Arrow Error\n" + e.Message);
  331. }
  332. }
  333. }
  334. if (!gameEnd && gm.gameLogic.gameEnd) {
  335. gameEnd = true;
  336. gm.gameMgr.StopGame();
  337. GameObject view = Resources.Load<GameObject>("Prefabs/Views/PKGameSettleView");
  338. GameObject.Instantiate(view);
  339. }
  340. if (!gm.IsMyPlayerRunning() && gm.hasBowTargBtQua) {
  341. BowCamera.ins.transform.rotation = Quaternion.Lerp(BowCamera.ins.transform.rotation, gm.bowTargetQua, Time.deltaTime * 12);
  342. }
  343. }
  344. }
  345. }