Hello there,
I'm currently developing a text-based game using Javascript. In my code, I have a variable called map
which is an object containing information about different rooms in the game. I found an algorithm that I would like to modify for my specific needs, but I'm unsure how to do so.
Here is a snippet of my variable:
/**
* [003]-[004]
* | |
* [001]-[002] [007]
* | |
* [005]-[006]
**/
var map = {
"001" : {
"Id" : "001",
"Name" : "Room 001",
"Directions" : {
"N" : "",
"S" : "",
"E" : "002",
"W" : ""
}
}, // Other room objects omitted for brevity
};
function findSteps( id, map, array ) {
if ( ! ( map && "object" === typeof map ) ) { return; }
if ( map.Id === id ) { return map; }
for ( var x in map ) {
if ( Object.hasOwnProperty.call( map, x ) ) {
map.Id && array.push( map.Id ); //used to exclude undefined
var result = findSteps( id, map[ x ], array );
if ( result !== undefined ) {
return [ result, array ];
}
}
}
}
console.dir( findSteps( "004", map, [] ) );
<p>I want the function to return an array of arrays containing all possible paths in the game. This will help me determine the closest available path later on.</p>
<p>The desired output would look something like this:</p>
<pre><code>output = [
[ "001", "002", "003", "004" ],
[ "001", "002", "005", "006", "007", "004" ]
]
I also need the function to accept a starting Id
and stop the recursion after a certain number of iterations if no path is found.
If you have any hints or tips, they would be much appreciated.
Thank you for your help!
Edit:
After considering everything, I believe I only need to find the shortest path.
Edit:
http://jsfiddle.net/GxZYX/1/ is where I tested implementing breadth-first search (currently buggy).