PKGameMode_OnlinePK.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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 == 5) {
  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. }
  64. }
  65. }
  66. if (key == "arrow") {
  67. List<ArrowSync.SyncData> arrowSyncDataList = JsonConvert.DeserializeObject<List<ArrowSync.SyncData>>(data);
  68. foreach (var item in arrowSyncMap) {
  69. item.Value.hasSetSyncData = false;
  70. }
  71. GameObject arrowPrefab = ArmBow.ins.arrow;
  72. foreach (var item in arrowSyncDataList) {
  73. ArrowSync arrowSync;
  74. arrowSyncMap.TryGetValue(item.id, out arrowSync);
  75. if (arrowSync == null) {
  76. GameObject arrowObj = GameObject.Instantiate(arrowPrefab);
  77. arrowSync = arrowObj.AddComponent<ArrowSync>();
  78. arrowSync.SetSyncData(item, true);
  79. arrowSyncMap[item.id] = arrowSync;
  80. } else {
  81. arrowSync.SetSyncData(item);
  82. }
  83. arrowSync.hasSetSyncData = true;
  84. }
  85. List<int> removeIDs = null;
  86. foreach (var item in arrowSyncMap) {
  87. if (!item.Value.hasSetSyncData) {
  88. if (removeIDs == null) removeIDs = new List<int>();
  89. removeIDs.Add(item.Key);
  90. }
  91. }
  92. if (removeIDs != null) {
  93. foreach (var id in removeIDs) {
  94. ArrowSync arrowSync = arrowSyncMap[id];
  95. arrowSyncMap.Remove(id);
  96. if (arrowSync && arrowSync.gameObject) {
  97. GameObject.Destroy(arrowSync.gameObject);
  98. }
  99. }
  100. }
  101. }
  102. if (key == "score") {
  103. HitTargetNumber.Create(float.Parse(data));
  104. AudioMgr.ins.PlayHit(AudioMgr.GetAudioSource(TargetBody.ins.gameObject));
  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.1f;
  154. Quaternion qua = BowCamera.ins.transform.rotation;
  155. socketPlayer.UploadPKGameData("bow", qua.x + "," + qua.y + "," + qua.z + "," + qua.w + "," + ArmBow.ins.phase);
  156. }
  157. }
  158. string scoreWillSend = null;
  159. void upload2() {
  160. uploadGameDataTime -= Time.deltaTime;
  161. if (uploadGameDataTime <= 0) {
  162. uploadGameDataTime = 0.05f;
  163. socketPlayer.UploadPKGameData("logic", gameLogic);
  164. List<ArrowSync.SyncData> arrowSyncDataList = new List<ArrowSync.SyncData>();
  165. foreach (var item in Arrow.arrowSet) {
  166. if (item.outputSyncData == null || !item.outputSyncData.inited) continue;
  167. arrowSyncDataList.Add(item.outputSyncData);
  168. }
  169. socketPlayer.UploadPKGameData("arrow", arrowSyncDataList);
  170. if (scoreWillSend != null) {
  171. socketPlayer.UploadPKGameData("score", scoreWillSend);
  172. scoreWillSend = null;
  173. }
  174. }
  175. }
  176. public override void onBowReady() {
  177. if (!IsMyPlayerRunning()) return;
  178. gameLogic.singleShootReadyTime = gameLogic.singleShootReadyMaxTime;
  179. gameLogic.singleShootTimeRunning = true;
  180. }
  181. public override void onBowShoot() {
  182. if (!IsMyPlayerRunning()) return;
  183. gameLogic.singleShootTimeRunning = false;
  184. }
  185. //gamelogic-data
  186. public GameLogic gameLogic = new GameLogic();
  187. public class GameLogic {
  188. public int currentPlayerIndex = 0;
  189. public int[] totalScores = {0, 0};
  190. public float[] currentScores = {0, 0};
  191. public int round = 1;
  192. public int maxRound = 5;
  193. public int[] shootCount = {0, 0};
  194. public int maxShootCount = 3;
  195. public float singleShootReadyTime = 20;
  196. public float singleShootReadyMaxTime = 20;
  197. public bool singleShootTimeRunning = false;
  198. public string[] gameRes = {"平局", "平局"};
  199. public bool gameEnd = false;
  200. //玩家出场顺序
  201. public Queue<int> appearPlayerIndexes = new Queue<int>();
  202. public int[] sequencePlayerIndexes = new int[]{0, 1};
  203. public int nextPlayerExcuteID = 0;
  204. public void InitAppearPlayerIndexes()
  205. {
  206. if (round >= 2)
  207. {
  208. if (totalScores[0] < totalScores[1])
  209. {
  210. sequencePlayerIndexes = new int[]{0, 1};
  211. }
  212. else if (totalScores[1] < totalScores[0])
  213. {
  214. sequencePlayerIndexes = new int[]{1, 0};
  215. }
  216. }
  217. for (int i = 0; i < maxShootCount; i++) {
  218. appearPlayerIndexes.Enqueue(sequencePlayerIndexes[0]);
  219. appearPlayerIndexes.Enqueue(sequencePlayerIndexes[1]);
  220. }
  221. }
  222. public void SetCurrentPlayerIndexToNext() {
  223. currentPlayerIndex = appearPlayerIndexes.Dequeue();
  224. nextPlayerExcuteID++;
  225. }
  226. public void Update(PKGameMode_OnlinePK gm) {
  227. if (singleShootTimeRunning && !gm.pauseTimeCounting) {
  228. singleShootReadyTime -= Time.deltaTime;
  229. if (singleShootReadyTime <= 0) {
  230. singleShootReadyTime = 0;
  231. singleShootTimeRunning = false;
  232. HitTarget(0);
  233. // BanBowReady();
  234. // //超时显示
  235. // Text timeoutText = PKGameView.ins.transform.Find("TimeoutText").GetComponent<Text>();
  236. // Sequence seq = DOTween.Sequence();
  237. // seq.Append(timeoutText.DOFade(1, 0.5f));
  238. // seq.AppendInterval(1);
  239. // seq.Append(timeoutText.DOFade(0, 0.5f));
  240. // seq.AppendCallback(delegate(){
  241. // if (DoNextShoot()) {
  242. // UnbanBowReady();
  243. // }
  244. // });
  245. DoNextShoot(gm);
  246. }
  247. }
  248. }
  249. public void HitTarget(float score) {
  250. currentScores[currentPlayerIndex] += score;
  251. shootCount[currentPlayerIndex]++;
  252. }
  253. public bool DoNextShoot(PKGameMode_OnlinePK gm) {
  254. if (gm.gameMgr.gameOver) return false;
  255. bool nextRound = false;
  256. if (shootCount[0] == maxShootCount && shootCount[1] == maxShootCount ) {
  257. shootCount = new int[]{0, 0};
  258. nextRound = true;
  259. //更新总比分
  260. if (currentScores[0] == currentScores[1]) {
  261. totalScores[0] += 1;
  262. totalScores[1] += 1;
  263. } else if (currentScores[0] > currentScores[1]) {
  264. totalScores[0] += 2;
  265. } else if (currentScores[0] < currentScores[1]) {
  266. totalScores[1] += 2;
  267. }
  268. //根据总比分判断游戏是否结束
  269. if (totalScores[0] == totalScores[1]) {
  270. if (round == maxRound) {
  271. if (round == 5) {
  272. maxShootCount = 1;
  273. maxRound = 6;
  274. } else {
  275. gameEnd = true;
  276. gameRes = new string[]{"平局", "平局"};
  277. }
  278. }
  279. } else if (totalScores[0] >= 6 && totalScores[0] > totalScores[1]) {
  280. gameEnd = true;
  281. gameRes = new string[]{"胜利", "失败"};
  282. } else if (totalScores[1] >= 6 && totalScores[1] > totalScores[0]) {
  283. gameEnd = true;
  284. gameRes = new string[]{"失败", "胜利"};
  285. }
  286. }
  287. if (gameEnd) {
  288. return false;
  289. } else {
  290. //进入下一回合?
  291. if (nextRound) {
  292. round++;
  293. currentScores[0] = currentScores[1] = 0;
  294. InitAppearPlayerIndexes();
  295. }
  296. //本轮玩家登记
  297. SetCurrentPlayerIndexToNext();
  298. gm.BanBowReady();
  299. }
  300. return true;
  301. }
  302. }
  303. //game-display
  304. public GameDisplay gameDisplay = new GameDisplay();
  305. public class GameDisplay {
  306. readonly float[] targetDistancesOnRound = {10, 20, 30, 50, 70, 70};
  307. public int[] playerRoleIDs = {1, 2};
  308. public int showRoundValueOnReadyView = 0;
  309. #region 用于控制显示更新的变量
  310. int round = 0;
  311. int nextPlayerExcuteID = 0;
  312. bool gameEnd = false;
  313. #endregion
  314. public void Update(PKGameMode_OnlinePK gm) {
  315. if (round != gm.gameLogic.round) {
  316. round = gm.gameLogic.round;
  317. gm.targetBody.SetDistance(targetDistancesOnRound[round - 1]);
  318. }
  319. if (nextPlayerExcuteID != gm.gameLogic.nextPlayerExcuteID) {
  320. nextPlayerExcuteID = gm.gameLogic.nextPlayerExcuteID;
  321. gm.BanBowReady();
  322. gm.AddReadyView();
  323. //清除箭矢
  324. foreach (var arrow in Arrow.arrowSet) {
  325. try {
  326. GameObject.Destroy(arrow.gameObject);
  327. } catch (UnityException e) {
  328. Debug.Log("Delete Arrow Error\n" + e.Message);
  329. }
  330. }
  331. }
  332. if (!gameEnd && gm.gameLogic.gameEnd) {
  333. gameEnd = true;
  334. gm.gameMgr.StopGame();
  335. GameObject view = Resources.Load<GameObject>("Prefabs/Views/PKGameSettleView");
  336. GameObject.Instantiate(view);
  337. }
  338. if (!gm.IsMyPlayerRunning() && gm.hasBowTargBtQua) {
  339. BowCamera.ins.transform.rotation = Quaternion.Lerp(BowCamera.ins.transform.rotation, gm.bowTargetQua, Time.deltaTime * 12);
  340. }
  341. }
  342. }
  343. }