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.

370 lines
12 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
  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. public blockSpawn spawnBlock;
  26. #endregion Inspector Field
  27. #region Private Variables
  28. public Dictionary<int, PlayerData> playerData;
  29. private ActiveBlock[] EnvironmentBlocks;
  30. #endregion Private Variables
  31. #region Read Only
  32. /// <summary>
  33. /// Easy access to IEnumerable in playerData so we can Enumerate through it
  34. /// </summary>
  35. private PlayerData[] playerDataAsArray { get { return playerData.Values.ToArray(); } }
  36. /// <summary>
  37. /// Easy access to GameMode value in CurrentGameMode reference
  38. /// </summary>
  39. private GameMode gameMode { get { return CurrentGameMode.Value; } }
  40. #endregion Read Only
  41. #region Unity Functions
  42. private void Start()
  43. {
  44. spawnBlock = gameObject.GetComponent<blockSpawn>();
  45. //Start Game
  46. StartCoroutine(GameRoutine());
  47. }
  48. private void Update()
  49. {
  50. //This is required so that the server can continue to recieve client messages
  51. //(it is a unity thing)
  52. server.ServerUpdate();
  53. }
  54. private void OnEnable()
  55. {
  56. //Let Server know we want to recieve some messages
  57. RegisterHandlers();
  58. }
  59. private void OnDisable()
  60. {
  61. //Let server know to not send messages this way
  62. UnRegisterHandlers();
  63. }
  64. #endregion Unity Functions
  65. #region Class Functions
  66. private IEnumerator GameRoutine()
  67. {
  68. //Allows game mode to instantiate anything it might need;
  69. gameMode.PreGameStart();
  70. //gets list of items to check spawn locations
  71. spawnBlock.wakeup();
  72. //Spawn Characters and tell let the GameMode do anything with the characters it might want
  73. SpawnCharacters();
  74. playerDataAsArray.ForEach(p => p.client.SendLives());
  75. gameMode.GameStart(playerDataAsArray);
  76. //Loop until the GameMode lets us know the game is over
  77. while (!gameMode.isGameOver(playerDataAsArray))
  78. {
  79. //wait until we have recieved all player input
  80. yield return StartCoroutine(WaitForPlayerInput());
  81. //I hate having to do this
  82. EnvironmentBlocks = FindObjectsOfType<ActiveBlock>();
  83. ////Debug.Log("Active blocks found: " + EnvironmentBlocks.Length);
  84. //Routine for players movement
  85. yield return StartCoroutine(RoundRoutine()); //it's pretty long so it gets it's own coroutine;
  86. }
  87. //Let the gamemode know that the game is over
  88. gameMode.GameEnd(playerDataAsArray);
  89. }
  90. private void removePlayer(PlayerData player)
  91. {
  92. player.client.ChangeScene("WaitScene");
  93. player.isDead = true;
  94. }
  95. private IEnumerator RoundRoutine()
  96. {
  97. //Tell the gamemode that we are starting a round
  98. gameMode.RoundStart(playerDataAsArray);
  99. //playerDataAsArray.OrderByDescending(unit => unit.character.transform.position.x);
  100. //playerDataAsArray = playerDataAsArray.OrderBy(unit => unit.character.CurrentBlock.transform.position.x).ToArray();
  101. playerData = playerData.OrderBy(unit => unit.Value.character.CurrentBlock.transform.position.x).ToDictionary(unit => unit.Key, unit => unit.Value);
  102. //Loop until all players have finished moving
  103. while (playerDataAsArray.Any(p => !p.blockReader.Finished))
  104. {
  105. //Loop through all players
  106. foreach (PlayerData player in playerDataAsArray)
  107. {
  108. yield return StartCoroutine(MoveRoutine(player));//Move Player
  109. gameMode.PlayerMoved(player);//LetGameModeKnow
  110. }
  111. //Let Gamemode know all players have moved
  112. gameMode.AllPlayersMoved(playerDataAsArray);
  113. //Let the environment take a turn
  114. yield return StartCoroutine(EnvironmentTurn());
  115. gameMode.EnvironmentTurn(playerDataAsArray);
  116. //if Game is over break out of loop
  117. if (gameMode.isGameOver(playerDataAsArray))
  118. break;
  119. }
  120. //decrease lives here!!
  121. foreach (PlayerData player in playerDataAsArray)
  122. {
  123. gameMode.PlayerKilled(player);
  124. }
  125. playerDataAsArray.ForEach(p => p.client.SendLives()); //Update the players score
  126. //Let GameMode know that Round is Over
  127. yield return StartCoroutine(EnvironmentEnd());
  128. gameMode.RoundEnd(playerDataAsArray.ToArray());
  129. //check is anyone has 0 lives remaining
  130. //remove them from the array
  131. //force them back to the waiting for players screen
  132. foreach (PlayerData player in playerDataAsArray)
  133. {
  134. if (player.client.Lives == 0)
  135. {
  136. //Debug.Log("Remove: " + player.client.characterAnimal);
  137. removePlayer(player);
  138. }
  139. }
  140. //spawn collectible logic blocks
  141. spawnBlock.Spawn();
  142. //Reset some player Data
  143. foreach (PlayerData player in playerDataAsArray)
  144. {
  145. if (player.client.Lives > 0)
  146. {
  147. player.blockReader.Reset();
  148. player.client.SendInventory();
  149. }
  150. }
  151. }
  152. private IEnumerator WaitForPlayerInput()
  153. {
  154. //send round length to players
  155. //#TODO make this only happen after first input
  156. LogicProtocols.FloatMsg RoundTime = new LogicProtocols.FloatMsg(gameMode.GetRoundTime());
  157. //playerDataAsArray.ForEach(p => p.client.conn.Send(LogicProtocols.SendRoundTime, RoundTime));
  158. foreach (PlayerData player in playerDataAsArray)
  159. {
  160. if (player.client.Lives > 0)
  161. {
  162. player.client.conn.Send(LogicProtocols.SendRoundTime, RoundTime);
  163. }
  164. }
  165. //Send players to input Scene
  166. //ClientList.ForEach(p => p.ChangeScene("ClientScene"));
  167. foreach (ClientData client in ClientList)
  168. {
  169. if (client.Lives > 0) { client.ChangeScene("ClientScene"); }
  170. }
  171. //Let gamemode know clients are input-ing
  172. gameMode.InputStart(playerDataAsArray);
  173. //wait for all players to
  174. yield return new WaitUntil(() => playerData.All(p => p.Value.recievedList || p.Value.isDead));
  175. //reset
  176. //playerDataAsArray.ForEach(p => p.recievedList = false); //reset all players list
  177. foreach (PlayerData player in playerDataAsArray)
  178. {
  179. if (player.client.Lives > 0) { player.recievedList = false; }
  180. }
  181. //Let gamemode know all inputs have been recieved
  182. gameMode.InputEnd(playerDataAsArray);
  183. }
  184. private IEnumerator MoveRoutine(PlayerData data)
  185. {
  186. //If the current block hasn't already been removed, remove it from the player inventory
  187. //We need to check if it has already been removed so loops don't eat an entire stack
  188. if (data.blockReader.CurrentBlock != null && !data.blockReader.CurrentBlock.hasBeenRemoved)
  189. {
  190. data.client.Inventory.Remove(data.blockReader.CurrentBlock);
  191. data.blockReader.CurrentBlock.hasBeenRemoved = true;
  192. }
  193. //Process the move
  194. //blockFinished = data.blockReader.Read(data.character, AnimationTime, out waitTime);
  195. //Wait for the animation to finish
  196. //yield return new WaitForSeconds(waitTime);
  197. yield return StartCoroutine(data.blockReader.Read(data.character, AnimationTime));
  198. }
  199. private void SpawnCharacters()
  200. {
  201. playerData = new Dictionary<int, PlayerData>();
  202. Block[] SpawnBlocks = FindObjectsOfType<Block>().Where(p => p.isSpawnable).ToArray();
  203. int blockIndex = 0;
  204. foreach (Block block in SpawnBlocks)
  205. {
  206. ////Debug.Log("Block #" + blockIndex++ + " (" + block.transform.position.x + ", " + block.transform.position.y + ", " + block.transform.position.z + ")");
  207. }
  208. //int spawnIndex = 0;
  209. //If we have an odd number of players, then we start at spawn point 0 (in the middle)
  210. //If we have an even number, then we skip it
  211. //int spawnIndex = ((ClientList.Count() + 1) % 2);
  212. int spawnIndex = 0;
  213. foreach (ClientData client in ClientList)
  214. {
  215. ////Debug.Log("spawnIndex = " + spawnIndex);
  216. Character newChar = Instantiate(characterPrefab);
  217. //Block startingBlock = SpawnBlocks[(spawnIndex++ % ClientList.ConnectedClients.Count)];
  218. Block startingBlock = SpawnBlocks[spawnIndex++];
  219. newChar.Initialise(startingBlock, client.Inventory, client.characterAnimal);
  220. newChar.transform.forward = startingBlock.SpawnDirection.ToVector();
  221. playerData.Add(client.ID, new PlayerData(newChar, client));
  222. newChar.ClientLink = client;
  223. client.playerCharacter = newChar;
  224. }
  225. }
  226. private IEnumerator EnvironmentTurn()
  227. {
  228. foreach (var InitiativeGroup in EnvironmentBlocks.GroupBy(p => p.GetInitative())){
  229. foreach (ActiveBlock block in InitiativeGroup)
  230. StartCoroutine(block.OnEnvironmentTurn(playerDataAsArray));
  231. yield return new WaitUntil(() => InitiativeGroup.All(p => p.isFinished));
  232. InitiativeGroup.ForEach(p => p.Reset());
  233. }
  234. }
  235. private IEnumerator EnvironmentEnd()
  236. {
  237. foreach (var InitiativeGroup in EnvironmentBlocks.GroupBy(p => p.GetInitative())){
  238. foreach (ActiveBlock block in InitiativeGroup)
  239. StartCoroutine(block.OnRoundEnd(playerDataAsArray));
  240. yield return new WaitUntil(() => InitiativeGroup.All(p => p.isFinished));
  241. InitiativeGroup.ForEach(p => p.Reset());
  242. }
  243. }
  244. private ActiveBlock[] GetActiveBlocksOf(int intiative)
  245. {
  246. return EnvironmentBlocks.Where(p => p.GetInitative() == intiative).ToArray();
  247. }
  248. #endregion Class Functions
  249. #region Networking Functions
  250. /// <summary>
  251. /// Registers functions which should deal with incoming messages from clients
  252. /// </summary>
  253. private void RegisterHandlers()
  254. {
  255. server.server.RegisterHandler(LogicProtocols.SendLogicList, RecieveLogicList);
  256. }
  257. /// <summary>
  258. /// Clears any functions from server register which the manager would deal with
  259. /// </summary>
  260. private void UnRegisterHandlers()
  261. {
  262. server.server.UnregisterHandler(LogicProtocols.SendLogicList);
  263. }
  264. /// <summary>
  265. /// Called when server recieves moves from client
  266. /// </summary>
  267. /// <param name="msg">messages passed by server</param>
  268. private void RecieveLogicList(NetworkMessage msg)
  269. {
  270. //try to read base message as a logic message
  271. LogicProtocols.LogicMsg logicMsg;
  272. if (!msg.TryRead(out logicMsg))
  273. return;
  274. ////Debug that we have recieved it
  275. ////Debug.Log("Recieved function from " + ClientList[msg.conn.connectionId].Name);
  276. //Update player Data with recieved list
  277. playerData[msg.conn.connectionId].blockReader.LogicChain = new List<LogicBlock>(logicMsg.elements);
  278. playerData[msg.conn.connectionId].recievedList = true;
  279. }
  280. #endregion Networking Functions
  281. }
  282. public class PlayerData
  283. {
  284. public Character character;
  285. public BlockReader blockReader;
  286. public ClientData client;
  287. public bool recievedList;
  288. public bool isDead = false;
  289. public PlayerData(Character character, ClientData client)
  290. {
  291. this.character = character;
  292. this.client = client;
  293. blockReader = new BlockReader();
  294. }
  295. }