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.

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