void MoveBlock(Block blockToMove, float duration) { if ((blockToMove.coord - emptyBlock.coord).sqrMagnitude == 1) { if (!blockIsMoving && !state.Equals(PuzzleState.Shuffling)) { source.clip = slide; source.Play(); } blocks[blockToMove.coord.x, blockToMove.coord.y] = emptyBlock; blocks[emptyBlock.coord.x, emptyBlock.coord.y] = blockToMove; Vector2Int targetCoord = emptyBlock.coord; emptyBlock.coord = blockToMove.coord; blockToMove.coord = targetCoord; Vector2 targetPosition = emptyBlock.transform.position; emptyBlock.transform.position = blockToMove.transform.position; blockToMove.MoveToPosition(targetPosition, duration); blockIsMoving = true; } }
public PuzzleResults ApplyAStar(Heuristic heuristic) { PriorityQueue <PuzzleState> fringe = new PriorityQueue <PuzzleState>(); // Closed set HashSet <PuzzleState> visited = new HashSet <PuzzleState>(); // We start with only the initial state generated. int numGenerated = 1; int numExpanded = 0; PuzzleState pathEnd = null; fringe.Enqueue(InitState, 0); while (!fringe.IsEmpty()) { PuzzleState current = fringe.Dequeue(); visited.Add(current); numExpanded++; // Goal check. if (current.Equals(GoalState)) { pathEnd = current; break; } List <PuzzleState> successors = current.GetSuccessors(); foreach (PuzzleState s in successors) { if (!visited.Contains(s)) { // Compute heuristic value and add to total cost to get priority. int hValue = Int32.MaxValue; if (heuristic == Heuristic.MisplacedTiles) { hValue = s.ComputeMisplacedTileDistance(GoalState); } else if (heuristic == Heuristic.ManhattanDistance) { hValue = s.ComputeManhattanDistance(GoalState); } else if (heuristic == Heuristic.None) { hValue = 0; } else { throw new ArgumentException("Expected MisplacedTiles or ManhattanDistance heuristic."); } int priority = s.Depth + hValue; bool alreadyExisted = fringe.Enqueue(s, priority); if (!alreadyExisted) { numGenerated++; } } } } // Build path into list. List <PuzzleState> path = new List <PuzzleState>(); PuzzleState currPathNode = pathEnd; path.Add(currPathNode); while (currPathNode.Prev != null) { path.Add(currPathNode.Prev); currPathNode = currPathNode.Prev; } path.Reverse(); PuzzleResults results = new PuzzleResults(numGenerated, numExpanded, path); return(results); }