private void InsertOneObstacle(int buttonId, bool onPlayerPath) { while (true) { //Calculates the shortest distance before adding the obstacle. GameObject algorithmObject = Instantiate(modifiedDijkstraAlgorithmPrefab); if (MainScript.CurrentLevelCount != -1) { MainScript.GarbageCollectorGameObjects.Add(algorithmObject); } ModifiedDijkstraAlgorithm algorithm = algorithmObject.GetComponent <ModifiedDijkstraAlgorithm>(); if (onPlayerPath) { //path between start and target node algorithm.Initialize(MainScript.AllNodes[playerStartPosition], MainScript.AllNodes[MainScript.NumberOfNodes - 1]); } else { //path between the node in the upper right corner and the node in the lower left corner algorithm.Initialize(MainScript.AllNodes[opponentStartPosition], MainScript.AllNodes[MainScript.Height - 1]); } algorithm.CalculateModifiedDijkstraAlgorithm(); List <NodeController> shortestPath = algorithm.ShortestPath; //Gets randomly a node of the shortest path as obstacle. int randomNumber = Random.Range((int)Math.Floor((double)shortestPath.Count / 4), (int)(shortestPath.Count - Math.Floor((double)shortestPath.Count / 10))); NodeController startNode = shortestPath[randomNumber]; NodeController targetNode = shortestPath[randomNumber + 1]; //Sets the new values of the obstacle EdgeController edge = startNode.GetEdgeToNode(targetNode); if (edge.Obstacle != -1) { continue; } TransformEdge(edge, buttonId); //Calculates the shortest distance after adding the obstacle. GameObject algorithmObject1 = Instantiate(modifiedDijkstraAlgorithmPrefab); if (MainScript.CurrentLevelCount != -1) { MainScript.GarbageCollectorGameObjects.Add(algorithmObject1); } ModifiedDijkstraAlgorithm algorithm1 = algorithmObject1.GetComponent <ModifiedDijkstraAlgorithm>(); if (onPlayerPath) { algorithm1.Initialize(MainScript.AllNodes[playerStartPosition], MainScript.AllNodes[MainScript.NumberOfNodes - 1]); } else { algorithm1.Initialize(MainScript.AllNodes[opponentStartPosition], MainScript.AllNodes[MainScript.Height - 1]); } algorithm1.CalculateModifiedDijkstraAlgorithm(); int shortestDistanceWithObstacle = algorithm1.ShortestDistance; //Tries to insert a valid button if (InsertButton(shortestDistanceWithObstacle, startNode, shortestPath, buttonId, onPlayerPath, edge)) { Destroy(algorithmObject); Destroy(algorithmObject1); //Changes the color of the obstacle to its initial value. edge.ChangeColorOfObstacle(0); break; } else { //Resets the edge and tries to find another location for the obstacle. Destroy(algorithmObject); Destroy(algorithmObject1); ResetEdge(edge); } } }