PKGameMode_OnlinePK.cs 14 KB

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