PKGameMode_OnlinePK.cs 14 KB

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