PKGameMode_OnlinePK.cs 14 KB

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