PKGameMode_OnlinePK.cs 14 KB

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