I want a simple algorithm in As3 that finds the shortest path in a simple grid, i need complete path not the only both points or the length.
check image here: http://screencast.com/t/GmR5YaO4L
so i need all the square numbers of the grid that comes in the path from A to B.
Although A* is kind of overkill when there are no obstacles, you might as well use it since I wrote a library for it in AS3: http://www.newarteest.com/flash/astar.html
EDIT: If you are anything less than 100% sure the pathfinding will never have obstacles then I still recommend A* because that gives you the most flexibility, but in your specific case it's pretty easy to find the path without obstacles because you only move once horizontally then vertically (or the other way around) as opposed to diagonally.
First subtract the x and y components of the positions to determine which way is longer and start moving in that direction. Then when the objects are in the same position on that axis, switch to moving in the other direction.
Depending on your needs you can easily build a loop or recursive function that finds the entire path before you traverse it, but it may be simpler to move the object in the correct direction without knowing the entire path ahead of time. While finding the path you need to loop through all the nodes anyway, so you could avoid having to loop through the nodes twice.
Related
I'm having some trouble finding the right approach to coding this.
Take a random-generated 2d array, about 50x50 with each cell having a value 1~99.
Starting at a random position "Green", and the goal is to surround the target "Red" with the lowest amount of actions.
Moving to a neighboring cell takes 1~99 actions depending on it's value.
example small array with low values:
[
Currently the best idea i have is, generate 4 sets of checkpoints based on the diagonals of the target and then using a lot of Dijkstra's to find a path that goes through all of them, as well as the starting point.
One problem i have is this very quickly becomes an extreme numbers of paths.
FROM any starting point "NorthWest-1 to NW-20" TO any ending point in "NE-1 to NE-20", is 400 possibilities. Adding the 3rd and 4th diagonal to that becomes 400 * 20 * 20.
Another problem using diagonal checkpoints is that the problem is not [shortest path from green to a diagonal (orange path)]
[
but rather from "green to any point on the path around red".
Current pseudocode;
take 2 sets of diagonals nearest to Green/start
find the shortest path that connects those diagonals while going through Green
(backtracking through the path is free)
draw a line starting from the target point, in-between the 2 connected diagonals,
set those cells to value infinite to force going around them (and thus around the target)
find the shortest path connecting the now-seperated diagonals
Unfortunately this pseudocode already includes some edge cases where the 'wall' blocks the most efficient path.
If relevant, this will be written in javascript.
Edit, as an edge case it could spiral the target before surrounding, though extremely rare
Edit2; "Surround" means disconnect the target from the rest of the field, regardless of how large the surrounded area is, or even if it includes the starting point (eg, all edges are 0)
Here is another larger field with (probably) optimal path, and 2 fields in text-form:
https://i.imgur.com/yMA14sS.png
https://pastebin.com/raw/YD0AG6YD
For short, let us call paths that surround the target fences. A valid fence is a set of (connected) nodes that makes the target disconnected from the start, but does not include the target. A minimal fence is one that does so while having a minimal cost. A lasso could be a fence that includes a path to the start node. The goal is to build a minimal-cost lasso.
A simple algorithm would be to use the immediate neighborhood of the target as a fence, and run Dijkstra to any of those fence-nodes to build a (probably non-optimal) lasso. Note that, if optimal answers are required, the choice of fence actually influences the choice of path from the start to the fence -- and vice-versa, the choice of path from start to fence can influence how the fence itself is chosen. The problem cannot be split neatly into two parts.
I believe that the following algorithm will yield optimal fences:
Build a path using Dijkstra from start to target (not including the end-points). Let us call this the yellow path.
Build 2 sets of nodes, one on each side of this yellow path, and neighboring it. Call those sets red and blue. Note that, for any given node that neighbors the path, it can either be part of the path, blue set, red set, or is actually an end-point.
For each node in the red set, run Dijkstra to find the shortest path to a node in the blue set that does not cross the yellow path.
For each of those previous paths, see which is shortest after adding the (missing) yellow-path bit to connect the blue and red ends together.
The cost is length(yellowPath) * cost_of_Dijkstra(redStart, anyBlue)
To make a good lasso, it would be enough to run Dijkstra from the start to any fence node. However, I am unsure of whether the final lasso will be optimal or not.
You might want to consider the A* search algorithm instead, you can probably adjust the algorithm to search for all 4 spots at once.
https://en.wikipedia.org/wiki/A*_search_algorithm
Basically A* expands Dijkstra's algorithm by focusing it's search on spots that are "closer" to the destination.
There are a number of other variations for search algorithms that may be more useful for your situation as well in the "Also See" section, though some of them are more suited for video game path planning rather than 2D grid paths.
Edit after reviewing question again:
Seems each spot has a weight. This makes the distance calculation a bit less straightforward. In this case, I would treat it as an optimization. For the heuristic cost function, it may be best to just use the most direct path (diagonal) to the goal as the heuristic cost, and then just use A* search to try to find an even better path.
As for the surround logic. I would treat that as it's own logic and a separate step (likely the second step). Find least cost path to the target first. Then find the cheapest way to surround the path. Honestly, the cheapest way to surround a point is probably worth it's own question.
Once you have both parts, it should be easy enough to merge the two. There will be some point where the two first overlap and that is where they are merged together.
I'm currently making an RTS game in unity and I need a way to calculate the shortest path between two points on a continuous 2d plane where there are certain obstacles.
I have a start position, an end position, and a function that can test whether a position is valid. I need an algorithm that returns a sequence of points to move through in order to get to the destination.
Most of the pathing algorithms like A* and IDA* that I know of require discretized search spaces. I would divide the plane into a grid myself but I fear that it would result in zig zag patterns that look really unnatural when moving along the diagonal. Is there a way to alleviate this problem or a different pathing algorithm I can use? It doesn't even have to find the absolute shortest path, just a path that makes sense.
One approach might be to discretize the search space by considering only points interesting for planing - points on the boundaries of the obstacles, for example only the corners of bounding boxes, and then use any of the algorithms you already know.
Another option would be to compute on a grid and then smoothen the best path found on the grid.
You could create a zig-zaggy path then use Pure Pursuit to smooth it.
I have an idea of creating yet another maze game. However, there is a key difference: maze changes on-the-fly during the game. When I think of the problem the following restrictions come into my mind:
there is main route in the maze which never changes
the main route is the only route which leads to the finish
maze mutation should not block paths back to the main route
It also would be nice to control (affect game difficulty):
how much of the maze gets changed during a single mutation
optionally disable restriction #3 (i.e. player can get blocked in the maze for a while)
EDIT:
The question is: can you suggest an algorithm (or give your ideas) for described maze generation/mutation, which will not violate given restrictions?
You could:
Block a path at random (or using some sneaky criteria).
Scan the maze to see if it has been partitioned into 2 regions that are no longer connected.
If disconnected, you can knock down a wall at random so long as it neighbors both regions.
If your maze has only one path between any two points, step 2 will always split the maze and so #3 will always be needed.
Make a graph connecting all the cells of the maze and the walkable connections between them. To modify the maze, first pick a random wall to knock down, which generates a new edge in the graph. Then find a cycle in the graph that contains that edge, and delete a random, non-main-path edge in that cycle, which will erect an edge somewhere else.
This algorithm ensures that if all cells were reachable at the start, they will remain so. You probably want that feature so you can't ever get trapped.
This is probably quite straightforward. Generate the maze using the standard depth-first-search algorithm. Store the list of cells that form the (only) path from start to exit in a list. When you decide you want to mutate the maze, do the following:
Reset the entire maze to the default state (all walls in place), with the exception of any cell along the critical path, and optionally, a few cells within line-of-sight of the player's current location.
Re-execute the breadth-first search algorithm from the start, with one modification: when choosing which unvisited neighbour to explore, prefer edges that already have the wall removed.
The modification in the second step will ensure that the algorithm first explores the existing paths, then adds on side-passages and so forth from there. It's not even strictly necessary to preserve the critical path if you don't want to - you can regenerate the entire maze except where the user's standing, and it'll remain valid.
I think this ought to always produce a valid tree in the same way the original algorithm would, but I'm not 100% sure about the implications of preserving the cells around the user, which may not be on the critical path. I'm positive the reconfigured maze will always be solvable from where the user is standing, though.
This is a pretty neat idea, too. I love the idea of the maze rearranging itself substantially wherever the user isn't looking. If you're doing this in first-person, you could even use the camera view to change the walls behind the user when they're not looking!
Just wondering if there was a nice (already implemented/documented) algorithm to do the following
boo! http://img697.imageshack.us/img697/7444/sdfhbsf.jpg
Given any shape (without crossing edges) and two points inside that shape, compute all the paths between the two points such that all reflections are perfect reflections. The path lengths should be limited to a certain length otherwise there are infinite solutions. I'm not interested in just shooting out rays to try to guess how close I can get, I'm interested in algorithms that can do it perfectly. Search based, not guess/improvement based.
I think you can do better than computing fans. Call your points A and B. You want to find paths of reflections from A to B.
Start off by reflecting A in an edge, and call the reflection A1. Can you draw a line from A1 to B that only hits that edge? If yes, that means you have a path from A to B that reflects on the edge. Do this for all the edges and you'll get all the single reflection paths that exist. It should be easy to construct these paths using the properties of reflections. Along the way, you need to check that the paths are legal, i.e. they do not cross other edges.
You can continue to find paths consisting of two reflections by reflecting all the first generation reflections of A in all the edges, and checking to see whether a line can be drawn from those points through the reflecting edge to B. Keep on doing this search until the distance of the reflected points from B exceeds a threshold.
I hope this makes sense. It should be easier than chasing fans and dealing with their breakups, even though you're still going to have to do some work.
By the way, this is a corner of a well studied field of billiards on tables of various geometries. Of course, a billiard ball bounces off the side of a table the same way light bounces off a mirror, so this is just another way of thinking of reflections. You can delve into this with search terms like polygonal billiards unfolding illumination, although the mathematicians tend to dwell on finding cases where there are no pool shots between two points on a polygonal table, as opposed to directly solving the problem you've posed.
Think not in terms of rays but fans. A fan would be all the rays emanating from one point and hitting a wall. You can then check if the fan contains the second point and if it does you can determine which ray hits it. Once a fan hits a wall, you can compute the reflected fan by transposing it's origin onto the outside of the wall - by doing this all fans are basically triangle shaped. There are some complications when a fan partially hits a wall and has to be broken into pieces to continue. Anyway, this tree of reflected fans can be traversed breadth first or depth first since you're limiting the total distance.
You may also want to look into radiosity methods, which is probably similar to what I've just described, but is usually done in 3d.
I do not know of any existing solutions for such a problem. Good luck to you if you find one, but incase you don't the first step to a complete but exponential (with regard to the line count) would be to break it into two parts:
Given an ordered subset of walls A,B,C and points P1, P2, calculate if a route is possible (either no solutions or a single unique solution).
Then generate permutations of your walls until you exceed whatever limit you had in mind.
The first part can be solved by a simple set of equations to find the necessary angles for each ray bounce. Then checking each line against existing lines for collisions would tell you if the path is possible.
The parameters to the system of equations would be
angle_1 = normal of line A with P1
angle_2 = normal of line B with intersection of line A
angle_3 = normal of line C with ...
angle_n = normal of line N-1 with P2
Each parameter is bounded by the constraints to hit the next line, which may not be linear (I have not checked). If they are not then you would probably have to pick suitable numerical non-linear solvers.
In response to brainjam
You still need wedges....
alt text http://img72.imageshack.us/img72/6959/ssdgk.jpg
In this situation, how would you know not to do the second reflection? How do you know what walls make sense to reflect over?
I'm working on a simple multiplayer game in which 2-4 players are placed at separate entrypoints in a maze and need to reach a goal point. Generating a maze in general is very easy, but in this case the goal of the game is to reach the goal before everyone else and I don't want the generation algorithm to drastically favor one player over others.
So I'm looking for a maze generation algorithm where the optimal path for each player from the startpoint to the goal is no more than 10% more steps than the average path. This way the players are on more or less an equal playing field. Can anyone think up such an algorithm?
(I've got one idea as it stands, but it's not well thought out and seems far less than optimal -- I'll post it as an answer.)
An alternative to freespace's answer would be to generate a random maze, then assign each cell a value representing the number of moves to reach the end of the maze (you can do both at once if you decide that you're starting at the 'end'). Then pick a distance (perhaps the highest one with n points at that distance?) and place the players at squares with that value.
What about first selecting the position of the players and goal and an equal length path and afterwards build a maze respecting the defined paths? If the paths do not intersect this should easily work, I presume
I would approach this by setting the goal and each player's entry point, then generating paths of similar length for each of them to the goal. Then I would start adding false branches along these paths, being careful to avoid linking to other player's paths, or having a branch connect back to the path. So essentially every branch is a dead end.
This way, you guarantee the paths are similar in length. However it won't allow players to interact with each other. You can however put this in, by creating links between branches such that branch entry points on either path are at a similar distance away from the goal. And on this branch you can branch off more dead ends for fun and profit :-)
The easiest solution I can come up with is to randomly generate an entire maze like normal, then randomly pick the goal point and player startpoints. Once this is done, calculate the shortest path from each startpoint to the goal. Find the average and start 'smoothing' (remove/move barriers -- don't know how this will work) the paths that are significantly above it, until all of the paths are within the proper margin. In addition, it could be possible to take the ones that are significantly below the average and insert additional barriers.
Pick your exit point somewhere in the middle
Start your N paths from there, adding 1 to each path per loop,
until they are as long as you want them to be.
There are your N start points, and they are all the same length.
Add additional branches off of the lines, until the maze is full.