LobbyManager_RandomMatch.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using Photon.Pun;
  6. using Photon.Realtime;
  7. using UnityEngine.SceneManagement;
  8. using System;
  9. public class LobbyManager_RandomMatch : MonoBehaviourPunCallbacks
  10. {
  11. private static readonly int CloseHash = Animator.StringToHash("Close");
  12. private static readonly int OpenHash = Animator.StringToHash("Open");
  13. private static WaitForSeconds _waitForSeconds0_2 = new WaitForSeconds(0.2f);
  14. private static WaitForSeconds _waitForSeconds0_1 = new WaitForSeconds(0.1f);
  15. private static WaitForSeconds _waitForSeconds0_5 = new WaitForSeconds(0.5f);
  16. private static WaitForSeconds _waitForSeconds1 = new WaitForSeconds(1f);
  17. [Header("message text")]
  18. public Text MessageText;
  19. [Header("time count text")]
  20. public Text TimeText;
  21. [Header("return to title button")]
  22. public GameObject ReturnButton;
  23. [Header("deck info panel")]
  24. public DeckInfoPanel deckInfoPanel;
  25. public Animator anim;
  26. public LoadingObject loadingObject;
  27. public LoadingObject disconnectLoadingObject;
  28. //Room name for an already existing random match room
  29. string RandomRoomName;
  30. bool endLoadingText = false;
  31. private bool isCoroutineRunning = false;
  32. //String that must be included in the random match room
  33. string RandomKey
  34. {
  35. get
  36. {
  37. return "randomMatchRoom";
  38. }
  39. }
  40. //Whether or not a room is being processed
  41. bool startJoin = false;
  42. #region Open Lobby Screen
  43. public void SetUpLobby()
  44. {
  45. Opening.instance.OffYesNoObjects();
  46. Opening.instance.deck.trialDraw.Close();
  47. Opening.instance.deck.deckListPanel.Close();
  48. ContinuousController.instance.isAI = false;
  49. ContinuousController.instance.isRandomMatch = true;
  50. this.gameObject.SetActive(true);
  51. //this.battleRule = battleRule;
  52. ContinuousController.instance.StartCoroutine(ConnectCoroutine());
  53. anim.SetInteger(OpenHash, 1);
  54. anim.SetInteger(CloseHash, 0);
  55. }
  56. #endregion
  57. #region Close Lobby Screen
  58. public void OffLobby()
  59. {
  60. this.gameObject.SetActive(false);
  61. }
  62. #endregion
  63. #region Leave from Random Match Screen
  64. public void CloseLobby()
  65. {
  66. ContinuousController.instance.StartCoroutine(CloseLobbyCoroutine());
  67. }
  68. public IEnumerator CloseLobbyCoroutine()
  69. {
  70. yield return ContinuousController.instance.StartCoroutine(disconnectLoadingObject.StartLoading("Now Loading"));
  71. ReturnButton.SetActive(false);
  72. once1 = true;
  73. DoneCompleteMatching = true;
  74. m = true;
  75. n = true;
  76. #region Leave From Room
  77. if (PhotonNetwork.InRoom)
  78. {
  79. PhotonNetwork.LeaveRoom();
  80. }
  81. yield return new WaitWhile(() => PhotonNetwork.InRoom);
  82. #endregion
  83. yield return ContinuousController.instance.StartCoroutine(PhotonUtility.DisconnectCoroutine());
  84. OffLobby();
  85. yield return ContinuousController.instance.StartCoroutine(disconnectLoadingObject.EndLoading());
  86. }
  87. #endregion
  88. #region 初期化
  89. public IEnumerator Init()
  90. {
  91. n = false;
  92. m = false;
  93. once1 = false;
  94. endLoadingText = false;
  95. isCoroutineRunning = false;
  96. time = 0;
  97. RandomRoomName = "";
  98. startJoin = false;
  99. DoneCompleteMatching = false;
  100. ContinuousController.instance.LoadingTextCoroutine = null;
  101. ReturnButton.SetActive(true);
  102. MessageText.text = "";
  103. TimeText.gameObject.SetActive(true);
  104. StartCoroutine(TimeCountUp());
  105. if (PhotonNetwork.InLobby)
  106. {
  107. PhotonNetwork.LeaveLobby();
  108. }
  109. yield return new WaitWhile(() => PhotonNetwork.InLobby);
  110. if (PhotonNetwork.IsConnected)
  111. {
  112. PhotonNetwork.Disconnect();
  113. }
  114. yield return new WaitWhile(() => PhotonNetwork.IsConnected);
  115. }
  116. #endregion
  117. #region Time text count up
  118. int time = 0;
  119. IEnumerator TimeCountUp()
  120. {
  121. time = 0;
  122. TimeText.gameObject.SetActive(true);
  123. while (!DoneCompleteMatching)
  124. {
  125. string min = (time / 60).ToString();
  126. string sec = (time % 60).ToString();
  127. if (min.Length == 1)
  128. {
  129. min = $"0{min}";
  130. }
  131. if (sec.Length == 1)
  132. {
  133. sec = $"0{sec}";
  134. }
  135. TimeText.text = $"{min}:{sec}";
  136. time++;
  137. yield return _waitForSeconds1;
  138. }
  139. TimeText.gameObject.SetActive(false);
  140. }
  141. #endregion
  142. #region Connect to Photon and Lobby
  143. IEnumerator ConnectCoroutine()
  144. {
  145. //yield return StartCoroutine(loadingObject.StartLoading("Now Loading"));
  146. if (ContinuousController.instance.BattleDeckData != null)
  147. {
  148. _ = deckInfoPanel.SetUpDeckInfoPanel(
  149. ContinuousController.instance.BattleDeckData
  150. );
  151. }
  152. if (ReturnButton != null)
  153. {
  154. ReturnButton.SetActive(false);
  155. }
  156. endLoadingText = true;
  157. yield return ContinuousController.instance.StartCoroutine(Init());
  158. yield return _waitForSeconds0_5;
  159. endLoadingText = false;
  160. ContinuousController.instance.LoadingTextCoroutine = ContinuousController.instance.StartCoroutine(SetWaitingText(
  161. LocalizeUtility.GetLocalizedString(
  162. EngMessage: "Connecting",
  163. JpnMessage: "接続中"
  164. )));
  165. MessageText.transform.localPosition = new Vector3(-180, -193, 0);
  166. yield return ContinuousController.instance.StartCoroutine(PhotonUtility.ConnectToLobbyCoroutine());
  167. yield return ContinuousController.instance.StartCoroutine(PhotonUtility.SignUpBattleDeckData());
  168. yield return _waitForSeconds0_5;
  169. StartRandomMatch();
  170. yield return new WaitWhile(() => !PhotonNetwork.InRoom);
  171. yield return _waitForSeconds0_1;
  172. yield return ContinuousController.instance.StartCoroutine(loadingObject.EndLoading());
  173. ReturnButton.SetActive(true);
  174. }
  175. #endregion
  176. #region ReturnToTitle()
  177. public void ReturnToTitle()
  178. {
  179. SceneManager.LoadSceneAsync("Opening");
  180. DoneCompleteMatching = true;
  181. }
  182. #endregion
  183. #region Callback on room list update
  184. bool m;
  185. bool n;
  186. public override void OnRoomListUpdate(List<RoomInfo> roomList)
  187. {
  188. if (this.gameObject.activeSelf)
  189. {
  190. if (!PhotonNetwork.InRoom && PhotonNetwork.InLobby && !m)
  191. {
  192. m = true;
  193. PhotonNetwork.LeaveLobby();
  194. }
  195. if (!PhotonNetwork.InRoom && PhotonNetwork.InLobby && n)
  196. {
  197. GetRandomMatcingRoom(roomList);
  198. }
  199. }
  200. }
  201. #endregion
  202. #region Search for random matching rooms available
  203. public void GetRandomMatcingRoom(List<RoomInfo> roomInfo)
  204. {
  205. if (startJoin)
  206. {
  207. return;
  208. }
  209. m = false;
  210. n = false;
  211. if (roomInfo == null || roomInfo.Count == 0)
  212. {
  213. return;
  214. }
  215. RandomRoomName = null;
  216. for (int i = 0; i < roomInfo.Count; i++)
  217. {
  218. int p = roomInfo[i].PlayerCount;
  219. string n = roomInfo[i].Name;
  220. int m = roomInfo[i].MaxPlayers;
  221. object c = roomInfo[i].CustomProperties["RoomCreator"];
  222. if (p != 0 && m != 0 && c != null)
  223. {
  224. if (n.Contains(RandomKey))
  225. {
  226. RandomRoomName = n;
  227. }
  228. }
  229. }
  230. }
  231. #endregion
  232. #region Callback when leaving the lobby
  233. public override void OnLeftLobby()
  234. {
  235. if (this.gameObject.activeSelf)
  236. {
  237. if (m)
  238. {
  239. n = true;
  240. PhotonNetwork.JoinLobby();
  241. }
  242. }
  243. }
  244. #endregion
  245. #region Callback when joining a room fails
  246. public override void OnJoinRoomFailed(short returnCode, string message)
  247. {
  248. if (this.gameObject.activeSelf && !DoneCompleteMatching)
  249. {
  250. Debug.Log($"[RandomMatch] Join room failed: [{returnCode}] {message}, retrying...");
  251. RandomRoomName = null;
  252. startJoin = false;
  253. m = false;
  254. n = false;
  255. if (!PhotonNetwork.InLobby)
  256. {
  257. PhotonNetwork.JoinLobby();
  258. }
  259. StartRandomMatch();
  260. }
  261. }
  262. #endregion
  263. #region Process to create a room
  264. public IEnumerator CreateRoomCoroutine(bool isRandomMatch)
  265. {
  266. yield return new WaitWhile(() => !PhotonNetwork.IsConnectedAndReady);
  267. yield return new WaitWhile(() => !PhotonNetwork.InLobby);
  268. //Setting up the room to be created
  269. RoomOptions roomOptions = new RoomOptions
  270. {
  271. IsVisible = true, //Make the room visible in the lobby.
  272. IsOpen = true, //Allow other players to enter the room
  273. PublishUserId = true,
  274. MaxPlayers = 2,
  275. //To display room creator in room custom properties, store creator's name
  276. CustomRoomProperties = new ExitGames.Client.Photon.Hashtable()
  277. {
  278. { "RoomCreator",PhotonNetwork.NickName },
  279. },
  280. //Display custom property information in the lobby
  281. CustomRoomPropertiesForLobby = new string[]
  282. {
  283. "RoomCreator",
  284. }
  285. };
  286. string RoomName = StringUtils.GeneratePassword_AlpahabetNum(8);
  287. if (isRandomMatch)
  288. {
  289. RoomName += RandomKey;
  290. }
  291. //Room Creation
  292. PhotonNetwork.CreateRoom(RoomName, roomOptions, null);
  293. while (!PhotonNetwork.InRoom)
  294. {
  295. yield return null;
  296. }
  297. endLoadingText = true;
  298. yield return _waitForSeconds0_2;
  299. endLoadingText = false;
  300. ContinuousController.instance.LoadingTextCoroutine = StartCoroutine(SetWaitingText(
  301. LocalizeUtility.GetLocalizedString(
  302. EngMessage: "Matching",
  303. JpnMessage: "マッチング中"
  304. )));
  305. MessageText.transform.localPosition = new Vector3(-148, -193, 0);
  306. if (ReturnButton != null)
  307. {
  308. ReturnButton.SetActive(true);
  309. }
  310. }
  311. #endregion
  312. #region Random match starts after entering the lobby
  313. public void StartRandomMatch()
  314. {
  315. if (ReturnButton != null)
  316. {
  317. ReturnButton.SetActive(true);
  318. }
  319. //If there is no room, make room.
  320. if (String.IsNullOrEmpty(RandomRoomName))
  321. {
  322. StartCoroutine(CreateRoomCoroutine(true));
  323. }
  324. //If there's room, I'll go in.
  325. else
  326. {
  327. startJoin = true;
  328. PhotonNetwork.JoinRoom(RandomRoomName);
  329. }
  330. }
  331. #endregion
  332. private IEnumerator SetWaitingText(string defaultString)
  333. {
  334. if (isCoroutineRunning)
  335. {
  336. yield break; // Exit if already running
  337. }
  338. isCoroutineRunning = true;
  339. float waitTime = 0.18f;
  340. int count = 0;
  341. while (!endLoadingText)
  342. {
  343. count++;
  344. if (count >= 4)
  345. {
  346. count = 0;
  347. }
  348. MessageText.text = defaultString;
  349. for (int i = 0; i < count; i++)
  350. {
  351. MessageText.text += ".";
  352. }
  353. yield return new WaitForSeconds(waitTime);
  354. }
  355. isCoroutineRunning = false;
  356. }
  357. public void StartLoadingText(string defaultString)
  358. {
  359. if (!isCoroutineRunning)
  360. {
  361. endLoadingText = false; // Ensure the flag is reset when starting
  362. StartCoroutine(SetWaitingText(defaultString));
  363. }
  364. }
  365. public void StopLoadingText()
  366. {
  367. endLoadingText = true;
  368. }
  369. Button ReturnButtonButton;
  370. private void Start()
  371. {
  372. ReturnButtonButton = ReturnButton.transform.GetChild(0).GetComponent<Button>();
  373. }
  374. private void LateUpdate()
  375. {
  376. if (PhotonNetwork.InRoom)
  377. {
  378. if (PhotonNetwork.CurrentRoom.PlayerCount == PhotonNetwork.CurrentRoom.MaxPlayers)
  379. {
  380. if (PhotonNetwork.IsMasterClient)
  381. {
  382. StartCoroutine(GoNextScene());
  383. }
  384. if (ReturnButtonButton != null)
  385. {
  386. ReturnButtonButton.enabled = false;
  387. }
  388. }
  389. else
  390. {
  391. if (ReturnButtonButton != null)
  392. {
  393. ReturnButtonButton.enabled = true;
  394. }
  395. }
  396. }
  397. else
  398. {
  399. ReturnButtonButton.enabled = true;
  400. }
  401. if (DoneCompleteMatching)
  402. {
  403. if (ReturnButtonButton != null)
  404. {
  405. ReturnButton.SetActive(false);
  406. }
  407. }
  408. }
  409. #region After matching is complete, transition to the battle scene.
  410. bool DoneCompleteMatching = false;
  411. bool once1 = false;
  412. IEnumerator GoNextScene()
  413. {
  414. if (DoneCompleteMatching || once1)
  415. {
  416. yield break;
  417. }
  418. once1 = true;
  419. yield return _waitForSeconds0_1;
  420. PhotonNetwork.CurrentRoom.IsVisible = false;
  421. photonView.RPC("GoToBattleScene", RpcTarget.All);
  422. }
  423. #endregion
  424. [PunRPC]
  425. public void GoToBattleScene()
  426. {
  427. if (DoneCompleteMatching)
  428. {
  429. return;
  430. }
  431. endLoadingText = true;
  432. DoneCompleteMatching = true;
  433. TimeText.gameObject.SetActive(false);
  434. MessageText.text = LocalizeUtility.GetLocalizedString(
  435. EngMessage: "Matching completed!",
  436. JpnMessage: "マッチングしました!"
  437. );
  438. MessageText.transform.localPosition = new Vector3(-390, -193, 0);
  439. ReturnButton.SetActive(false);
  440. ContinuousController.instance.StartCoroutine(GoToBattleSceneCoroutine());
  441. }
  442. IEnumerator GoToBattleSceneCoroutine()
  443. {
  444. ContinuousController.instance.StartCoroutine(Opening.instance.OpeningBGM.FadeOut(0.2f));
  445. Debug.Log("Matching completed!");
  446. yield return _waitForSeconds0_1;
  447. //Opening.instance.MainCamera.gameObject.SetActive(false);
  448. foreach (Camera camera in Opening.instance.openingCameras)
  449. {
  450. camera.gameObject.SetActive(false);
  451. }
  452. yield return _waitForSeconds0_1;
  453. SceneManager.LoadSceneAsync("BattleScene", LoadSceneMode.Additive);
  454. yield return null;
  455. }
  456. }
  457. #region Generation of random strings
  458. public static class StringUtils
  459. {
  460. public static string GeneratePassword_AlpahabetNum(int length)
  461. {
  462. string PASSWORD_CHARS =
  463. "0123456789abcdefghijklmnopqrstuvwxyz";
  464. var sb = new System.Text.StringBuilder(length);
  465. var r = new System.Random();
  466. for (int i = 0; i < length; i++)
  467. {
  468. int pos = r.Next(PASSWORD_CHARS.Length);
  469. char c = PASSWORD_CHARS[pos];
  470. sb.Append(c);
  471. }
  472. return sb.ToString();
  473. }
  474. public static string GeneratePassword_Num(int length)
  475. {
  476. string PASSWORD_CHARS =
  477. "0123456789";
  478. var sb = new System.Text.StringBuilder(length);
  479. var r = new System.Random();
  480. for (int i = 0; i < length; i++)
  481. {
  482. int pos = r.Next(PASSWORD_CHARS.Length);
  483. char c = PASSWORD_CHARS[pos];
  484. sb.Append(c);
  485. }
  486. return sb.ToString();
  487. }
  488. }
  489. #endregion