MatchController.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. namespace Mirror.Examples.MultipleMatch
  6. {
  7. #pragma warning disable 618
  8. [RequireComponent(typeof(NetworkMatchChecker))]
  9. #pragma warning restore 618
  10. public class MatchController : NetworkBehaviour
  11. {
  12. internal readonly SyncDictionary<NetworkIdentity, MatchPlayerData> matchPlayerData = new SyncDictionary<NetworkIdentity, MatchPlayerData>();
  13. internal readonly Dictionary<CellValue, CellGUI> MatchCells = new Dictionary<CellValue, CellGUI>();
  14. CellValue boardScore = CellValue.None;
  15. bool playAgain = false;
  16. [Header("GUI References")]
  17. public CanvasGroup canvasGroup;
  18. public Text gameText;
  19. public Button exitButton;
  20. public Button playAgainButton;
  21. public Text winCountLocal;
  22. public Text winCountOpponent;
  23. [Header("Diagnostics - Do Not Modify")]
  24. public CanvasController canvasController;
  25. public NetworkIdentity player1;
  26. public NetworkIdentity player2;
  27. public NetworkIdentity startingPlayer;
  28. [SyncVar(hook = nameof(UpdateGameUI))]
  29. public NetworkIdentity currentPlayer;
  30. void Awake()
  31. {
  32. canvasController = FindObjectOfType<CanvasController>();
  33. }
  34. public override void OnStartServer()
  35. {
  36. StartCoroutine(AddPlayersToMatchController());
  37. }
  38. // For the SyncDictionary to properly fire the update callback, we must
  39. // wait a frame before adding the players to the already spawned MatchController
  40. IEnumerator AddPlayersToMatchController()
  41. {
  42. yield return null;
  43. matchPlayerData.Add(player1, new MatchPlayerData { playerIndex = CanvasController.playerInfos[player1.connectionToClient].playerIndex });
  44. matchPlayerData.Add(player2, new MatchPlayerData { playerIndex = CanvasController.playerInfos[player2.connectionToClient].playerIndex });
  45. }
  46. public override void OnStartClient()
  47. {
  48. matchPlayerData.Callback += UpdateWins;
  49. canvasGroup.alpha = 1f;
  50. canvasGroup.interactable = true;
  51. canvasGroup.blocksRaycasts = true;
  52. exitButton.gameObject.SetActive(false);
  53. playAgainButton.gameObject.SetActive(false);
  54. }
  55. public void UpdateGameUI(NetworkIdentity _, NetworkIdentity newPlayerTurn)
  56. {
  57. if (!newPlayerTurn) return;
  58. if (newPlayerTurn.gameObject.GetComponent<NetworkIdentity>().isLocalPlayer)
  59. {
  60. gameText.text = "Your Turn";
  61. gameText.color = Color.blue;
  62. }
  63. else
  64. {
  65. gameText.text = "Their Turn";
  66. gameText.color = Color.red;
  67. }
  68. }
  69. public void UpdateWins(SyncDictionary<NetworkIdentity, MatchPlayerData>.Operation op, NetworkIdentity key, MatchPlayerData matchPlayerData)
  70. {
  71. if (key.gameObject.GetComponent<NetworkIdentity>().isLocalPlayer)
  72. {
  73. winCountLocal.text = $"Player {matchPlayerData.playerIndex}\n{matchPlayerData.wins}";
  74. }
  75. else
  76. {
  77. winCountOpponent.text = $"Player {matchPlayerData.playerIndex}\n{matchPlayerData.wins}";
  78. }
  79. }
  80. [Command(requiresAuthority = false)]
  81. public void CmdMakePlay(CellValue cellValue, NetworkConnectionToClient sender = null)
  82. {
  83. // If wrong player or cell already taken, ignore
  84. if (sender.identity != currentPlayer || MatchCells[cellValue].playerIdentity != null)
  85. return;
  86. MatchCells[cellValue].playerIdentity = currentPlayer;
  87. RpcUpdateCell(cellValue, currentPlayer);
  88. MatchPlayerData mpd = matchPlayerData[currentPlayer];
  89. mpd.currentScore = mpd.currentScore | cellValue;
  90. matchPlayerData[currentPlayer] = mpd;
  91. boardScore = boardScore | cellValue;
  92. if (CheckWinner(mpd.currentScore))
  93. {
  94. mpd.wins += 1;
  95. matchPlayerData[currentPlayer] = mpd;
  96. RpcShowWinner(currentPlayer);
  97. currentPlayer = null;
  98. }
  99. else if (boardScore == CellValue.Full)
  100. {
  101. RpcShowWinner(null);
  102. currentPlayer = null;
  103. }
  104. else
  105. {
  106. // Set currentPlayer SyncVar so clients know whose turn it is
  107. currentPlayer = currentPlayer == player1 ? player2 : player1;
  108. }
  109. }
  110. bool CheckWinner(CellValue currentScore)
  111. {
  112. if ((currentScore & CellValue.TopRow) == CellValue.TopRow)
  113. return true;
  114. if ((currentScore & CellValue.MidRow) == CellValue.MidRow)
  115. return true;
  116. if ((currentScore & CellValue.BotRow) == CellValue.BotRow)
  117. return true;
  118. if ((currentScore & CellValue.LeftCol) == CellValue.LeftCol)
  119. return true;
  120. if ((currentScore & CellValue.MidCol) == CellValue.MidCol)
  121. return true;
  122. if ((currentScore & CellValue.RightCol) == CellValue.RightCol)
  123. return true;
  124. if ((currentScore & CellValue.Diag1) == CellValue.Diag1)
  125. return true;
  126. if ((currentScore & CellValue.Diag2) == CellValue.Diag2)
  127. return true;
  128. return false;
  129. }
  130. [ClientRpc]
  131. public void RpcUpdateCell(CellValue cellValue, NetworkIdentity player)
  132. {
  133. MatchCells[cellValue].SetPlayer(player);
  134. }
  135. [ClientRpc]
  136. public void RpcShowWinner(NetworkIdentity winner)
  137. {
  138. foreach (CellGUI cellGUI in MatchCells.Values)
  139. cellGUI.GetComponent<Button>().interactable = false;
  140. if (winner == null)
  141. {
  142. gameText.text = "Draw!";
  143. gameText.color = Color.yellow;
  144. }
  145. else if (winner.gameObject.GetComponent<NetworkIdentity>().isLocalPlayer)
  146. {
  147. gameText.text = "Winner!";
  148. gameText.color = Color.blue;
  149. }
  150. else
  151. {
  152. gameText.text = "Loser!";
  153. gameText.color = Color.red;
  154. }
  155. exitButton.gameObject.SetActive(true);
  156. playAgainButton.gameObject.SetActive(true);
  157. }
  158. // Assigned in inspector to ReplayButton::OnClick
  159. [Client]
  160. public void RequestPlayAgain()
  161. {
  162. playAgainButton.gameObject.SetActive(false);
  163. CmdPlayAgain();
  164. }
  165. [Command(requiresAuthority = false)]
  166. public void CmdPlayAgain(NetworkConnectionToClient sender = null)
  167. {
  168. if (!playAgain)
  169. {
  170. playAgain = true;
  171. }
  172. else
  173. {
  174. playAgain = false;
  175. RestartGame();
  176. }
  177. }
  178. [Server]
  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. public void OnPlayerDisconnected(NetworkConnection conn)
  218. {
  219. // Check that the disconnecting client is a player in this match
  220. if (player1 == conn.identity || player2 == conn.identity)
  221. {
  222. StartCoroutine(ServerEndMatch(conn, true));
  223. }
  224. }
  225. public IEnumerator ServerEndMatch(NetworkConnection conn, bool disconnected)
  226. {
  227. canvasController.OnPlayerDisconnected -= OnPlayerDisconnected;
  228. RpcExitGame();
  229. // Skip a frame so the message goes out ahead of object destruction
  230. yield return null;
  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. }