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.

471 lines
17 KiB

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using Networking.Server;
  5. using TMPro;
  6. using UnityEngine.UI;
  7. using System.Linq;
  8. [CreateAssetMenu(menuName = "Major Project/GameModes/Racetrack", order = 201)]
  9. public class RacetrackGameMode : GameMode
  10. {
  11. public MapManager mapManager;
  12. public blockSpawn spawn;
  13. public int MaxRound = 999;
  14. public string nextScene = "ServerTestScene";
  15. List<ClientData> ConnectedClients;
  16. public Material OverlayMaterial;
  17. public float scrollSpeed = 1.0f; //The rate at which the level will scroll past
  18. [SerializeField]
  19. [Tooltip("Layers to ignore when checking for blocks")]
  20. public LayerMask Ignore;
  21. public int RoundCount { get; private set; }
  22. private Dictionary<ClientData, List<Block>> BlocksOwned;
  23. int currentBoulderCount;
  24. /// <summary>
  25. /// Called once before any players have spawned
  26. /// </summary>
  27. protected override void OnPreGameStart()
  28. {
  29. mapManager.init();
  30. }
  31. /// <summary>
  32. /// Called once all players have finished their moves but before the Objective is checked
  33. /// </summary>
  34. protected override void OnRoundEnd(PlayerData[] allPlayers)
  35. {
  36. cameraCheck(allPlayers);
  37. //At the end of each round, any stuck players are freed to resume moving next round
  38. respawnPlayers(allPlayers);
  39. /*foreach (PlayerData player in allPlayers)
  40. {
  41. player.character.stuck = false;
  42. if (player.character.respawnNeeded && player.client.Lives > 0)
  43. {
  44. player.character.respawnCharacter();
  45. }
  46. }*/
  47. RoundCount++;
  48. }
  49. void respawnPlayers(PlayerData[] allPlayers)
  50. {
  51. //First step: determine if anyone is waiting to respawn
  52. List<PlayerData> respawningPlayers = new List<PlayerData>();
  53. List<PlayerData> survivingPlayers = new List<PlayerData>();
  54. foreach (PlayerData player in allPlayers)
  55. {
  56. if (player.client.Lives > 0)
  57. {
  58. if (player.character.respawnNeeded)
  59. {
  60. respawningPlayers.Add(player);
  61. }
  62. else
  63. {
  64. survivingPlayers.Add(player);
  65. }
  66. }
  67. }
  68. //If nobody needs a respawn, we stop here. Otherwise, we carry on
  69. if (respawningPlayers.Count > 0)
  70. {
  71. //Next step: figure out the appropriate respawn point
  72. //If there are any players left, it will be the average of their positions
  73. //Otherwise, it will be as close to the centre of the screen as possible
  74. Vector3 respawnLocation = new Vector3(0.0f, -0.5f, 0.0f);
  75. //Debug.Log("Initial respawn location: " + respawnLocation);
  76. if (survivingPlayers.Count > 0) //If any players are not currently waiting to respawn, we get the average of their locations
  77. {
  78. //Debug.Log("Averaging survivor locations");
  79. //We list the positions of all the surviving players
  80. List<Vector3> survivingPlayerLocations = new List<Vector3>();
  81. foreach (PlayerData player in survivingPlayers)
  82. {
  83. survivingPlayerLocations.Add(player.character.transform.position);
  84. }
  85. foreach (Vector3 vec in survivingPlayerLocations)
  86. {
  87. respawnLocation += vec;
  88. }
  89. respawnLocation = respawnLocation / survivingPlayers.Count;
  90. //Debug.Log("Averaged survivor locations, new respawn location: " + respawnLocation);
  91. }
  92. else //Otherwise, we go for the middle of the screen
  93. {
  94. //Debug.Log("Seeking the middle of the screen");
  95. //We start in the middle of the track, at the back, and scroll forward until we're past the centre of the camera's view
  96. respawnLocation.x = mapManager.startX;
  97. Vector3 respawnLocationVP = Camera.main.WorldToViewportPoint(respawnLocation);
  98. while (respawnLocationVP.x < 0.5f || respawnLocationVP.y < 0.5f)
  99. {
  100. respawnLocation.x += 1.0f;
  101. respawnLocationVP = Camera.main.WorldToViewportPoint(respawnLocation);
  102. //Debug.Log("respawnLocation = " + respawnLocation + ", viewport = " + respawnLocationVP);
  103. }
  104. //Debug.Log("Found middle of camera view, new respawn location: " + respawnLocation);
  105. }
  106. //Now we randomly pick blocks in the vicinity of this point to respawn players on
  107. //Valid blocks are those within x & +/-1 from the chosen location
  108. //If we don't find enough open, unoccupied blocks within that radius, then we widen it
  109. int radius = 0;
  110. List<Block> respawnBlocks;
  111. do
  112. {
  113. respawnBlocks = new List<Block>();
  114. radius++;
  115. //Debug.Log("Finding respawn blocks at radius = " + radius);
  116. for (int i = -1 * radius; i <= radius; i++)
  117. {
  118. for (int j = -1 * radius; j <= radius; j++)
  119. {
  120. Block currentBlock;
  121. Vector3 currentPos = new Vector3(respawnLocation.x + i, respawnLocation.y, respawnLocation.z + j);
  122. //Debug.Log("Checking position " + currentPos);
  123. if (Block.isBlockAtPosition(currentPos, 1, ~Ignore, out currentBlock))
  124. {
  125. /*Debug.Log("Found block at " + currentPos
  126. + ". is_Walkable = " + currentBlock.is_Walkable
  127. + ", currentBlock is Water = " + (currentBlock is Water)
  128. + ", isPit = " + currentBlock.isPit
  129. + ", no currentPlayer = " + (currentBlock.CurrentPlayer == null));*/
  130. if (currentBlock.is_Walkable //Are we allowed on this block?
  131. && !(currentBlock is Water) && !(currentBlock.isPit) //Don't respawn on top of instant traps
  132. && currentBlock.CurrentPlayer == null) //Block must be unoccupied
  133. {
  134. respawnBlocks.Add(currentBlock);
  135. //Debug.Log("Added block at " + currentPos);
  136. }
  137. else
  138. {
  139. //Debug.Log("Block at " + currentPos + " invalid");
  140. }
  141. }
  142. else
  143. {
  144. //Debug.Log("No block at " + currentPos);
  145. }
  146. }
  147. }
  148. } while (respawnBlocks.Count < respawningPlayers.Count);
  149. //Debug.Log("Possible respawn spots: ");
  150. /*foreach(Block block in respawnBlocks)
  151. {
  152. Debug.Log(block.transform.position);
  153. }*/
  154. foreach (PlayerData player in respawningPlayers)
  155. {
  156. //We randomly pick a block for them to respawn on
  157. int respawnIndex = (int)Random.Range(0.0f, (float)respawnBlocks.Count);
  158. //Debug.Log("Respawn index = " + respawnIndex);
  159. Block respawnBlock = respawnBlocks[respawnIndex];
  160. //Debug.Log("Respawn location = " + respawnBlock.transform.position);
  161. player.character.respawnCharacter(respawnBlock);
  162. respawnBlocks.Remove(respawnBlock); //Then we remove it from the list for the next player
  163. }
  164. }
  165. }
  166. void cameraCheck(PlayerData[] allPlayers)
  167. {
  168. //Get the average x-position of all players
  169. float xAvg = 0.0f;
  170. int livePlayerCount = 0;
  171. foreach (PlayerData player in allPlayers)
  172. {
  173. if (!(player.character.respawnNeeded) && player.client.Lives > 0)
  174. {
  175. xAvg += player.character.transform.position.x;
  176. livePlayerCount++;
  177. }
  178. }
  179. if (livePlayerCount > 0)
  180. {
  181. xAvg = xAvg / livePlayerCount;
  182. }
  183. //Turn that position into a vector in viewport space
  184. Vector3 xAvgPos = new Vector3(xAvg, 0.0f, 0.0f);
  185. Vector3 xAvgVP = Camera.main.WorldToViewportPoint(xAvgPos);
  186. //Debug.Log("xAvgPos = " + xAvgPos + ", xAvgVP = " + xAvgVP);
  187. //We move the camera forward by at least one increment
  188. //Keep doing it until the average x-position is roughly centred
  189. do
  190. {
  191. Camera.main.transform.Translate(scrollSpeed, 0, 0, Space.World);
  192. xAvgVP = Camera.main.WorldToViewportPoint(xAvgPos);
  193. //Debug.Log("Camera = " + Camera.main.transform.position + ", xAvgVP = " + xAvgVP);
  194. } while (xAvgVP.x > 0.5f || xAvgVP.y > 0.5f);
  195. //If the foremost player is off the screen, scroll forward to catch up with them
  196. //Find who's furthest ahead
  197. PlayerData playerAhead = allPlayers[0];
  198. foreach (PlayerData player in allPlayers)
  199. {
  200. if (player.client.Lives > 0 && player.character.transform.position.x > playerAhead.character.transform.position.x)
  201. {
  202. playerAhead = player;
  203. }
  204. }
  205. //Turn their position to a viewport vector
  206. Vector3 playerVP = Camera.main.WorldToViewportPoint(playerAhead.character.transform.position);
  207. //If that position is not in view, advance until it is
  208. while (playerVP.x > 1 || playerVP.y > 1)
  209. {
  210. Camera.main.transform.Translate(scrollSpeed, 0, 0, Space.World);
  211. playerVP = Camera.main.WorldToViewportPoint(playerAhead.character.transform.position);
  212. }/**/
  213. //If anyone is out of view at this point, they are dead and need to respawn
  214. foreach (PlayerData player in allPlayers)
  215. {
  216. if (player.client.Lives > 0 && !(player.character.respawnNeeded))
  217. {
  218. playerVP = Camera.main.WorldToViewportPoint(player.character.transform.position);
  219. if (playerVP.x < 0.0f || playerVP.y < 0.0f)
  220. {
  221. player.character.respawnNeeded = true;
  222. }
  223. }
  224. }
  225. //We check for track sections we need to add/remove
  226. mapManager.checkTrack();
  227. //spawn.wakeup();
  228. //Move the camera forward at a steady rate each round
  229. /*if (scrollSpeed > 0.0f)
  230. {
  231. Camera.main.transform.Translate(scrollSpeed, 0, 0, Space.World);
  232. mapManager.checkTrack();
  233. //Debug.Log("New camera position at x = " + Camera.main.transform.position.x);
  234. //Plan: get average position of surviving players, centre camera view on it
  235. //Also, will need to check every time someone moves: are they still on camera?
  236. //If ahead of camera, advance it until they're visible
  237. //If behind camera, they lose a life & respawn
  238. }
  239. else
  240. {
  241. //Debug.Log("Not scrolling");
  242. }*/
  243. }
  244. /// <summary>
  245. /// Checks if the Game is finished
  246. /// </summary>
  247. /// <returns>returns if game is finished</returns>
  248. public override bool isGameOver(PlayerData[] allPlayers)
  249. {
  250. return (RoundCount >= MaxRound -1);
  251. }
  252. /// <summary>
  253. /// Called once per player after they have moved onto a block
  254. /// </summary>
  255. /// <param name="character">Character which moved</param>
  256. /// <param name="client">Client of the character</param>
  257. /// <param name="currentBlock">Block moved onto</param>
  258. protected override void OnPlayerMoved(Character character, ClientData client, Block currentBlock)
  259. {
  260. handleFalling(character, client, currentBlock, character.justMoved);
  261. /*Debug.Log("Moved to square at " + currentBlock.transform.position.x + ", "
  262. + currentBlock.transform.position.y + ", "
  263. + currentBlock.transform.position.z);
  264. //If a character has fallen in the water or into a pit, we mark that fact, and they lose the rest of their turn
  265. character.inWater = currentBlock.isWater;
  266. character.respawnNeeded = currentBlock.isPit;
  267. if (character.inWater == true || character.respawnNeeded == true)
  268. {
  269. character.stuck = true;
  270. }
  271. Debug.Log("inWater = " + character.inWater + ", respawnNeeded = " + character.respawnNeeded + ", stuck = " + character.stuck);*/
  272. //Commented out because we don't do this in the racetrack mode
  273. /*ClientData OwnedClient;
  274. Material overlay = null;
  275. if (isOwned(currentBlock, out OwnedClient))
  276. {
  277. if (OwnedClient == client)
  278. return;
  279. BlocksOwned[OwnedClient].Remove(currentBlock);
  280. foreach (Material mat in currentBlock.GetComponent<Renderer>().materials)
  281. {
  282. if (mat.name == OverlayMaterial.name + " (Instance)")
  283. overlay = mat;
  284. }
  285. }
  286. if (overlay == null)
  287. {
  288. overlay = new Material(OverlayMaterial);
  289. List<Material> mats = new List<Material>(currentBlock.GetComponent<Renderer>().materials);
  290. mats.Add(overlay);
  291. currentBlock.GetComponent<Renderer>().materials = mats.ToArray();
  292. }
  293. overlay.SetColor("_NewColor", client.Color);
  294. if (!BlocksOwned.ContainsKey(client))
  295. BlocksOwned.Add(client, new List<Block>());
  296. BlocksOwned[client].Add(currentBlock);
  297. if (overlay != null)
  298. currentBlock.StartCoroutine(AnimateBlock(overlay, 0.25f));*/
  299. }
  300. protected override void OnRoundStart(PlayerData[] allPlayers)
  301. {
  302. }
  303. protected override void OnAllPlayersMoved(PlayerData[] allPlayers)
  304. {
  305. foreach (PlayerData player in allPlayers)
  306. {
  307. /* The justMoved variable is used to determine whether a player taking their turn in the water should become stuck
  308. * (because they moved into/in the water), or not (because they're turning while remaining in the same square)
  309. * It's not needed from move to move, so we clear it
  310. */
  311. player.character.justMoved = false;
  312. /* if (BlocksOwned.ContainsKey(player.client))
  313. player.client.SceneScore = BlocksOwned[player.client].Count;
  314. else
  315. player.client.SceneScore = 0;*/
  316. }
  317. }
  318. protected override void OnGameOver(PlayerData[] allPlayers)
  319. {
  320. throw new System.NotImplementedException();
  321. }
  322. private bool isOwned(Block block, out ClientData client)
  323. {
  324. client = null;
  325. foreach (KeyValuePair<ClientData, List<Block>> ownedList in BlocksOwned)
  326. {
  327. if (ownedList.Value.Contains(block))
  328. {
  329. client = ownedList.Key;
  330. return true;
  331. }
  332. }
  333. return false;
  334. }
  335. private void handleFalling(Character character, ClientData client, Block currentBlock, bool didMove)
  336. {
  337. //If a character has fallen in the water or into a pit, we mark that fact, and they lose the rest of their turn
  338. character.inWater = currentBlock.isWater;
  339. character.respawnNeeded = currentBlock.isPit;
  340. character.onCrystal = currentBlock.isCrystals;
  341. character.underRock = currentBlock.isRock;
  342. if (didMove && (character.inWater || character.respawnNeeded))
  343. {
  344. character.stuck = true;
  345. }
  346. //Debug.Log("inWater = " + character.inWater + ", respawnNeeded = " + character.respawnNeeded + ", stuck = " + character.stuck);
  347. }
  348. protected override void OnPlayerKilled(Character character, ClientData client)
  349. {
  350. if (character.respawnNeeded || character.onCrystal)
  351. {
  352. character.lives -= 1;
  353. character.ClientLink.Lives = character.lives;
  354. }
  355. if(character.underRock && currentBoulderCount < 1)
  356. {
  357. character.lives -= 1;
  358. character.ClientLink.Lives = character.lives;
  359. }
  360. }
  361. private IEnumerator AnimateBlock(Material mat, float time)
  362. {
  363. float timeElasped = 0;
  364. while (timeElasped < time)
  365. {
  366. mat.SetFloat("_Multiplier", (timeElasped / time));
  367. yield return new WaitForEndOfFrame();
  368. timeElasped += Time.deltaTime;
  369. }
  370. mat.SetFloat("_Multiplier", 1);
  371. }
  372. protected override void OnGameStart(PlayerData[] AllPlayers)
  373. {
  374. BlocksOwned = new Dictionary<ClientData, List<Block>>();
  375. RoundCount = 0;
  376. AllPlayers = getPlayerOrder(AllPlayers);
  377. for (int i = 0; i < AllPlayers.Length; i++)
  378. {
  379. OnPlayerMoved(AllPlayers[i].character, AllPlayers[i].client, AllPlayers[i].character.CurrentBlock);
  380. }
  381. }
  382. public override PlayerData[] getPlayerOrder(PlayerData[] AllPlayers)
  383. {
  384. AllPlayers = AllPlayers.ToArray().OrderBy(unit => unit.character.CurrentBlock.transform.position.x).ToArray();
  385. int order = 1;
  386. foreach(PlayerData data in AllPlayers)
  387. {
  388. data.character.runOrder = order;
  389. order++;
  390. }
  391. return AllPlayers;
  392. }
  393. }