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.

313 lines
9.8 KiB

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