MatchController.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. namespace Mirror.Examples.MultipleMatch
  6. {
  7. [RequireComponent(typeof(NetworkMatch))]
  8. public class MatchController : NetworkBehaviour
  9. {
  10. internal readonly SyncDictionary<NetworkIdentity, MatchPlayerData> matchPlayerData = new SyncDictionary<NetworkIdentity, MatchPlayerData>();
  11. internal readonly Dictionary<CellValue, CellGUI> MatchCells = new Dictionary<CellValue, CellGUI>();
  12. CellValue boardScore = CellValue.None;
  13. bool playAgain = false;
  14. [Header("GUI References")]
  15. public CanvasGroup canvasGroup;
  16. public Text gameText;
  17. public Button exitButton;
  18. public Button playAgainButton;
  19. public Text winCountLocal;
  20. public Text winCountOpponent;
  21. [Header("Diagnostics - Do Not Modify")]
  22. public CanvasController canvasController;
  23. public NetworkIdentity player1;
  24. public NetworkIdentity player2;
  25. public NetworkIdentity startingPlayer;
  26. [SyncVar(hook = nameof(UpdateGameUI))]
  27. public NetworkIdentity currentPlayer;
  28. void Awake()
  29. {
  30. #if UNITY_2021_3_OR_NEWER
  31. canvasController = GameObject.FindAnyObjectByType<CanvasController>();
  32. #else
  33. // Deprecated in Unity 2023.1
  34. canvasController = GameObject.FindObjectOfType<CanvasController>();
  35. #endif
  36. }
  37. public override void OnStartServer()
  38. {
  39. StartCoroutine(AddPlayersToMatchController());
  40. }
  41. // For the SyncDictionary to properly fire the update callback, we must
  42. // wait a frame before adding the players to the already spawned MatchController
  43. IEnumerator AddPlayersToMatchController()
  44. {
  45. yield return null;
  46. matchPlayerData.Add(player1, new MatchPlayerData { playerIndex = CanvasController.playerInfos[player1.connectionToClient].playerIndex });
  47. matchPlayerData.Add(player2, new MatchPlayerData { playerIndex = CanvasController.playerInfos[player2.connectionToClient].playerIndex });
  48. }
  49. public override void OnStartClient()
  50. {
  51. matchPlayerData.Callback += UpdateWins;
  52. canvasGroup.alpha = 1f;
  53. canvasGroup.interactable = true;
  54. canvasGroup.blocksRaycasts = true;
  55. exitButton.gameObject.SetActive(false);
  56. playAgainButton.gameObject.SetActive(false);
  57. }
  58. [ClientCallback]
  59. public void UpdateGameUI(NetworkIdentity _, NetworkIdentity newPlayerTurn)
  60. {
  61. if (!newPlayerTurn) return;
  62. if (newPlayerTurn.gameObject.GetComponent<NetworkIdentity>().isLocalPlayer)
  63. {
  64. gameText.text = "Your Turn";
  65. gameText.color = Color.blue;
  66. }
  67. else
  68. {
  69. gameText.text = "Their Turn";
  70. gameText.color = Color.red;
  71. }
  72. }
  73. [ClientCallback]
  74. public void UpdateWins(SyncDictionary<NetworkIdentity, MatchPlayerData>.Operation op, NetworkIdentity key, MatchPlayerData matchPlayerData)
  75. {
  76. if (key.gameObject.GetComponent<NetworkIdentity>().isLocalPlayer)
  77. winCountLocal.text = $"Player {matchPlayerData.playerIndex}\n{matchPlayerData.wins}";
  78. else
  79. winCountOpponent.text = $"Player {matchPlayerData.playerIndex}\n{matchPlayerData.wins}";
  80. }
  81. [Command(requiresAuthority = false)]
  82. public void CmdMakePlay(CellValue cellValue, NetworkConnectionToClient sender = null)
  83. {
  84. // If wrong player or cell already taken, ignore
  85. if (sender.identity != currentPlayer || MatchCells[cellValue].playerIdentity != null)
  86. return;
  87. MatchCells[cellValue].playerIdentity = currentPlayer;
  88. RpcUpdateCell(cellValue, currentPlayer);
  89. MatchPlayerData mpd = matchPlayerData[currentPlayer];
  90. mpd.currentScore = mpd.currentScore | cellValue;
  91. matchPlayerData[currentPlayer] = mpd;
  92. boardScore = boardScore | cellValue;
  93. if (CheckWinner(mpd.currentScore))
  94. {
  95. mpd.wins += 1;
  96. matchPlayerData[currentPlayer] = mpd;
  97. RpcShowWinner(currentPlayer);
  98. currentPlayer = null;
  99. }
  100. else if (boardScore == CellValue.Full)
  101. {
  102. RpcShowWinner(null);
  103. currentPlayer = null;
  104. }
  105. else
  106. {
  107. // Set currentPlayer SyncVar so clients know whose turn it is
  108. currentPlayer = currentPlayer == player1 ? player2 : player1;
  109. }
  110. }
  111. [ServerCallback]
  112. bool CheckWinner(CellValue currentScore)
  113. {
  114. if ((currentScore & CellValue.TopRow) == CellValue.TopRow)
  115. return true;
  116. if ((currentScore & CellValue.MidRow) == CellValue.MidRow)
  117. return true;
  118. if ((currentScore & CellValue.BotRow) == CellValue.BotRow)
  119. return true;
  120. if ((currentScore & CellValue.LeftCol) == CellValue.LeftCol)
  121. return true;
  122. if ((currentScore & CellValue.MidCol) == CellValue.MidCol)
  123. return true;
  124. if ((currentScore & CellValue.RightCol) == CellValue.RightCol)
  125. return true;
  126. if ((currentScore & CellValue.Diag1) == CellValue.Diag1)
  127. return true;
  128. if ((currentScore & CellValue.Diag2) == CellValue.Diag2)
  129. return true;
  130. return false;
  131. }
  132. [ClientRpc]
  133. public void RpcUpdateCell(CellValue cellValue, NetworkIdentity player)
  134. {
  135. MatchCells[cellValue].SetPlayer(player);
  136. }
  137. [ClientRpc]
  138. public void RpcShowWinner(NetworkIdentity winner)
  139. {
  140. foreach (CellGUI cellGUI in MatchCells.Values)
  141. cellGUI.GetComponent<Button>().interactable = false;
  142. if (winner == null)
  143. {
  144. gameText.text = "Draw!";
  145. gameText.color = Color.yellow;
  146. }
  147. else if (winner.gameObject.GetComponent<NetworkIdentity>().isLocalPlayer)
  148. {
  149. gameText.text = "Winner!";
  150. gameText.color = Color.blue;
  151. }
  152. else
  153. {
  154. gameText.text = "Loser!";
  155. gameText.color = Color.red;
  156. }
  157. exitButton.gameObject.SetActive(true);
  158. playAgainButton.gameObject.SetActive(true);
  159. }
  160. // Assigned in inspector to ReplayButton::OnClick
  161. [ClientCallback]
  162. public void RequestPlayAgain()
  163. {
  164. playAgainButton.gameObject.SetActive(false);
  165. CmdPlayAgain();
  166. }
  167. [Command(requiresAuthority = false)]
  168. public void CmdPlayAgain(NetworkConnectionToClient sender = null)
  169. {
  170. if (!playAgain)
  171. playAgain = true;
  172. else
  173. {
  174. playAgain = false;
  175. RestartGame();
  176. }
  177. }
  178. [ServerCallback]
  179. public void RestartGame()
  180. {
  181. foreach (CellGUI cellGUI in MatchCells.Values)
  182. cellGUI.SetPlayer(null);
  183. boardScore = CellValue.None;
  184. NetworkIdentity[] keys = new NetworkIdentity[matchPlayerData.Keys.Count];
  185. matchPlayerData.Keys.CopyTo(keys, 0);
  186. foreach (NetworkIdentity identity in keys)
  187. {
  188. MatchPlayerData mpd = matchPlayerData[identity];
  189. mpd.currentScore = CellValue.None;
  190. matchPlayerData[identity] = mpd;
  191. }
  192. RpcRestartGame();
  193. startingPlayer = startingPlayer == player1 ? player2 : player1;
  194. currentPlayer = startingPlayer;
  195. }
  196. [ClientRpc]
  197. public void RpcRestartGame()
  198. {
  199. foreach (CellGUI cellGUI in MatchCells.Values)
  200. cellGUI.SetPlayer(null);
  201. exitButton.gameObject.SetActive(false);
  202. playAgainButton.gameObject.SetActive(false);
  203. }
  204. // Assigned in inspector to BackButton::OnClick
  205. [Client]
  206. public void RequestExitGame()
  207. {
  208. exitButton.gameObject.SetActive(false);
  209. playAgainButton.gameObject.SetActive(false);
  210. CmdRequestExitGame();
  211. }
  212. [Command(requiresAuthority = false)]
  213. public void CmdRequestExitGame(NetworkConnectionToClient sender = null)
  214. {
  215. StartCoroutine(ServerEndMatch(sender, false));
  216. }
  217. [ServerCallback]
  218. public void OnPlayerDisconnected(NetworkConnectionToClient conn)
  219. {
  220. // Check that the disconnecting client is a player in this match
  221. if (player1 == conn.identity || player2 == conn.identity)
  222. StartCoroutine(ServerEndMatch(conn, true));
  223. }
  224. [ServerCallback]
  225. public IEnumerator ServerEndMatch(NetworkConnectionToClient conn, bool disconnected)
  226. {
  227. RpcExitGame();
  228. canvasController.OnPlayerDisconnected -= OnPlayerDisconnected;
  229. // Wait for the ClientRpc to get out ahead of object destruction
  230. yield return new WaitForSeconds(0.1f);
  231. // Mirror will clean up the disconnecting client so we only need to clean up the other remaining client.
  232. // If both players are just returning to the Lobby, we need to remove both connection Players
  233. if (!disconnected)
  234. {
  235. NetworkServer.RemovePlayerForConnection(player1.connectionToClient, true);
  236. CanvasController.waitingConnections.Add(player1.connectionToClient);
  237. NetworkServer.RemovePlayerForConnection(player2.connectionToClient, true);
  238. CanvasController.waitingConnections.Add(player2.connectionToClient);
  239. }
  240. else if (conn == player1.connectionToClient)
  241. {
  242. // player1 has disconnected - send player2 back to Lobby
  243. NetworkServer.RemovePlayerForConnection(player2.connectionToClient, true);
  244. CanvasController.waitingConnections.Add(player2.connectionToClient);
  245. }
  246. else if (conn == player2.connectionToClient)
  247. {
  248. // player2 has disconnected - send player1 back to Lobby
  249. NetworkServer.RemovePlayerForConnection(player1.connectionToClient, true);
  250. CanvasController.waitingConnections.Add(player1.connectionToClient);
  251. }
  252. // Skip a frame to allow the Removal(s) to complete
  253. yield return null;
  254. // Send latest match list
  255. canvasController.SendMatchList();
  256. NetworkServer.Destroy(gameObject);
  257. }
  258. [ClientRpc]
  259. public void RpcExitGame()
  260. {
  261. canvasController.OnMatchEnded();
  262. }
  263. }
  264. }