Help Using Path Finding Code

Hi all.
I found some open source code which implements the A Star algorithm to achieve path finding for the purpose of navigating something in a game (although it could really be used for anything). Problem is, I can't get it to work. I've e-mailed the author but no reply yet so I was hoping someone could shed some light on my situation.
The code is meant to find a path on a 2 dimensional grid filled with obstacles using the following methods:
PathFinder star = new PathFinder(grid);
Path p = star.findShortest(startRow,startCol,goalRow,goalCol);
I've made a simple Test class with a small 2D array but when I compile the code I recieve the error:
Incompatible types.
Found: int.
Required: Test.Path
on Path p = star.findShortest(1,1,2,2);
I don't understand this error at all. The findShortest method takes 4 integers and I'm passing it 4 integers! Any ideas what this error means?
Here's my Test class:
import java.util.*;
import javax.swing.plaf.basic.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import javax.swing.filechooser.*;
import java.util.Random;
public class Test
        public static void main(String args[])
                Test test = new Test();
                test.run();
       public final static class Path
                /** 2 for down, 0 is up, 1 is right and 3 is left */
                public int giveMove() {
                    if (size() < 2)
                        return -1;
                    Position last = (Position)positions.get(size() - 1);
                    Position forlast = (Position)positions.get(size() - 2);
                    if (forlast.col - last.col == 1)
                        return 2; //down
                    else if (forlast.col - last.col == -1)
                        return 0; //up
                    else if (forlast.row - last.row == 1)
                        return 1;//right
                    else if (forlast.row - last.row == -1)
                        return 3; //left
                    return -1;
                /** list of positions */
                public List positions;
                public int getCost() { return positions.size() - 1; }
                public int size() { return positions.size(); }
                public void add(Object o) { positions.add(o); }
                /** add (r,c) to the path */
                public void add(int r, int c) {
                    positions.add(new Position(r,c));
                /** get first position */
                public Position head() { return (Position) positions.get(0); }
                public Path(ArrayList positions) { this.positions = positions; }
                public Path(Position initial) {
                    positions = new ArrayList(1);
                    positions.add(initial);
                public Path(int cap) { positions = new ArrayList(cap); }
                public void set(Position front, Path old) {
                    positions.add(front);
                    Iterator i = old.positions.iterator();
                    while (i.hasNext())
                        positions.add(i.next());
        /** position on the grid */
       public static final  class Position
                public int row, col;
                public Position(int row, int col) {
                    this.row = row; this.col = col;
        public void run()
                System.out.println("Test");
                PathFinder star = new PathFinder(grid);
                for(int counter = 0; counter < grid.length; counter++)
                        for (int j=0; j < grid[counter].length; j++)
                                grid[counter][j] = 0;
                Path p = star.findShortest(1, 1, 2, 2);
     private static int[][] grid = new int[2][2];    
} Here's the PathFinder class I downloaded:
import java.util.*;
import javax.swing.plaf.basic.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import javax.swing.filechooser.*;
import java.util.Random;
public final class PathFinder {
    /** the map grid to look on */
    private final int [][] grid;
    /** keep distances to each position here */
    private final int [][] distances;
    /** is gridposition (r, c) empty (empty is -1) ? */
    private boolean isEmpty(int r, int c) {
        return grid[r][c] == -1 ;
    /** pathfinder for grid */
    public PathFinder(int[][] grid) {
        this.grid = grid;
        this.distances = new int [grid.length][grid.length];
    /** clear distances */
    private void clear() {
        for (int i = 0 ; i < distances.length ; i++)
            for (int j = 0 ; j < distances.length ; j++)
distances[i][j] = Integer.MAX_VALUE;
/** position on the grid */
public final static class Position {
public int row, col;
public Position(int row, int col) {
this.row = row; this.col = col;
/** path from start to a certain position */
public final static class Path {
/** 2 for down, 0 is up, 1 is right and 3 is left */
public int giveMove() {
if (size() < 2)
return -1;
Position last = (Position)positions.get(size() - 1);
Position forlast = (Position)positions.get(size() - 2);
if (forlast.col - last.col == 1)
return 2; //down
else if (forlast.col - last.col == -1)
return 0; //up
else if (forlast.row - last.row == 1)
return 1;//right
else if (forlast.row - last.row == -1)
return 3; //left
return -1;
/** list of positions */
public List positions;
public int getCost() { return positions.size() - 1; }
public int size() { return positions.size(); }
public void add(Object o) { positions.add(o); }
/** add (r,c) to the path */
public void add(int r, int c) {
positions.add(new Position(r,c));
/** get first position */
public Position head() { return (Position) positions.get(0); }
public Path(ArrayList positions) { this.positions = positions; }
public Path(Position initial) {
positions = new ArrayList(1);
positions.add(initial);
public Path(int cap) { positions = new ArrayList(cap); }
public void set(Position front, Path old) {
positions.add(front);
Iterator i = old.positions.iterator();
while (i.hasNext())
positions.add(i.next());
/** gives the move to take for the shortest path from startRow to startCol
* 0 up, 1 right, 2 down, 3 left
* -1 if no move possible
public final int findShortest
(int startRow, int startCol, int goalRow, int goalCol) {
clear();
Position initial = new Position(startRow, startCol);
//LinkedList list = new LinkedList();
Position goal = new Position(goalRow, goalCol);
BinaireHoop list = new BinaireHoop(200, new Path(goal), goal);
list.add(new Path(initial));
Position [] successors = new Position[4];
int trie = 0;
for ( ; ! list.isEmpty() && trie < 10000 ; trie++) {
Path first = (Path) list.remove();
Position firstPos = first.head();
int r = firstPos.row; int c = firstPos.col;
if (r == goalRow && c == goalCol) {  //goal found !             
return first.giveMove();
} else {
int successorsCount = 0;
if (isEmpty(r-1,c)) {
successors[successorsCount++]
= new Position(r-1, c);
if (isEmpty(r+1,c)) {
successors[successorsCount++]
= new Position(r+1, c);
if (isEmpty(r,c-1)) {
successors[successorsCount++]
= new Position(r, c-1);
if (isEmpty(r,c+1)) {
successors[successorsCount++]
= new Position(r, c+1);
while (successorsCount-- > 0) {
Position succ = successors[successorsCount];
int newPathCost = first.getCost() + 1;
//add newPath if shorter than other path to this position
if (distances[succ.row][succ.col] > newPathCost) { //shorter
distances[succ.row][succ.col] = newPathCost;
Path newPath = new Path(newPathCost + 1);
newPath.set(succ, first);
//add path to binary heap
list.add(newPath);
} // else longer: discard
return -1;
There's also a BinaireHoop class which the PathFinder class uses. I'll post that code if anyone thinks it's relevant but the error appears to be soley on my implementation. The Path and Position and just small subclass which for the sake of quickness I just placed into my Test class too instead of into a new class to themselves.
Any thoughts appreciated! I would really like to get this working =)
Thanks.

Thanks for your reply. Doh, totally missed that one =)
Anyway, I got the code working but it's still very buggy. I think this must just be a problem with the PathFinder class I downloaded.
I create a 2D array
      int[][] array = {       
                              {-1, -1, -1, -1, -1, -1, -1, -1},          
                              {-1, -1, -1, -1, -1, -1, -1, -1},
                              {-1, -1, -1, -1, -1, -1, -1, -1},
                              {-1, -1, -1, -1, -1, -1, -1, -1},
                              {-1, -1, -1, -1, -1, -1, -1, -1},
                              {-1, -1, -1, -1, -1, -1, -1, -1},
                              {-1, -1, -1, -1, -1, -1, -1, -1},
                              {-1, -1, -1, -1, -1, -1, -1, -1}
                      };and choose starting and goal coordinates
int p = star.findShortest(1, 1, 2, 2);The PathFinder will generate the coordinates to move to (I just stuck it all in a loop and updated the starting coordinates as appropriate to lead me to the goal). This is great!
However, there seem to be a lot of bugs when I introduce "occupied squares". Basically, -1 in the array means that that square is empty whereas anything else means its full and the path finder should, in theory, generate a path around these obstacles. This isn't working correctly though.
Sometimes a path wil be found around the obstacle, sometimes the path will go straight through it, and many times it just throws an array index out of bounds exception error!
Anyone got any ideas? Or does anyone have any examples of a working path finder? =)
Cheers

Similar Messages

  • Help on path finding

    Hello everyone!
    Help me please!
    Have you ever played games like Baldur's gate or Diablo or classic adventure games (like Monkey island)?
    What I'm saying is:
    I'm trying to implement a way to move my character, on a 2D space, to the point I clicked on.
    If there is no obstacle between the start and the finish points, I can make it work pretty easily (I just let the charachter walk the straight line connecting the points).
    The problem is when I introduce obstacles.
    I'm trying to implement the A* algorithm for the path finding process.
    Since the character and the obstacles lay on a 2D plane not divided into tiles or any sort of sub-division, it is quite hard to calculate a path.
    What I thought of doing is:
    when I click on a destination point, I create a 2D grid surrounding the character, at its actual position, and the destination point.
    The intersections between the horizontal and the vertical lines of this grid, will be the possible nodes of the path to the destination. (I hope it's clear).
    The A* will calculate the best path among these nodes, considering whether a node is reachable (i.e. not overlapping an obstacle) or not.
    I still haven't implemented it, so it's just an idea, and I don't even know if it works!
    Is it possible there is no other way of doing that?
    How do the games I mentioned above work?
    My problem is finding a way to determine the possible nodes (2D points on the 2D plane) for the A* algorithm to work on.
    Please help, I'm stuck.
    Any suggestion?
    Thank you!
    P.S: If you need me to make it more clear, I'll give it a try!

    So far as I've tested it they haven't gotten stuck.
    The best way I can think of to do it is with the Line2D.Double class.
    - I draw a line between me and the enemy
    - create two lines that are equal to that first line
    - rotate the first line, from the enemy, to the left
    - rotate the first line, from the enemy, to the right
    - if both still intersect the obstacle, I rotate the two again
    - if one of them no longer intersects the obstacle, that new line becomes my path
    Once the clear path is found, I can use the endpoint of that line as the destination, rather than saying that MY coordinates are the destination. It takes a lot of math figuring so it gets messy written out, but in words it's very clean :)
    For simplicity you could try:
    - if he hits an obstacle do the following:
    - draw a line between the entity and the center of the obstacle
    - if you're on the left side of that line, make him turn left 90 degrees
    - if you're on the right side, turn right 90 degrees
    Based on how you're creating your obstacles you could think further how you want to do it, like tell them to move in that direction a set distance, that sort of thing.
    Or you could give them set paths to follow, that's another solution, and just have them be able to aim at you freely to fire, provided that's how they attack.

  • I need help using customized HTML code for media players in Dreamweaver CC. My client is waiting patiently for this issue to be resolved.

    When I add multiple media players to my web page and upload them online, all four mp3 files begin to play at one time.  I need someone to take me through the steps to create playback controls in the HTML code so that the media players DO NOT play until the viewer clicks the "play button."

    By default, HTML5 videos do not autoplay on page load.
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>HTML5 with Video</title>
    <!--help for older IE browsers-->
    <!--[if lt IE 9]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    </head>
    <style>
    video {
        max-width:100%;
        display:block;
        margin:0 auto;
    </style>
    <body>
    <h2>Use 3 File Types to support all browsers &amp; mobile devices:  MP4, WEBM and OGV.</h2>
    <h3>If needed, use this Online Video Converter
    http://video.online-convert.com/</h3>
    <!--begin video-->
    <video controls poster="Your_poster_image.jpg">
    <!--these are 6 sec sample videos for testing purposes. Replace sample-videos with your own files-->
    <source src="http://techslides.com/demos/sample-videos/small.webm" type="video/webm">
    <source src="http://techslides.com/demos/sample-videos/small.ogv" type="video/ogg">
    <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
    If you're seeing this, you're using an
    outdated browser that doesn't support
    the video tag. </video>
    <!--end video-->
    </body>
    </html>

  • Help Using Navbar Find mode with dynamic viewobjects,

    What needs to be added to my coded to make the JUNavigatorBar QBE function in the "ADF Swing: Binding dynamically created ViewObjects to ADF Swing" example posted by Frank Nimphius on March 07, 2006. My table loads from the dynamic viewobject and the Navbar moves the cursor over each row in the table but when I go into Find mode ,the table row for entering the search criteria is not editable. I must be missing something basic here, but I am at a lost for the solution.

    Ok, I found this solution to make the dynamic view objects example 'searchable' from the NavigatorBar 'Find' button.
    I had to extend and replace the JUTableBinding class when creating a TableBinding which is then set as the model for my dynamic JTable using .setModel(); The rest of the example code works without modification.
    class MyJUTableBinding extends JUTableBinding{
    public MyJUTableBinding(javax.swing.JTable control,
    JUIteratorBinding iterBinding,
    java.lang.String[] attrNames){
    super(control, iterBinding,attrNames);
    public boolean isCellEditable(int row, int col) {
    return true;
    }

  • Need Helping using VBA custom code to query AS400 database

    Hi
    I am trying to connect the AS400 using the custom page programmability in etester. I am able to make the connection for SQL queries but when i try to do the same for a SPROC, I am not able to do it successfully. Any help is very much appreciated.
    Thanks
    Subu

    The easiest thing to open the ODBC interface and create a DSN entry for your AS400. (You will need the appropriate drivers loaded on the windows machine) Once you have done that, you can use the Microsoft Active-x data objects to connect, query, read and write data.

  • HT201372 used this to make a bootable copy for a new hard drive installation. copied the install find but gave error code 110 when making the disk bootable.. Any help in what this code is

    Used createinstallmedis to make a copy of the Mavericks app for use in a new hard drive install.. Copied find but gave error code 110 and failed to make the flash drive bootable.. Any help in what errror code means?

    Did you partition and format the flash drive first? See the following:
    Make Your Own Mavericks, Mountain/Lion Installer
    After downloading the installer you must first save the Install Mac OS X application. After the installer downloads DO NOT click on the Install button. Go to your Applications folder and make a copy of the installer. Move the copy into your Downloads folder. Now you can click on the Install button. You must do this because the installer deletes itself automatically when it finishes installing.
       2. Get a USB flash drive that is at least 8 GBs. Prep this flash drive as follows:
    Open Disk Utility in your Utilities folder.
    After DU loads select your flash drive (this is the entry with the mfgr.'s ID and size) from the leftside list. Under the Volume Scheme heading set the number of partitions from the drop down menu to one. Set the format type to Mac OS Extended (Journaled.) Click on the Options button, set the partition scheme to GUID then click on the OK button. Click on the Partition button and wait until the process has completed.
    Select the volume you just created (this is the sub-entry under the drive entry) from the left side list.
    Click on the Erase tab in the DU main window.
    Set the format type to Mac OS Extended (Journaled.) Click on the Options button, check the button for Zero Data and click on OK to return to the Erase window.
    Click on the Erase button. The format process can take up to an hour depending upon the flash drive size.
    Make your own Mavericks flash drive installer using the Mavericks tool:
    Mavericks has its own built-in installer maker you use via the Terminal:
    You will need a freshly partitioned and formatted USB flash drive with at least 8GBs. Leave the name of the flash drive at the system default, "Untitled." Do not change this name. Open the Terminal in the Utilities folder. Copy this command line after the prompt in the Terminal's window:
    sudo /Applications/Install\ OS\ X\ Mavericks.app/Contents/Resources/createinstallmedia --volume /Volumes/Untitled --applicationpath /Applications/Install\ OS\ X\ Mavericks.app --nointeraction
    Press RETURN. Enter your admin password when prompted. It will not be echoed to the screen so be careful to enter it correctly. Press RETURN, again.
    Wait for the process to complete which will take quite some time.

  • I could not find network utility option in mavericks. i was using os x lion.there is a network utility option in utility menu.help me to find out the option in mavericks.

    i could not find network utility option in mavericks. i was using os x lion.there is a network utility option in utility menu.help me to find out the option in mavericks.

    Choose Go to Folder from the Finder's Go menu, provide /System/Library/CoreServices/Applications/ as the path, and open it.
    (109612)

  • I am new with iMac and I am trying to copy some file from my external HDD but it does not let me also I can't delete anything from this HDD using the finder. Can somebody help me , please?

    I am new with iMac and I am trying to copy some file from my external HDD that a used with my PC but it does not let me also I can't delete anything from this HDD using the finder. Can somebody help me , please?

    No, unfortunately, when you format a drive, it will erase all the contents. So you will need to find a temporary "storage" place to put the stuff using a PC so you have access to it. Then reformat using Disk Utility (Applications > Utilities). If only using with mac, format Mac OS Extended (Journaled) and use GUID Partition scheme under Partitions/Options. After formatting, you can drag the files back.

  • Hello i forgot my i cloud password..anyone can help me to find my password.i already make a new apple id..but my icloud use another account..so how to reset my iCloud account plz hel me

    hello i forgot my i cloud password..anyone can help me to find my password.i already make a new apple id..but my icloud use another account..so how to reset my iCloud account plz hel me

    Making a new Apple ID is not a good idea, since you have to reset the password for that Apple ID anyway. All of your purchases are tied to the Apple ID that the iCloud account was created under. So, you have to retrieve the password for that Apple ID in order to sign into iCloud anyway.
    Go to Manage your Apple ID, and click on the Reset Password option (Apple - My Apple ID). Sign on with the Apple ID that the iCloud account was created under, and answer the security questions. If you do not remember the answers to the Security Questions, contact Apple Support to have them reset:
    ACCOUNT SECURITY CONTACT NUMBERS
    Cheers,
    GB

  • How find out which user is using which company code?

    Hi Gurus,
    I am having more than 500 users in Production System.I need to find out which user is using which company code?I can get the roles and users separately from two different SAP tables.
    Is it possible to get it from a single table or Tcode?
    Best Regards,
    Rahman

    Hi,
    Thanks for the update.Yes I tried with SUIM.But I was unable to find any clue.
    Regards,
    Rahman

  • Could u plz help me to find simple example for how to save data file in a spread sheet or any other way in the real time controller for Sbrio 9642 using memory or usb flash memory

    Could u plz help me to find simple example for how to save data file in a spread sheet or any other way in the real time controller for Sbrio 9642 using memory or usb flash memory

    Here are a few Links to a helpful Knowledge Base article and a White Paper that should help you out: http://digital.ni.com/public.nsf/allkb/BBCAD1AB08F1B6BB8625741F0082C2AF and http://www.ni.com/white-paper/10435/en/ . The methods for File IO in Real Time are the same for all of the Real Time Targets. The White Paper has best practices for the File IO and goes over how to do it. 
    Alex D
    Applications Engineer
    National Instruments

  • I'm working in Photoshop CS6 on a Mac and am having trouble when I select a Path it automatically feathers the selection border. I can't seem to find any place to adjust a feather setting. Does anyone have a suggestion? I'm using paths to silhouette an im

    How do I change a default from feathered edge to sharp edge when I select a path?
    I'm working in Photoshop CS6 on a Mac and am having trouble when I select a Path it automatically feathers the selection border. I can't seem to find any place to adjust a feather setting. Does anyone have a suggestion? I'm using paths to silhouette an image on a photograph to use in another document and I need a hard edge on it, not a feathered one.

    In the Paths panel, click the flyout menu (in the top right of the panel) and choose Make Selection (this option will only be available if you have a path selected). Reduce the Feather Radius to 0 (zero) and click OK. This setting will be the default even when clicking the Load Path as Selection button.

  • How to use standard Search Input Help (return 2 data code and desc) ?

    Hi,
    Please advise how to use standard Input Help provided by SAP and return 2 data (code and description) ? because the standard Input Help only return the code only ?
    Thank You and Best Regards
    Fernand

    >
    Saket  Abhyankar wrote:
    > Hi,
    >
    > I think you need to go for 'Search Help Exit' or OVS.
    >
    > Regards,
    >
    > Saket.
    That is not true that this is the only way.  The standard Data Dictory based search help can return more than one value as long as there are multiple exporting values defined in the search help, the search help is attached to a Data Dictionary Structure, and this same data dictionary structure is used as the source of the context node. You can read more about this in the online help:
    http://help.sap.com/saphelp_nw70ehp1/helpdata/en/47/9f724642314aabe10000000a42189b/frameset.htm
    The Note section under Integration:
    If an input help structure is stored in a field in the ABAP Dictionary, and if you want to use the field mapping of search help parameters stored in the ABAP Dictionary as the field name for the structure for your Web Dynpro input help, then map your context nodes to this structure. This ensures that all components of the structure are available dynamically at runtime as attributes of the node.
    If the context node is not mapped to the structure, the data element's input help can be used if there is one.

  • Hello find my mac displays offline when I'm using the actual mac I want to find at the time, can anyone help?, Hello find my mac displays offline when I'm using the actual mac I want to find at the time, can anyone help?

    Hello find my mac displays offline when I'm using the actual mac I want to find at the time, can anyone help?, Hello find my mac displays offline when I'm using the actual mac I want to find at the time, can anyone help?

    Welcome to the Apple community.
    Is your Mac connected to the network via ethernet. Mac's thatareI connected via ethernet cannot be located using "find my phone".

  • Everything on my desktop disappeared. i tried using the finder to locate specific files and they are missing. Help!

    i'm using a macbook pro retina, 2.4 GHz Intel Core i7, 8GB. operating OSX Yosemite 10.10.1
    everything on my desktop disappeared. i've managed to make my HD reappear on my desktop but my files etc are nowhere to be found. i tried using the finder to locate specific files and they are missing. Help! I foolishly filled up my desktop with piles of screen grabs and folders - no doubt that was the cause... what do i do, aside from punish myself for being so stupid?

    Could you have logged into another account?
    If you go to System Preferences>Users and Accounts what accounts are listed?
    To show users at login go to the Login Options of chanck the box that says show list of users.
    If they they are gone and you can't find them then restore them from a backup

Maybe you are looking for

  • System reboot on backuop attempt BEX error applicationshows as WerCon.exe 6.0.6002.18005 in stackhash_307c

     mine is a recent problem happens when I attempt to run Norton GHOST backup of system. Has been a month since ran properly. pc freezes up and then eventually reboots itself. Problem signature:   Problem Event Name:                        BEX   Applic

  • How to optimize Database Calls to improve performance of an application

    Hi, I have a performance issue with my applications. It takes a lot of time to load, as it is making several calls to the database. And, moreover, the resultset has more than 2000 records that are returned. I need to know what is the better way to im

  • Myofferpal is taking over my games. How can I get rid of it?

    myofferpal is taking over my games - particularly Hotties For Sale. It hijacks the site each time I try to play. Can you tell me how to block it or how to get rid of it please? I found this domain linked to it. http://return.domainnamesales.com/retur

  • Lenovo U410 Recovery

    Recovery 'Your PC needs to be repaired'' 'File: \BCD Error Code: 0xc0000098' I don't have a USB or recovery disk, is there an alternative way to fix this solution? I tried the one key recovery, clicked system recovery, but it would go into a blank sc

  • Default set of KF in Planning Book?

    Hi, I am currently working on 'slimming' down the SNP Planning Books being used by us. Basically trying to remove KFs/Macros not relevant to us. In doing so basically I am trying to make separate books for Production Planning and Capacity Planning. S