简体   繁体   中英

Applying pathfinding algorithm (Tower Defense) in C++

I've implemented flood fill algorithm that takes array[15*15] with path and generates a queue of steps he took while filling the path. tl;dr it looks like this

std::queue <int> f_path;

void Enemy::find_path(int *map, int *grid, int node) {

    if (grid[node] == 1) // colored-grid
        return;
    if (map[node] == 0) // grid with defined map (0 - no path, 1 path)
        return;

    f_path.push(node);
    grid[node] = 1;

    if ((node + 1) % 15 != 0) this->find_path(map, grid, node + 1); // go right
    if (node % 15 != 0) this->find_path(map, grid, node - 1); // go left
    if (node - 15 > 0) this->find_path(map, grid, node - 15); // go up
    if (node + 15 < 15*15) this->find_path(map, grid, node + 15); // go down
}

But now I have a queue of steps it took to fill the grid, but I don't know how to apply this information for my objects to follow and get from start to end. I mean, it's simple with one path, but if it splits like this (9 is exit):
0 0 1 0 0
0 1 1 1 0
0 1 0 1 0
0 1 1 1 0
0 0 9 0 0
I will have both left and right path in queue so if I do a simple go(f_path.front()) it will do god's know what. How do I filter it, so it only goes to exit and then stops? I can't wrap my head arround it.

I don't know the exact internals of your algorithm but you can easily get the shortest path to your destination by associating to every node the minimum distance from the starting node found for the current path request.

In this way whenever you find another path which passes from the same cell if distance is lower than the stored one then this path is better than the previous otherwise you can ignore it and skip to the next one.

In this way you can end up having more than one path which reach the goal but they all have same length (thus you can just choose one of them). Once reached the goal node you can backtrack: for every node at distance x starting from goal search a neighbor at distance x-1 .

Just to give you a graphical idea of what I mean:

在此输入图像描述

Mind that this is not the fastest solution and it will be suitable just for small tile maps, for larger one you'd need better algorithms than a breadth first search .

Deith, I will say you're on the right track!

Right now your code will simply iterate through everything and get nowhere. You forgot a couple things.
First, Enemy::find_path has to return a boolean: whether or not it reached the destination. So, at the top you have

if (grid[node] == 1) // colored-grid
    return;
if (map[node] == 0) // grid with defined map (0 - no path, 1 path)
    return;

I noticed the first one is to keep it from backtracking over itself.
The second one is pretty clear: It hits a wall. Therefore, have return false after it to show it reached a dead-end. But you need a third so that, if it reaches its destination, it returns true.

Then, when you call the four-way iterations, test if they return true . If they do then return true again since the goal was reached, thus searching, finding, and zipping back to the source!

Do note that zipping back to the source part, because that's the part you can use. Right now your queue will fill up with random junk going everywhere. It doesn't empty after it goes the wrong way. However, that zip-back part is perfect - instead of a queue, use a stack, and once you reach the destination, push each node when zipping back onto the stack, thus providing a full path from beginning to end!

Hope I could help ;-)

EDIT: Ok, so there is one more important thing I must mention: working, but inefficient paths.
Your algorithm will find a path, but not always the shortest path - in fact sometimes it'll even find a really long path. Fortunately to fix this is somewhat simple. You need to have the coordinate of the destination, first. Then, at each iteration of the find_path function, reorder your direction iterators. First you choose right, then left, then up, then down. Instead, see which direction will head in the direction of the goal. Then check that direction. If it fails try the next closest. If that fails, then try the next closest, and the next closest (well, now the farthest).

Yes, I know this will not be the shortest distance, since it generally tends toward wall-hugging, but it's definitely better than going in completely random directions.

Do a depth-first search (dfs) on the final grid that you get.

http://en.wikipedia.org/wiki/Depth-first_search

You will get individual paths. If you want to choose the shortest there are few optimizations you can do.

  • Keep a max-limit, if the dfs looks further than that, skip that path.
  • If you find a path with a length smaller than the max-limit. Set max-limit to that.

Hope this would help.

EDIT: I wrote this code, and it should work for you. It will give the shortest path, in a vector< pair > as x,y coordinates.

#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;

ifstream fin("map.txt");

int width, height;
int map[10][10];
// Start (x,y), End (x,y)
int sy, sx, ey, ex;

bool visited[10][10];

vector<pair<int, int> > final_path;
int max_size = 9999;

void getInput() {
  fin >> width >>  height;

  for (int i = 0; i < height; i++) {
    for (int j = 0; j < width; j++) {
        int x;
        fin >> x;
        map[i][j] = x; 

        if(x == 8){
          sy = i;
          sx = j;
        }

        if(x == 9){
          ey = i;
          ex = j;
        }
    }
  }
}

void dfs(int x, int y, vector<pair<int, int> > path) {
  if(path.size() > max_size){
    cout << "Returning : path size too big" << endl;
    return;
  }

  if(x < 0 || x >= width || y < 0 || y >= height){
    cout << "Returning : bounds" << endl;
    return;
  }

  // If the tile is blocked, can't go there
  if(map[y][x] == 0){
    cout << "Returning : blocked" << endl;
    return;
  }

  if(visited[y][x]){
    cout << "Returning : visited" << endl;
    return;
  }

  // We don't want to revisit a tile
  visited[y][x] = true;

  cout << "Visiting " << x << " " << y << endl;

  path.push_back(make_pair(x, y));
  if(map[y][x] == 9) {
    final_path = path;
    visited[y][x] = false;
    return;
  }

  dfs(x, y - 1, path);
  dfs(x + 1, y, path);
  dfs(x, y + 1, path);
  dfs(x - 1, y, path);

  visited[y][x] = false;

  return;
}

int main() {

  getInput();
  cout << "Got Input" << endl;
  cout << width << " " << height << endl;

  memset(visited, 0, sizeof(visited));
  vector<pair<int, int> > starting_path;

  cout << sx << " " << sy << endl;

  dfs(sx, sy, starting_path);

  cout << "Path size is " << final_path.size() << endl;

  for(int i = 0; i < final_path.size(); i++){
    cout << final_path[i].first << " " << final_path[i].second << endl;
  }

  return 0;
}

map.txt contains the map that you gave in the question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM