You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

252 lines
7.3 KiB

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. using UnityEngine.Networking;
  6. using Networking.Server;
  7. using Networking;
  8. using UnityEngine.SceneManagement;
  9. public class GameManager : MonoBehaviour
  10. {
  11. #region Inspector Field
  12. [Header("Settings")]
  13. [SerializeField]
  14. private float AnimationTime;
  15. [SerializeField]
  16. private GameModeReference CurrentGameMode;
  17. [Header("References")]
  18. [SerializeField]
  19. [Tooltip("Prefab of character for players to play")]
  20. private Character characterPrefab;
  21. [SerializeField]
  22. private ServerObject server;
  23. [SerializeField]
  24. private ClientList ClientList;
  25. #endregion Inspector Field
  26. #region Private Variables
  27. private Dictionary<int, PlayerData> playerData;
  28. #endregion Private Variables
  29. #region Read Only
  30. /// <summary>
  31. /// Easy access to IEnumerable in playerData so we can Enumerate through it
  32. /// </summary>
  33. private IEnumerable<PlayerData> playerDataAsArray { get { return playerData.Values; } }
  34. /// <summary>
  35. /// Easy access to GameMode value in CurrentGameMode reference
  36. /// </summary>
  37. private GameMode gameMode {get { return CurrentGameMode.Value; } }
  38. #endregion Read Only
  39. public GameObject levelInfo;
  40. public blockSpawn bspawn;
  41. #region Unity Functions
  42. public void Awake()
  43. {
  44. RegisterHandlers();
  45. SpawnCharacters();
  46. ClientList.ForEach(p => p.ChangeScene("ClientScene"));
  47. }
  48. private void Start()
  49. {
  50. StartCoroutine(displayforSeconds(levelInfo, 5.0f));
  51. gameMode.GameStart(playerDataAsArray.ToArray());
  52. StartRound();
  53. }
  54. private void Update()
  55. {
  56. //This is required so that the server can continue to recieve client messages
  57. //(it is a unity thing)
  58. server.ServerUpdate();
  59. }
  60. private void OnDisable()
  61. {
  62. //Let server know to not send messages this way
  63. UnRegisterHandlers();
  64. }
  65. #endregion Unity Functions
  66. IEnumerator displayforSeconds(GameObject display, float time)
  67. {
  68. display.SetActive (true);
  69. yield return new WaitForSeconds(time);
  70. display.SetActive (false);
  71. }
  72. private void DoRoundRoutine()
  73. {
  74. Debug.Log("Starting Round");
  75. StartCoroutine(RoundRoutine());
  76. }
  77. private void StartRound()
  78. {
  79. gameMode.RoundStart(playerDataAsArray.ToArray());
  80. LogicProtocols.FloatMsg RoundTime = new LogicProtocols.FloatMsg( gameMode.GetRoundTime());
  81. bspawn.Spawn();
  82. playerDataAsArray.ForEach(p => p.client.conn.Send(LogicProtocols.SendRoundTime, RoundTime));
  83. }
  84. private IEnumerator RoundRoutine()
  85. {
  86. playerDataAsArray.ForEach(p => p.recievedList = false);
  87. //Debug.Log("Doing Round Routine");
  88. while (playerDataAsArray.Any(p => !p.blockReader.Finished))
  89. {
  90. //Debug.Log("One Move");
  91. foreach (PlayerData player in playerDataAsArray)
  92. {
  93. Debug.Log(player.client.Name);
  94. StartCoroutine(RunOnce(player));
  95. yield return new WaitUntil(() => player.waiting);
  96. }
  97. //wait until all players have finished
  98. //yield return new WaitUntil(() => playerArray.All(p => p.waiting));
  99. gameMode.FinishedMove(playerDataAsArray.ToArray());
  100. playerDataAsArray.ForEach(p => p.client.SendScore());
  101. }
  102. if (gameMode.isGameOver(playerDataAsArray.ToArray()))
  103. {
  104. Debug.Log("Game Over");
  105. SceneManager.LoadScene("ScoreBoards");
  106. }
  107. gameMode.RoundEnd(playerDataAsArray.ToArray());
  108. foreach (PlayerData player in playerDataAsArray)
  109. {
  110. player.blockReader.Reset();
  111. player.waiting = false;
  112. player.client.SendInventory();
  113. player.client.ChangeScene("ClientScene");
  114. }
  115. //Debug.Log("Finished Moving");
  116. StartRound();
  117. }
  118. private void SpawnCharacters()
  119. {
  120. playerData = new Dictionary<int, PlayerData>();
  121. Block[] SpawnBlocks = FindObjectsOfType<Block>().Where(p => p.isSpawnable).ToArray();
  122. int spawnIndex = 0;
  123. foreach (ClientData client in ClientList)
  124. {
  125. Character newChar = Instantiate(characterPrefab);
  126. Block startingBlock = SpawnBlocks[(spawnIndex++ % ClientList.ConnectedClients.Count)];
  127. newChar.Initialise(startingBlock, client.Inventory, client.characterAnimal);
  128. newChar.transform.forward = startingBlock.SpawnDirection.ToVector();
  129. playerData.Add(client.ID, new PlayerData(newChar,client));
  130. newChar.ClientLink = client;
  131. client.playerCharacter = newChar;
  132. }
  133. }
  134. #region Networking Functions
  135. /// <summary>
  136. /// Registers functions which should deal with incoming messages from clients
  137. /// </summary>
  138. private void RegisterHandlers()
  139. {
  140. server.server.RegisterHandler(LogicProtocols.SendLogicList, RecieveLogicList);
  141. }
  142. /// <summary>
  143. /// Clears any functions from server register which the manager would deal with
  144. /// </summary>
  145. private void UnRegisterHandlers()
  146. {
  147. server.server.UnregisterHandler(LogicProtocols.SendLogicList);
  148. }
  149. /// <summary>
  150. /// Called when server recieves moves from client
  151. /// </summary>
  152. /// <param name="msg">messages passed by server</param>
  153. private void RecieveLogicList(NetworkMessage msg)
  154. {
  155. //try to read base message as a logic message
  156. LogicProtocols.LogicMsg logicMsg;
  157. if (!msg.TryRead(out logicMsg))
  158. return;
  159. //Debug that we have recieved it
  160. Debug.Log("Recieved function from " + ClientList[msg.conn.connectionId].Name);
  161. //Update player Data with recieved list
  162. playerData[msg.conn.connectionId].blockReader.LogicChain = new List<LogicBlock>(logicMsg.elements);
  163. playerData[msg.conn.connectionId].recievedList = true;
  164. //if we have recieved all moves start round
  165. if (playerData.All(p => p.Value.recievedList))
  166. DoRoundRoutine();
  167. }
  168. #endregion Networking Functions
  169. private IEnumerator RunOnce(PlayerData data)
  170. {
  171. data.waiting = false;
  172. bool blockFinished = false;
  173. float waitTime;
  174. while (!blockFinished && !data.blockReader.Finished)
  175. {
  176. //Debug.Log(data.client + "Moving once");
  177. if (data.blockReader.CurrentBlock != null && !data.blockReader.CurrentBlock.hasBeenRemoved)
  178. {
  179. data.client.Inventory.Remove(data.blockReader.CurrentBlock);
  180. data.blockReader.CurrentBlock.hasBeenRemoved = true;
  181. }
  182. blockFinished = data.blockReader.Read(data.character, AnimationTime,out waitTime);
  183. //Debug.Log("Waiting: " + waitTime);
  184. yield return new WaitForSeconds(waitTime);
  185. gameMode.OnePlayerMoved(data);
  186. }
  187. data.waiting = true;
  188. }
  189. }
  190. public class PlayerData
  191. {
  192. public Character character;
  193. public BlockReader blockReader;
  194. public ClientData client;
  195. public bool recievedList;
  196. public bool waiting;
  197. public PlayerData(Character character, ClientData client)
  198. {
  199. this.character = character;
  200. this.client = client;
  201. blockReader = new BlockReader();
  202. }
  203. }