GameMgr.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using DG.Tweening;
  5. using UnityEngine.UI;
  6. using UnityEngine.SceneManagement;
  7. /* 游戏管理者(游戏模式:单人模式、PK模式) */
  8. public class GameMgr : MonoBehaviour
  9. {
  10. public static bool debugInEditor = false;
  11. public static int gameType = 9;
  12. public GameMode gameMode;
  13. [System.NonSerialized] public bool gameOver = false;
  14. public static GameMgr ins;
  15. void Awake()
  16. {
  17. ins = this;
  18. HomeMgr.HideCacheViews();
  19. if (Application.platform == RuntimePlatform.WindowsEditor)
  20. {
  21. debugInEditor = true;
  22. }
  23. AudioMgr.Init();
  24. this.InitGameMode();
  25. if (debugInEditor) {
  26. guideFinish = true;
  27. gameMode.Start();
  28. } else {
  29. if (!BluetoothStatus.IsAllConnected()) {
  30. GameObject view = DeviceReconnectView.Show();
  31. if (view) {
  32. view.GetComponent<DeviceReconnectView>().onComplete = CheckGuide;
  33. }
  34. } else {
  35. this.CheckGuide();
  36. }
  37. }
  38. // GameSceneLoadBtns.Create();
  39. }
  40. void Start()
  41. {
  42. try {
  43. GlobalEventCenter.ins.onGameSceneLoad?.Invoke();
  44. } catch (System.Exception e) { Debug.LogError(e.Message); }
  45. if (ShootCheck.ins) ShootCheck.ins.AdjustNormalOrHightMode();
  46. }
  47. void OnDestroy() {
  48. try {
  49. GlobalEventCenter.ins.onGameSceneDestroy?.Invoke();
  50. } catch (System.Exception e) { Debug.LogError(e.Message); }
  51. if (AimHandler.ins) AimHandler.ins.BanControlObjRotate(false);
  52. }
  53. void FixedUpdate()
  54. {
  55. gameMode.Update();
  56. }
  57. void InitGameMode() {
  58. if (gameType == 0) gameMode = new GameModeTest(this);
  59. if (gameType == 1) gameMode = new TimeLimitGameMode(this);
  60. if (gameType == 2) gameMode = new PKGameMode(this);
  61. if (gameType == 3) gameMode = new RabbitHuntGameMode(this);
  62. if (gameType == 4) gameMode = new YejiHuntGameMode(this);
  63. if (gameType == 5) gameMode = new WolfHuntGameMode(this);
  64. if (gameType == 6) gameMode = new RabbitHuntGameMode_LocalPK(this);
  65. if (gameType == 7) gameMode = new YejiHuntGameMode_LocalPK(this);
  66. if (gameType == 8) gameMode = new WolfHuntGameMode_LocalPK(this);
  67. if (gameType == 9) gameMode = new PKGameMode_OnlinePK(this);
  68. }
  69. public void StopGame() {
  70. gameOver = true;
  71. if (BowCamera.ins) BowCamera.ins.enabled = false;
  72. Arrow[] arrows = GameObject.FindObjectsOfType<Arrow>();
  73. foreach(var arrow in arrows)
  74. {
  75. Destroy(arrow);
  76. }
  77. }
  78. bool guideFinish = false;
  79. public void CheckGuide() {
  80. if (gameType > 0) {
  81. if (!LoginMgr.myUserInfo.deviceCalibrateGuideFinish) {
  82. DeviceCalibrateView.Create();
  83. return;
  84. }
  85. if (gameType < 3) {
  86. bool gameRuleGuideFinish = (bool)LoginMgr.myUserInfo.GetType().GetField($"gameRule{GameMgr.gameType}GuideFinish").GetValue(LoginMgr.myUserInfo);
  87. if (!gameRuleGuideFinish) {
  88. GameRuleView.Create();
  89. return;
  90. }
  91. }
  92. }
  93. guideFinish = true;
  94. gameMode.Start();
  95. }
  96. public void FinishGameRuleGuide() {
  97. if (guideFinish) return;
  98. LoginMgr.myUserInfo.GetType().GetField($"gameRule{GameMgr.gameType}GuideFinish").SetValue(LoginMgr.myUserInfo, true);
  99. LoginMgr.myUserInfo.Save();
  100. CheckGuide();
  101. }
  102. public void FinishDeviceCalibrateGuide() {
  103. if (guideFinish) return;
  104. LoginMgr.myUserInfo.deviceCalibrateGuideFinish = true;
  105. LoginMgr.myUserInfo.Save();
  106. CheckGuide();
  107. }
  108. HashSet<Object> gamePauseLockers = new HashSet<Object>();
  109. public bool gamePause {
  110. get {
  111. return gamePauseLockers.Count > 0;
  112. }
  113. }
  114. public void addLockerForGamePause(Object o)
  115. {
  116. gamePauseLockers.Add(o);
  117. if (gamePauseLockers.Count > 0) {
  118. Time.timeScale = 0;
  119. }
  120. }
  121. public void removeLockerForGamePause(Object o)
  122. {
  123. gamePauseLockers.Remove(o);
  124. if (gamePauseLockers.Count == 0) {
  125. Time.timeScale = 1;
  126. }
  127. }
  128. //现实的计量值转游戏场景的计量值(米)
  129. public static float RealSizeToGameSize(float realSize)
  130. {
  131. // return realSize * 0.413966f;
  132. return realSize;
  133. }
  134. //游戏场景的计量值转现实的计量值(米)
  135. public static float GameSizeToRealSize(float gameSize)
  136. {
  137. // return gameSize / 0.413966f;
  138. return gameSize;
  139. }
  140. }
  141. public abstract class GameMode
  142. {
  143. public GameMgr gameMgr;
  144. public bool pauseTimeCounting {
  145. get {
  146. return timeCountingPauseLockers.Count > 0;
  147. }
  148. }
  149. HashSet<System.Object> timeCountingPauseLockers = new HashSet<System.Object>();
  150. public void PauseTimeCounting(System.Object o)
  151. {
  152. timeCountingPauseLockers.Add(o);
  153. }
  154. public void ResumeTimeCounting(System.Object o)
  155. {
  156. timeCountingPauseLockers.Remove(o);
  157. }
  158. public GameMode(GameMgr gameMgr) {
  159. this.gameMgr = gameMgr;
  160. }
  161. public virtual void HitTarget(float score) {}
  162. public virtual bool DoNextShoot() { return true; }
  163. public virtual object[] Settle() {return null; }
  164. public virtual void Start() {}
  165. public virtual void Update() {}
  166. public virtual void onBowReady() {}
  167. public virtual void onBowShoot() {}
  168. public void BanBowReady() {
  169. PauseTimeCounting(this);
  170. ArmBow armBow = GameObject.FindObjectOfType<ArmBow>();
  171. armBow.banReady = true;
  172. armBow.banShoot = true;
  173. }
  174. public void UnbanBowReady() {
  175. ResumeTimeCounting(this);
  176. ArmBow armBow = GameObject.FindObjectOfType<ArmBow>();
  177. armBow.banReady = false;
  178. armBow.banShoot = false;
  179. GameObject.FindObjectOfType<ArmBow>().readyShoot();
  180. }
  181. }
  182. public class GameModeTest : GameMode {
  183. public GameModeTest(GameMgr gameMgr) : base(gameMgr) {
  184. //记录可射击的靶子
  185. if (SceneManager.GetActiveScene().name == "Game") {
  186. TargetBody targetBody = GameObject.Find("GameArea/TargetObject/TargetBody").GetComponent<TargetBody>();
  187. GameObject.FindObjectOfType<ArmBow>().validTargets.Add(targetBody);
  188. }
  189. }
  190. public override void HitTarget(float score) {
  191. HitTargetNumber.Create(score);
  192. }
  193. }
  194. /**单人限时模式 */
  195. public class TimeLimitGameMode : GameMode {
  196. public static int[] distanceCanSelected = {10, 20, 30, 50, 70};
  197. public static int distance = 10;
  198. public float score = 0;
  199. int oneStarScore = 10;
  200. float time = 60;
  201. TargetBody targetBody;
  202. public TimeLimitGameMode(GameMgr gameMgr) : base(gameMgr) {
  203. //记录可射击的靶子
  204. targetBody = GameObject.Find("GameArea/TargetObject/TargetBody").GetComponent<TargetBody>();
  205. GameObject.FindObjectOfType<ArmBow>().validTargets.Add(targetBody);
  206. //添加游戏界面
  207. GameObject view = Resources.Load<GameObject>("Prefabs/Views/TimeLimitGameView");
  208. GameObject.Instantiate(view);
  209. BanBowReady();
  210. }
  211. public override void Start()
  212. {
  213. UnbanBowReady();
  214. GameObject.Instantiate(Resources.Load<GameObject>("Prefabs/Views/TimeLimitGameDistanceSelectView"));
  215. }
  216. public void ConfirmSelectedTargetDistance()
  217. {
  218. targetBody.SetDistance(distance);
  219. if (TimeLimitGameView.ins) TimeLimitGameView.ins.RenderHighestScoreByDistance(distance);
  220. TargetView.ins.Show(true);
  221. }
  222. public override void HitTarget(float score) {
  223. this.score += score;
  224. HitTargetNumber.Create(score);
  225. }
  226. public override bool DoNextShoot() {
  227. return !GameMgr.ins.gameOver;
  228. }
  229. public override object[] Settle() {
  230. int starCount = Mathf.FloorToInt(this.score / this.oneStarScore);
  231. float highestScore = 0;
  232. string distanceStr = distance.ToString();
  233. System.Object highestScoreObj = LoginMgr.myUserInfo.timeLimitGameHighestScores[distanceStr];
  234. if (highestScoreObj != null) highestScore = float.Parse(highestScoreObj.ToString());
  235. if (this.score > highestScore) {
  236. LoginMgr.myUserInfo.timeLimitGameHighestScores.Remove(distanceStr);
  237. LoginMgr.myUserInfo.timeLimitGameHighestScores.Add(distanceStr, this.score);
  238. LoginMgr.myUserInfo.Save();
  239. }
  240. return new object[]{starCount, this.score};
  241. }
  242. public override void Update() {
  243. if (gameMgr.gameOver || pauseTimeCounting) return;
  244. if (this.time > 0) {
  245. this.time -= Time.deltaTime;
  246. } else {
  247. this.time = 0;
  248. gameMgr.StopGame();
  249. //添加结算界面
  250. GameObject view = Resources.Load<GameObject>("Prefabs/Views/TimeLimitGameSettleView");
  251. GameObject.Instantiate(view);
  252. }
  253. }
  254. public string GetTimeStr()
  255. {
  256. int seconds = (int) Mathf.Ceil(this.time);
  257. string str = "";
  258. int m = seconds / 60;
  259. if (m < 10) {
  260. str += 0;
  261. }
  262. str += m;
  263. str += " : ";
  264. int s = seconds % 60;
  265. if (s < 10)
  266. {
  267. str += 0;
  268. }
  269. str += s;
  270. return str;
  271. }
  272. }
  273. /**双人PK模式 */
  274. public class PKGameMode : GameMode {
  275. public int currentPlayerIndex = 0;
  276. public int[] totalScores = {0, 0};
  277. public float[] currentScores = {0, 0};
  278. public int round = 1;
  279. public int showRoundValue = 0; //回合开始提示值,如果已经提示,则showRoundValue == round
  280. float[] targetDistancesOnRound = {10, 20, 30, 50, 70, 70};
  281. int maxRound = 5;
  282. int[] shootCount = {0, 0};
  283. int maxShootCount = 3;
  284. public float singleShootReadyTime = 20;
  285. public float singleShootReadyMaxTime = 20;
  286. bool singleShootTimeRunning = false;
  287. public static int[] playerRoleIDs = {1, 2};
  288. string[] gameRes = {"平局", "平局"};
  289. //玩家出场顺序
  290. Queue<int> appearPlayerIndexes = new Queue<int>();
  291. //记录可射击的靶子
  292. TargetBody targetBody;
  293. public PKGameMode(GameMgr gameMgr) : base(gameMgr) {
  294. playerRoleIDs = GlobalData.localPK_playerRoleIDs;
  295. InitAppearPlayerIndexes();
  296. currentPlayerIndex = appearPlayerIndexes.Dequeue();
  297. //记录可射击的靶子
  298. targetBody = GameObject.Find("GameArea/TargetObject/TargetBody").GetComponent<TargetBody>();
  299. GameObject.FindObjectOfType<ArmBow>().validTargets.Add(targetBody);
  300. targetBody.SetDistance(targetDistancesOnRound[round - 1]);
  301. //添加游戏界面
  302. GameObject view = Resources.Load<GameObject>("Prefabs/Views/PKGameView");
  303. GameObject.Instantiate(view);
  304. //禁止动作-相机和手臂
  305. BanBowReady();
  306. }
  307. public override void Start() {
  308. TargetView.ins.Show(true);
  309. //添加预备界面
  310. AddReadyView();
  311. }
  312. int[] sequencePlayerIndexes = new int[]{0, 1};
  313. void InitAppearPlayerIndexes()
  314. {
  315. if (round >= 2)
  316. {
  317. if (totalScores[0] < totalScores[1])
  318. {
  319. sequencePlayerIndexes = new int[]{0, 1};
  320. }
  321. else if (totalScores[1] < totalScores[0])
  322. {
  323. sequencePlayerIndexes = new int[]{1, 0};
  324. }
  325. }
  326. for (int i = 0; i < maxShootCount; i++) {
  327. appearPlayerIndexes.Enqueue(sequencePlayerIndexes[0]);
  328. appearPlayerIndexes.Enqueue(sequencePlayerIndexes[1]);
  329. }
  330. }
  331. void AddReadyView()
  332. {
  333. GameObject view = Resources.Load<GameObject>("Prefabs/Views/PKGameReadyView");
  334. GameObject.Instantiate(view);
  335. }
  336. public override void HitTarget(float score) {
  337. currentScores[currentPlayerIndex] += score;
  338. shootCount[currentPlayerIndex]++;
  339. HitTargetNumber.Create(score);
  340. }
  341. public override bool DoNextShoot() {
  342. if (gameMgr.gameOver) return false;
  343. bool nextRound = false;
  344. bool gameEnd = false; //游戏是否结束
  345. if (shootCount[0] == maxShootCount && shootCount[1] == maxShootCount ) {
  346. shootCount = new int[]{0, 0};
  347. nextRound = true;
  348. //更新总比分
  349. if (currentScores[0] == currentScores[1]) {
  350. totalScores[0] += 1;
  351. totalScores[1] += 1;
  352. } else if (currentScores[0] > currentScores[1]) {
  353. totalScores[0] += 2;
  354. } else if (currentScores[0] < currentScores[1]) {
  355. totalScores[1] += 2;
  356. }
  357. //根据总比分判断游戏是否结束
  358. if (totalScores[0] == totalScores[1]) {
  359. if (round == maxRound) {
  360. if (round == 5) {
  361. maxShootCount = 1;
  362. maxRound = 6;
  363. } else {
  364. gameEnd = true;
  365. gameRes = new string[]{"平局", "平局"};
  366. }
  367. }
  368. } else if (totalScores[0] >= 6 && totalScores[0] > totalScores[1]) {
  369. gameEnd = true;
  370. gameRes = new string[]{"胜利", "失败"};
  371. } else if (totalScores[1] >= 6 && totalScores[1] > totalScores[0]) {
  372. gameEnd = true;
  373. gameRes = new string[]{"失败", "胜利"};
  374. }
  375. }
  376. if (gameEnd) {
  377. gameMgr.StopGame();
  378. GameObject view = Resources.Load<GameObject>("Prefabs/Views/PKGameSettleView");
  379. GameObject.Instantiate(view);
  380. return false;
  381. } else {
  382. //进入下一回合?
  383. if (nextRound) {
  384. round++;
  385. currentScores[0] = currentScores[1] = 0;
  386. InitAppearPlayerIndexes();
  387. targetBody.SetDistance(targetDistancesOnRound[round - 1]);
  388. }
  389. //本轮玩家登记
  390. currentPlayerIndex = appearPlayerIndexes.Dequeue();
  391. //准备切换玩家
  392. BanBowReady();
  393. AddReadyView();
  394. //清除箭矢
  395. Arrow[] arrows = GameObject.FindObjectsOfType<Arrow>();
  396. foreach (var arrow in arrows)
  397. {
  398. try {
  399. GameObject.Destroy(arrow.gameObject);
  400. } catch (UnityException e) {
  401. Debug.Log("Delete Arrow Error\n" + e.Message);
  402. }
  403. }
  404. }
  405. return true;
  406. }
  407. public override object[] Settle() {
  408. return gameRes;
  409. }
  410. public override void Update() {
  411. if (singleShootTimeRunning && !pauseTimeCounting) {
  412. singleShootReadyTime -= Time.deltaTime;
  413. if (singleShootReadyTime <= 0) {
  414. singleShootReadyTime = 0;
  415. singleShootTimeRunning = false;
  416. HitTarget(0);
  417. BanBowReady();
  418. //超时显示
  419. Text timeoutText = PKGameView.ins.transform.Find("TimeoutText").GetComponent<Text>();
  420. Sequence seq = DOTween.Sequence();
  421. seq.Append(timeoutText.DOFade(1, 0.5f));
  422. seq.AppendInterval(1);
  423. seq.Append(timeoutText.DOFade(0, 0.5f));
  424. seq.AppendCallback(delegate(){
  425. if (DoNextShoot()) {
  426. UnbanBowReady();
  427. }
  428. });
  429. }
  430. }
  431. }
  432. public string GetTimeStr()
  433. {
  434. int seconds = (int) Mathf.Ceil(this.singleShootReadyTime);
  435. string str = "";
  436. int m = seconds / 60;
  437. if (m < 10) {
  438. str += 0;
  439. }
  440. str += m;
  441. str += " : ";
  442. int s = seconds % 60;
  443. if (s < 10)
  444. {
  445. str += 0;
  446. }
  447. str += s;
  448. return str;
  449. }
  450. public override void onBowReady() {
  451. singleShootReadyTime = singleShootReadyMaxTime;
  452. singleShootTimeRunning = true;
  453. }
  454. public override void onBowShoot() {
  455. singleShootTimeRunning = false;
  456. }
  457. }