PKGameMode_OnlinePK.cs 14 KB

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