| | | 1 | | using System.Collections.Generic; |
| | | 2 | | using System.Linq; |
| | | 3 | | |
| | | 4 | | using UnityEngine; |
| | | 5 | | using UnityEngine.Networking; |
| | | 6 | | |
| | | 7 | | using TMPro; |
| | | 8 | | |
| | | 9 | | using Newtonsoft.Json; |
| | | 10 | | |
| | | 11 | | using MyBox; |
| | | 12 | | using System.Collections; |
| | | 13 | | |
| | | 14 | | namespace DroneGame |
| | | 15 | | { |
| | | 16 | | /// <summary>Mostly just a short way to type the dictionary inside a dictionary |
| | | 17 | | /// for the parsed data from the API</summary> |
| | | 18 | | public sealed class ParsedData : Dictionary<string, Dictionary<string, float>> |
| | | 19 | | { |
| | | 20 | | |
| | | 21 | | } |
| | | 22 | | |
| | | 23 | | /// <summary>The returned final path</summary> |
| | | 24 | | public struct PathReturn |
| | | 25 | | { |
| | | 26 | | /// <summary>Calculated total time that it would take the drone to travel</summary> |
| | | 27 | | public float totalTime; |
| | | 28 | | |
| | | 29 | | /// <summary>The path in coordinates</summary> |
| | | 30 | | public List<string> path; |
| | | 31 | | |
| | | 32 | | /// <summary>The tile data of the coordinates</summary> |
| | | 33 | | public List<TileData> tiles; |
| | | 34 | | } |
| | | 35 | | |
| | | 36 | | /// <summary>Dijkstras algorithm returns all paths to the Start position, |
| | | 37 | | /// since that operation can take a while to complete depending on the amount of nodes |
| | | 38 | | /// we cache the results </summary> |
| | | 39 | | public struct CachedPath |
| | | 40 | | { |
| | | 41 | | /// <summary>Key is the coordinate and value is |
| | | 42 | | /// how long it would take to reach the start position </summary> |
| | | 43 | | public Dictionary<string, float> shortestPath; |
| | | 44 | | |
| | | 45 | | /// <summary>Key is the coordinate and value is the shortest next path to Start</summary> |
| | | 46 | | public Dictionary<string, string> previousNodes; |
| | | 47 | | } |
| | | 48 | | |
| | | 49 | | /// <summary>The 2D grid that will be used for the path finding</summary> |
| | | 50 | | public sealed class Grid : MonoBehaviour |
| | | 51 | | { |
| | | 52 | | |
| | 2 | 53 | | public string url = "https://mocki.io/v1/10404696-fd43-4481-a7ed-f9369073252f"; |
| | 2 | 54 | | readonly Dictionary<string, CachedPath> _cachedPaths = new(); |
| | | 55 | | public ParsedData parsed; |
| | 2 | 56 | | List<string> _pathHistory = new(); |
| | | 57 | | |
| | | 58 | | [Header("Prefabs/Assets")] |
| | | 59 | | [SerializeField] Tile _tilePrefab; |
| | | 60 | | [SerializeField] Connector _connectorPrefab; |
| | | 61 | | [SerializeField] Drone _drone; |
| | | 62 | | |
| | | 63 | | [Header("UI Inputs")] |
| | | 64 | | [SerializeField] TMP_InputField _startCoordinateInput; |
| | | 65 | | [SerializeField] TMP_InputField _pickupCoordinateInput; |
| | | 66 | | [SerializeField] TMP_InputField _dropOffCoordinateInput; |
| | | 67 | | |
| | | 68 | | [Header("Other UI")] |
| | | 69 | | [SerializeField] TextMeshProUGUI _pathElement; |
| | | 70 | | [SerializeField] TextMeshProUGUI _pathHistoryUi; |
| | | 71 | | [SerializeField] TextMeshProUGUI _loading; |
| | | 72 | | |
| | | 73 | | |
| | 2 | 74 | | readonly HashSet<Tile> _changedColorsTiles = new(); |
| | | 75 | | |
| | | 76 | | /// <summary>Dict used to convert from letters to numbers</summary> |
| | 2 | 77 | | private readonly Dictionary<char, int> _letterToInt = new(){ |
| | | 78 | | {'A', 0}, |
| | | 79 | | {'B', 1}, |
| | | 80 | | {'C', 2}, |
| | | 81 | | {'D', 3}, |
| | | 82 | | {'E', 4}, |
| | | 83 | | {'F', 5}, |
| | | 84 | | {'G', 6}, |
| | | 85 | | {'H', 7} |
| | | 86 | | }; |
| | | 87 | | Dictionary<string, TileData> _allTilesData; |
| | | 88 | | Dictionary<string, Tile> _allTiles; |
| | | 89 | | string _lastPath; |
| | | 90 | | |
| | | 91 | | public TileData this[string coordinate] |
| | | 92 | | { |
| | 66 | 93 | | get => _allTilesData[coordinate]; |
| | | 94 | | } |
| | | 95 | | |
| | | 96 | | void PushToHistory(string entry) |
| | 0 | 97 | | { |
| | 0 | 98 | | _pathHistory.Add(entry); |
| | 0 | 99 | | var historyCount = _pathHistory.Count; |
| | 0 | 100 | | if (historyCount > 5) _pathHistory.RemoveAt(0); |
| | 0 | 101 | | } |
| | | 102 | | |
| | 0 | 103 | | public Vector3 GetTileWorldCoordinate(string coordinate) => _allTilesData[coordinate].globalCoordinates; |
| | | 104 | | |
| | | 105 | | /// <summary>This is a default unity function, it is called when the object is instantiated into the scene</summary> |
| | | 106 | | [ButtonMethod] |
| | | 107 | | void Awake() |
| | 1 | 108 | | { |
| | 1 | 109 | | StartCoroutine(DownloadAndParseGridData(url)); |
| | 1 | 110 | | } |
| | | 111 | | |
| | | 112 | | /// <summary>This is meant to be called from a button in the UI |
| | | 113 | | /// This method does: |
| | | 114 | | /// * Set some colors for a couple tiles |
| | | 115 | | /// * Get inputs from the UI |
| | | 116 | | /// * Call the pathfinding functions |
| | | 117 | | /// * Start the drone Coroutine that makes it move |
| | | 118 | | /// </summary> |
| | | 119 | | public void MoveDrone() |
| | 0 | 120 | | { |
| | 0 | 121 | | if (_drone.alreadyMoving) return; |
| | | 122 | | |
| | 0 | 123 | | var start = _startCoordinateInput.text.ToUpper(); |
| | 0 | 124 | | var pickup = _pickupCoordinateInput.text.ToUpper(); |
| | 0 | 125 | | var dropOff = _dropOffCoordinateInput.text.ToUpper(); |
| | | 126 | | |
| | 0 | 127 | | foreach (var currTile in _changedColorsTiles) currTile.ResetColor(); |
| | 0 | 128 | | _changedColorsTiles.Clear(); |
| | 0 | 129 | | SetColor(start, Color.green); |
| | 0 | 130 | | SetColor(pickup, Color.yellow); |
| | 0 | 131 | | SetColor(dropOff, Color.blue); |
| | | 132 | | |
| | 0 | 133 | | if (_lastPath != null) PushToHistory(_lastPath); |
| | 0 | 134 | | var shortestPath = GetShortestPath(new string[] { start, pickup, dropOff }); |
| | 0 | 135 | | _lastPath = $"Path: {string.Join(" -> ", shortestPath.path)}\nTotal Time:{shortestPath.totalTime}"; |
| | 0 | 136 | | _pathElement.text = _lastPath; |
| | 0 | 137 | | _pathHistoryUi.text = string.Join('\n', _pathHistory); |
| | | 138 | | |
| | 0 | 139 | | StartCoroutine(_drone.FollowPath(shortestPath.tiles)); |
| | 0 | 140 | | } |
| | | 141 | | |
| | | 142 | | /// <summary>Set color of a tile based o it's coordinates</summary> |
| | | 143 | | private void SetColor(string coords, Color color) |
| | 0 | 144 | | { |
| | 0 | 145 | | var tileToChange = _allTiles[coords]; |
| | 0 | 146 | | tileToChange.SetColor(color); |
| | 0 | 147 | | _changedColorsTiles.Add(tileToChange); |
| | 0 | 148 | | } |
| | | 149 | | |
| | | 150 | | /// <summary>Download and parse the API</summary> |
| | | 151 | | IEnumerator DownloadAndParseGridData(string url) |
| | 1 | 152 | | { |
| | 1 | 153 | | var www = UnityWebRequest.Get(url); |
| | | 154 | | |
| | 1 | 155 | | yield return www.SendWebRequest(); |
| | | 156 | | |
| | 1 | 157 | | if (www.result != UnityWebRequest.Result.Success) Debug.Log(www.error); |
| | | 158 | | |
| | 1 | 159 | | var json = www.downloadHandler.text; |
| | 1 | 160 | | parsed = JsonConvert.DeserializeObject<ParsedData>(json); |
| | 1 | 161 | | _loading?.gameObject.SetActive(false); |
| | | 162 | | |
| | | 163 | | #if !UNITY_INCLUDE_TESTS |
| | | 164 | | if (_loading == null) throw new("Loading UI not defined"); |
| | | 165 | | #endif |
| | 1 | 166 | | GenerateGrid(parsed); |
| | | 167 | | #if !UNITY_INCLUDE_TESTS |
| | | 168 | | _drone.Initialize(this); |
| | | 169 | | #endif |
| | 1 | 170 | | } |
| | | 171 | | |
| | | 172 | | /// <summary>Generate grid based on the parsed API</summary> |
| | | 173 | | void GenerateGrid(ParsedData parsed) |
| | 1 | 174 | | { |
| | 1 | 175 | | _allTilesData = new(); |
| | 1 | 176 | | _allTiles = new(); |
| | | 177 | | |
| | 131 | 178 | | foreach (var currParsedTile in parsed) |
| | 64 | 179 | | { |
| | 64 | 180 | | var coordinate = currParsedTile.Key; |
| | 64 | 181 | | var neighbors = currParsedTile.Value; |
| | | 182 | | |
| | 64 | 183 | | var currTile = GetOrCreateTile(coordinate); |
| | | 184 | | |
| | 64 | 185 | | var currInstance = Instantiate(_tilePrefab, transform); |
| | 64 | 186 | | currInstance.Initialize(currTile); |
| | | 187 | | |
| | 64 | 188 | | _allTiles[coordinate] = currInstance; |
| | | 189 | | |
| | 640 | 190 | | foreach (var currNeighbor in neighbors) |
| | 224 | 191 | | { |
| | 224 | 192 | | var neighborDistance = currNeighbor.Value; |
| | 224 | 193 | | var neighborCoordinate = currNeighbor.Key; |
| | 224 | 194 | | var converted = GetOrCreateTile(neighborCoordinate); |
| | | 195 | | |
| | 224 | 196 | | currTile.neighbors[neighborCoordinate] = neighborDistance; |
| | | 197 | | |
| | | 198 | | // Since I want to have a visualization of the grid paths, |
| | | 199 | | // I am adding a connector between the tiles and their neighbors |
| | 224 | 200 | | var createdConnection = Instantiate(_connectorPrefab, transform); |
| | 224 | 201 | | createdConnection.Initialize(currTile, converted, neighborDistance); |
| | 224 | 202 | | } |
| | 64 | 203 | | } |
| | 1 | 204 | | } |
| | | 205 | | |
| | | 206 | | /// <summary>Return an already created tile or create a new one if a tile |
| | | 207 | | /// with the coordinates does not already exist</summary> |
| | | 208 | | /// <param name="key">The coordinate in the format A2</param> |
| | | 209 | | /// <returns>A brand new or already existing Tile</returns> |
| | | 210 | | private TileData GetOrCreateTile(string key) |
| | 288 | 211 | | { |
| | 288 | 212 | | if (_allTilesData.ContainsKey(key)) |
| | 224 | 213 | | { |
| | 224 | 214 | | return _allTilesData[key]; |
| | | 215 | | } |
| | | 216 | | |
| | 64 | 217 | | var createdTile = new TileData |
| | | 218 | | { |
| | | 219 | | globalCoordinates = FromLetterNumberToVector(key), |
| | | 220 | | letterCoordinate = key, |
| | | 221 | | neighbors = new() |
| | | 222 | | }; |
| | 64 | 223 | | _allTilesData[key] = createdTile; |
| | 64 | 224 | | return createdTile; |
| | 288 | 225 | | } |
| | | 226 | | |
| | | 227 | | /// <summary>Transform letter and number coordinate system to a Vector to be used by Unity later</summary> |
| | | 228 | | private Vector3 FromLetterNumberToVector(string letterAndNumber) |
| | 64 | 229 | | { |
| | 64 | 230 | | var firstNumber = _letterToInt[letterAndNumber[0]]; |
| | 64 | 231 | | var secondNumber = int.Parse(letterAndNumber[1].ToString()); |
| | | 232 | | |
| | 64 | 233 | | return new(firstNumber, 0, secondNumber); |
| | 64 | 234 | | } |
| | | 235 | | |
| | | 236 | | // TODO: Convert this into an async operation |
| | | 237 | | public PathReturn GetShortestPath(string[] positions) |
| | 3 | 238 | | { |
| | 3 | 239 | | var positionsLen = positions.Length; |
| | 3 | 240 | | if (positionsLen < 2) throw new("positions need to have at least 2 items"); |
| | | 241 | | |
| | 3 | 242 | | var totalTime = 0f; |
| | | 243 | | |
| | 3 | 244 | | var path = new List<string>(); |
| | 3 | 245 | | var tiles = new List<TileData>(); |
| | | 246 | | |
| | 18 | 247 | | for (int pathIndex = 1; pathIndex < positionsLen; pathIndex++) |
| | 6 | 248 | | { |
| | 6 | 249 | | var previousCoordinate = positions[pathIndex - 1]; |
| | 6 | 250 | | var nextCoordinate = positions[pathIndex]; |
| | | 251 | | |
| | 6 | 252 | | var currPath = GetShortestPath(previousCoordinate, nextCoordinate); |
| | 6 | 253 | | totalTime += currPath.totalTime; |
| | | 254 | | |
| | 6 | 255 | | if (pathIndex < positionsLen - 1) |
| | 3 | 256 | | { |
| | 3 | 257 | | currPath.path.RemoveAt(currPath.path.Count - 1); |
| | 3 | 258 | | currPath.tiles.RemoveAt(currPath.tiles.Count - 1); |
| | 3 | 259 | | } |
| | | 260 | | |
| | 6 | 261 | | path = path.Concat(currPath.path).ToList(); |
| | 6 | 262 | | tiles = tiles.Concat(currPath.tiles).ToList(); |
| | 6 | 263 | | } |
| | 3 | 264 | | return new() |
| | | 265 | | { |
| | | 266 | | path = path, |
| | | 267 | | totalTime = totalTime, |
| | | 268 | | tiles = tiles |
| | | 269 | | }; |
| | 3 | 270 | | } |
| | | 271 | | |
| | | 272 | | /// <summary>Find the shortest paths between start and end using Dijkstras algorithm |
| | | 273 | | /// All paths to start node are automatically cached so if it is asked |
| | | 274 | | /// again, there's no need to recalculate it</summary> |
| | | 275 | | /// <seealso cref="FindAllPathsFrom"/> |
| | | 276 | | public PathReturn GetShortestPath(string startPosition, string endPosition) |
| | 11 | 277 | | { |
| | | 278 | | // If the API were dynamic, we would recreate the grid in here by simply called Awake after deleting the grid |
| | | 279 | | // But since it is static, we don't have to. |
| | | 280 | | CachedPath currCachedPath; |
| | 11 | 281 | | var path = new List<string>(); |
| | | 282 | | |
| | | 283 | | // No need to do anything other than return start position if the start and end are the same |
| | 11 | 284 | | if (startPosition == endPosition) |
| | 1 | 285 | | { |
| | 1 | 286 | | path.Add(startPosition); |
| | 1 | 287 | | return new PathReturn() |
| | | 288 | | { |
| | | 289 | | path = path, |
| | | 290 | | totalTime = 0, |
| | | 291 | | tiles = new() { _allTilesData[path[0]] } |
| | | 292 | | }; |
| | | 293 | | } |
| | 17 | 294 | | if (_cachedPaths.ContainsKey(startPosition)) currCachedPath = _cachedPaths[startPosition]; |
| | | 295 | | else |
| | 3 | 296 | | { |
| | 3 | 297 | | currCachedPath = FindAllPathsFrom(startPosition); |
| | 3 | 298 | | _cachedPaths[startPosition] = currCachedPath; |
| | 3 | 299 | | } |
| | | 300 | | |
| | 10 | 301 | | var node = endPosition; |
| | 10 | 302 | | var previousNodes = currCachedPath.previousNodes; |
| | 73 | 303 | | while (node != startPosition) |
| | 63 | 304 | | { |
| | 63 | 305 | | path.Add(node); |
| | 63 | 306 | | node = previousNodes[node]; |
| | 63 | 307 | | } |
| | | 308 | | |
| | 10 | 309 | | path.Add(startPosition); |
| | 10 | 310 | | path.Reverse(); |
| | | 311 | | |
| | 10 | 312 | | return new() |
| | | 313 | | { |
| | | 314 | | path = path, |
| | | 315 | | totalTime = currCachedPath.shortestPath[endPosition], |
| | 73 | 316 | | tiles = (from currCoordinate in path select _allTilesData[currCoordinate]).ToList() |
| | | 317 | | }; |
| | 11 | 318 | | } |
| | | 319 | | |
| | | 320 | | /// <summary>Find all paths to the start position using Dijkstras algorithm |
| | | 321 | | /// This is necessary because the API only have seconds instead of distance, which we can use as weight |
| | | 322 | | /// if we had distance information, we could use A* which is more effective</summary> |
| | | 323 | | CachedPath FindAllPathsFrom(string startPosition) |
| | 3 | 324 | | { |
| | 3 | 325 | | var unvisitedNodes = _allTilesData.Keys.ToList(); |
| | 3 | 326 | | var shortestPath = new Dictionary<string, float>(); |
| | 3 | 327 | | var previousNodes = new Dictionary<string, string>(); |
| | | 328 | | |
| | 393 | 329 | | foreach (var currNode in unvisitedNodes) |
| | 192 | 330 | | { |
| | 192 | 331 | | shortestPath[currNode] = float.MaxValue; |
| | 192 | 332 | | } |
| | | 333 | | |
| | 3 | 334 | | shortestPath[startPosition] = 0; |
| | | 335 | | |
| | 195 | 336 | | while (unvisitedNodes.Count > 0) |
| | 192 | 337 | | { |
| | 192 | 338 | | string minNode = null; |
| | 13056 | 339 | | foreach (var currNode in unvisitedNodes) |
| | 6240 | 340 | | { |
| | 6432 | 341 | | if (minNode == null) minNode = currNode; |
| | 6577 | 342 | | else if (shortestPath[currNode] < shortestPath[minNode]) minNode = currNode; |
| | 6240 | 343 | | } |
| | | 344 | | |
| | 192 | 345 | | var neighbors = GetNeighbors(minNode); |
| | 1920 | 346 | | foreach (var currNeighbor in neighbors) |
| | 672 | 347 | | { |
| | 672 | 348 | | var neighborCoordinate = currNeighbor.Key; |
| | 672 | 349 | | var totalCost = shortestPath[minNode] + currNeighbor.Value; |
| | 672 | 350 | | if (totalCost < shortestPath[neighborCoordinate]) |
| | 231 | 351 | | { |
| | 231 | 352 | | shortestPath[neighborCoordinate] = totalCost; |
| | 231 | 353 | | previousNodes[neighborCoordinate] = minNode; |
| | 231 | 354 | | } |
| | 672 | 355 | | } |
| | 192 | 356 | | unvisitedNodes.Remove(minNode); |
| | 192 | 357 | | } |
| | 3 | 358 | | return new CachedPath |
| | | 359 | | { |
| | | 360 | | shortestPath = shortestPath, |
| | | 361 | | previousNodes = previousNodes |
| | | 362 | | }; |
| | 3 | 363 | | } |
| | | 364 | | |
| | | 365 | | /// <summary>Get all neighbors of the tile<summary> |
| | 192 | 366 | | Dictionary<string, float> GetNeighbors(string coordinates) => _allTilesData[coordinates].neighbors; |
| | | 367 | | } |
| | | 368 | | } |