Frage

I am making a Pac-Man game and I am currently working on the ghosts AI. I am planning on using Dijkstra's algorithm for the pathfinding. My problem is that when my game is loaded the vertices for the graph are stored in a matrix. I am trying to assign each vertex all of its edges like this

    for(int x = 0; x<40; x++)
    {
        for(int y = 0; y<40; y++)
        {
            Vertex vertex = map[x][y];
            vertex.adjacencies = new Edge[]{new Edge(map[x-1][y], 1), new Edge(map[x+1][y], 1), new Edge(map[x][y-1], 1), new Edge(map[x][y+1], 1)};
        }
    }

the problem is that it sometimes throws an array out of bounds exception. How would I fix this without putting in tons of if statements to check if the current vertex is on the edge of the graph?

War es hilfreich?

Lösung

One easy way is to include a non-traversable border around the edges.

For example, if your actual map is 40x40, you can declare a 42x42 array. Rows 0 and n would be non-traversable, as would be columns 0 and n.

You'd still need to handle cylindrical travel of the pacman between left and right sides.

Andere Tipps

You should start your loop with a "border" of 1, like this:

for(int x = 1; x < 39; x++)

because, when you create your edges with map[x-1][y] with a x started to 0, it take -1 as array index, so it throw an Array Out of Bounds exception.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top