1
0

MatchController.cs 11 KB

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