a_star 2.0.0 copy "a_star: ^2.0.0" to clipboard
a_star: ^2.0.0 copied to clipboard

A comprehensive A* algorithm. Suitable for anything from physical grids to abstract search spaces.

example/example.dart

// ignore_for_file: avoid_print

import "dart:math";

import "package:a_star/a_star.dart";

class CoordinatesState extends AStarState<CoordinatesState> {
  final int x;
  final int y;
  final int goalX;
  final int goalY;
  final String? direction;
  CoordinatesState(this.x, this.y, this.goalX, this.goalY, {this.direction});

  Iterable<CoordinatesState> getNeighbors() => [
    CoordinatesState(x, y + 1, goalX, goalY, direction: "up"),
    CoordinatesState(x, y - 1, goalX, goalY, direction: "down"),
    CoordinatesState(x + 1, y, goalX, goalY, direction: "right"),
    CoordinatesState(x - 1, y, goalX, goalY, direction: "left"),
  ];

  bool get isValid => true;

  @override
  Iterable<CoordinatesState> expand() => [
    for (final neighbor in getNeighbors())
      if (neighbor.isValid)
        neighbor,
  ];

  @override
  double heuristic() => sqrt(pow(goalX - x, 2) + pow(goalY - y, 2));

  @override
  bool isGoal() => x == goalX && y == goalY;

  @override
  String hash() => "($x, $y)";
}

void main() {
  final start = CoordinatesState(0, 0, 10, 10);
  final result = aStar(start);
  if (result == null) {
    print("Could not find a path");
    return;
  }
  final path = result.reconstructPath();
  for (final intermediate in path) {
    if (intermediate.direction == null) {
      print("Start at ${intermediate.hash()}");
    } else {
      print("Go ${intermediate.direction} to ${intermediate.hash()}");
    }
  }
}
2
likes
135
pub points
61%
popularity

Publisher

unverified uploader

A comprehensive A* algorithm. Suitable for anything from physical grids to abstract search spaces.

Repository (GitHub)
View/report issues

Documentation

API reference

License

unknown (license)

Dependencies

collection, meta

More

Packages that depend on a_star