ondras / rot.js

ROguelike Toolkit in JavaScript. Cool dungeon-related stuff, interactive manual, documentation, tests!
https://ondras.github.io/rot.js/hp/
BSD 3-Clause "New" or "Revised" License
2.33k stars 254 forks source link

Allow path 'weighting' within AStar #79

Open jaycrossler opened 8 years ago

jaycrossler commented 8 years ago

Added callback function to allow path 'weighting' within AStar so that longer routes through some cells are preferred over shorter routes through other difficult cells (for example, routing around a forest or lake).

Example usage:

    function tile_traversability_weight (x, y) {
        var cell = game.tile_details(x, y);

        var weight = 0;
        if (cell.name == 'plains') weight += 2;
        if (cell.name == 'mountains') weight += 6;
        if (cell.name == 'forest') weight += 3;
        if (cell.name == 'lake') weight += 4;
        if (cell.density == 'medium') weight += 2;
        if (cell.density == 'large') weight += 4;
        if (cell.has('path')) weight -= 1;
        if (cell.has('road')) weight -= 2;
        if (cell.has('rail')) weight -= 4;
        if (cell.has('river')) weight += 2;

        return Math.max(0, weight);
    }  
    astar.compute(from_x, from_y, pathCallback, tile_traversability_weight);
ondras commented 8 years ago

I would suggest storing the weightingCallback as a private property, not passing it to _add and calling this._weigtingCallback(x, y) instead.