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.

278 lines
8.7 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 PlayerData[] playerDataAsArray { get { return playerData.Values.ToArray(); } }
  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. #region Unity Functions
  40. private void Start()
  41. {
  42. //Start Game
  43. StartCoroutine(GameRoutine());
  44. }
  45. private void Update()
  46. {
  47. //This is required so that the server can continue to recieve client messages
  48. //(it is a unity thing)
  49. server.ServerUpdate();
  50. }
  51. private void OnEnable()
  52. {
  53. //Let Server know we want to recieve some messages
  54. RegisterHandlers();
  55. }
  56. private void OnDisable()
  57. {
  58. //Let server know to not send messages this way
  59. UnRegisterHandlers();
  60. }
  61. #endregion Unity Functions
  62. #region Class Functions
  63. private IEnumerator GameRoutine()
  64. {
  65. //Allows game mode to instantiate anything it might need;
  66. gameMode.PreGameStart();
  67. //Spawn Characters and tell let the GameMode do anything with the characters it might want
  68. SpawnCharacters();
  69. gameMode.GameStart(playerDataAsArray);
  70. //Loop until the GameMode lets us know the game is over
  71. while (!gameMode.isGameOver(playerDataAsArray))
  72. {
  73. //wait until we have recieved all player input
  74. yield return StartCoroutine(WaitForPlayerInput());
  75. //Routine for players movement
  76. yield return StartCoroutine(RoundRoutine()); //it's pretty long so it gets it's own coroutine;
  77. }
  78. //Let the gamemode know that the game is over
  79. gameMode.GameEnd(playerDataAsArray);
  80. }
  81. private IEnumerator RoundRoutine()
  82. {
  83. //Tell the gamemode that we are starting a round
  84. gameMode.RoundStart(playerDataAsArray);
  85. //Loop until all players have finished moving
  86. while (playerDataAsArray.Any(p => !p.blockReader.Finished))
  87. {
  88. //Loop through all players
  89. foreach (PlayerData player in playerDataAsArray)
  90. {
  91. yield return StartCoroutine(MoveRoutine(player));//Move Player
  92. gameMode.PlayerMoved(player);//LetGameModeKnow
  93. }
  94. //Let Gamemode know all players have moved
  95. gameMode.AllPlayersMoved(playerDataAsArray.ToArray());
  96. playerDataAsArray.ForEach(p => p.client.SendScore()); //Update the players score
  97. //if Game is over break out of loop
  98. if (gameMode.isGameOver(playerDataAsArray))
  99. break;
  100. }
  101. //Let GameMode know that Round is Over
  102. gameMode.RoundEnd(playerDataAsArray.ToArray());
  103. //Reset some player Data
  104. foreach (PlayerData player in playerDataAsArray)
  105. {
  106. player.blockReader.Reset();
  107. player.client.SendInventory();
  108. }
  109. }
  110. private IEnumerator WaitForPlayerInput()
  111. {
  112. //send round length to players
  113. //#TODO make this only happen after first input
  114. LogicProtocols.FloatMsg RoundTime = new LogicProtocols.FloatMsg(gameMode.GetRoundTime());
  115. playerDataAsArray.ForEach(p => p.client.conn.Send(LogicProtocols.SendRoundTime, RoundTime));
  116. //Send players to input Scene
  117. ClientList.ForEach(p => p.ChangeScene("ClientScene"));
  118. //Let gamemode know clients are input-ing
  119. gameMode.InputStart(playerDataAsArray);
  120. //wait for all players to
  121. yield return new WaitUntil(() => playerData.All(p => p.Value.recievedList));
  122. //reset
  123. playerDataAsArray.ForEach(p => p.recievedList = false); //reset all players list
  124. //Let gamemode know all inputs have been recieved
  125. gameMode.InputEnd(playerDataAsArray);
  126. }
  127. private IEnumerator MoveRoutine(PlayerData data)
  128. {
  129. bool blockFinished = false;
  130. float waitTime;
  131. //Loop until the current block indicates or the reader indicates it has finished
  132. while (!blockFinished && !data.blockReader.Finished)
  133. {
  134. //If the current block hasn't already been removed, remove it from the player inventory
  135. //We need to check if it has already been removed so loops don't eat an entire stack
  136. if (data.blockReader.CurrentBlock != null && !data.blockReader.CurrentBlock.hasBeenRemoved)
  137. {
  138. data.client.Inventory.Remove(data.blockReader.CurrentBlock);
  139. data.blockReader.CurrentBlock.hasBeenRemoved = true;
  140. }
  141. //Process the move
  142. blockFinished = data.blockReader.Read(data.character, AnimationTime, out waitTime);
  143. //Wait for the animation to finish
  144. yield return new WaitForSeconds(waitTime);
  145. }
  146. }
  147. private void SpawnCharacters()
  148. {
  149. playerData = new Dictionary<int, PlayerData>();
  150. Block[] SpawnBlocks = FindObjectsOfType<Block>().Where(p => p.isSpawnable).ToArray();
  151. int blockIndex = 0;
  152. foreach (Block block in SpawnBlocks)
  153. {
  154. Debug.Log("Block #" + blockIndex++ + " (" + block.transform.position.x + ", " + block.transform.position.y + ", " + block.transform.position.z + ")");
  155. }
  156. //int spawnIndex = 0;
  157. //If we have an odd number of players, then we start at spawn point 0 (in the middle)
  158. //If we have an even number, then we skip it
  159. int spawnIndex = ((ClientList.Count() + 1) % 2);
  160. //int spawnIndex = 0;
  161. foreach (ClientData client in ClientList)
  162. {
  163. //Debug.Log("spawnIndex = " + spawnIndex);
  164. Character newChar = Instantiate(characterPrefab);
  165. //Block startingBlock = SpawnBlocks[(spawnIndex++ % ClientList.ConnectedClients.Count)];
  166. Block startingBlock = SpawnBlocks[spawnIndex++];
  167. newChar.Initialise(startingBlock, client.Inventory, client.characterAnimal);
  168. newChar.transform.forward = startingBlock.SpawnDirection.ToVector();
  169. playerData.Add(client.ID, new PlayerData(newChar, client));
  170. newChar.ClientLink = client;
  171. client.playerCharacter = newChar;
  172. }
  173. }
  174. #endregion Class Functions
  175. #region Networking Functions
  176. /// <summary>
  177. /// Registers functions which should deal with incoming messages from clients
  178. /// </summary>
  179. private void RegisterHandlers()
  180. {
  181. server.server.RegisterHandler(LogicProtocols.SendLogicList, RecieveLogicList);
  182. }
  183. /// <summary>
  184. /// Clears any functions from server register which the manager would deal with
  185. /// </summary>
  186. private void UnRegisterHandlers()
  187. {
  188. server.server.UnregisterHandler(LogicProtocols.SendLogicList);
  189. }
  190. /// <summary>
  191. /// Called when server recieves moves from client
  192. /// </summary>
  193. /// <param name="msg">messages passed by server</param>
  194. private void RecieveLogicList(NetworkMessage msg)
  195. {
  196. //try to read base message as a logic message
  197. LogicProtocols.LogicMsg logicMsg;
  198. if (!msg.TryRead(out logicMsg))
  199. return;
  200. //Debug that we have recieved it
  201. Debug.Log("Recieved function from " + ClientList[msg.conn.connectionId].Name);
  202. //Update player Data with recieved list
  203. playerData[msg.conn.connectionId].blockReader.LogicChain = new List<LogicBlock>(logicMsg.elements);
  204. playerData[msg.conn.connectionId].recievedList = true;
  205. }
  206. #endregion Networking Functions
  207. }
  208. public class PlayerData
  209. {
  210. public Character character;
  211. public BlockReader blockReader;
  212. public ClientData client;
  213. public bool recievedList;
  214. public PlayerData(Character character, ClientData client)
  215. {
  216. this.character = character;
  217. this.client = client;
  218. blockReader = new BlockReader();
  219. }
  220. }