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.

318 lines
9.9 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. 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. bool blockFinished = false;
  165. float waitTime;
  166. //Loop until the current block indicates or the reader indicates it has finished
  167. while (!blockFinished && !data.blockReader.Finished)
  168. {
  169. //If the current block hasn't already been removed, remove it from the player inventory
  170. //We need to check if it has already been removed so loops don't eat an entire stack
  171. if (data.blockReader.CurrentBlock != null && !data.blockReader.CurrentBlock.hasBeenRemoved)
  172. {
  173. data.client.Inventory.Remove(data.blockReader.CurrentBlock);
  174. data.blockReader.CurrentBlock.hasBeenRemoved = true;
  175. }
  176. //Process the move
  177. blockFinished = data.blockReader.Read(data.character, AnimationTime, out waitTime);
  178. //Wait for the animation to finish
  179. yield return new WaitForSeconds(waitTime);
  180. }
  181. }
  182. private void SpawnCharacters()
  183. {
  184. playerData = new Dictionary<int, PlayerData>();
  185. Block[] SpawnBlocks = FindObjectsOfType<Block>().Where(p => p.isSpawnable).ToArray();
  186. int blockIndex = 0;
  187. foreach (Block block in SpawnBlocks)
  188. {
  189. Debug.Log("Block #" + blockIndex++ + " (" + block.transform.position.x + ", " + block.transform.position.y + ", " + block.transform.position.z + ")");
  190. }
  191. //int spawnIndex = 0;
  192. //If we have an odd number of players, then we start at spawn point 0 (in the middle)
  193. //If we have an even number, then we skip it
  194. //int spawnIndex = ((ClientList.Count() + 1) % 2);
  195. int spawnIndex = 0;
  196. foreach (ClientData client in ClientList)
  197. {
  198. //Debug.Log("spawnIndex = " + spawnIndex);
  199. Character newChar = Instantiate(characterPrefab);
  200. //Block startingBlock = SpawnBlocks[(spawnIndex++ % ClientList.ConnectedClients.Count)];
  201. Block startingBlock = SpawnBlocks[spawnIndex++];
  202. newChar.Initialise(startingBlock, client.Inventory, client.characterAnimal);
  203. newChar.transform.forward = startingBlock.SpawnDirection.ToVector();
  204. playerData.Add(client.ID, new PlayerData(newChar, client));
  205. newChar.ClientLink = client;
  206. client.playerCharacter = newChar;
  207. }
  208. }
  209. #endregion Class Functions
  210. #region Networking Functions
  211. /// <summary>
  212. /// Registers functions which should deal with incoming messages from clients
  213. /// </summary>
  214. private void RegisterHandlers()
  215. {
  216. server.server.RegisterHandler(LogicProtocols.SendLogicList, RecieveLogicList);
  217. }
  218. /// <summary>
  219. /// Clears any functions from server register which the manager would deal with
  220. /// </summary>
  221. private void UnRegisterHandlers()
  222. {
  223. server.server.UnregisterHandler(LogicProtocols.SendLogicList);
  224. }
  225. /// <summary>
  226. /// Called when server recieves moves from client
  227. /// </summary>
  228. /// <param name="msg">messages passed by server</param>
  229. private void RecieveLogicList(NetworkMessage msg)
  230. {
  231. //try to read base message as a logic message
  232. LogicProtocols.LogicMsg logicMsg;
  233. if (!msg.TryRead(out logicMsg))
  234. return;
  235. //Debug that we have recieved it
  236. Debug.Log("Recieved function from " + ClientList[msg.conn.connectionId].Name);
  237. //Update player Data with recieved list
  238. playerData[msg.conn.connectionId].blockReader.LogicChain = new List<LogicBlock>(logicMsg.elements);
  239. playerData[msg.conn.connectionId].recievedList = true;
  240. }
  241. #endregion Networking Functions
  242. }
  243. public class PlayerData
  244. {
  245. public Character character;
  246. public BlockReader blockReader;
  247. public ClientData client;
  248. public bool recievedList;
  249. public bool isDead = false;
  250. public PlayerData(Character character, ClientData client)
  251. {
  252. this.character = character;
  253. this.client = client;
  254. blockReader = new BlockReader();
  255. }
  256. }