This is a collection of code examples from the blog series https://shendriks.dev/series/a-pathfinding-in-2d-games/
In here you'll find the following projects:
Blog Post | Projects | Branch |
---|---|---|
Part 1: A* Pathfinding in 2D Games: The Basics for a simple Top-down Scenario |
|
main |
Part 2: A* Pathfinding in 2D Games: A simple Top-down Scenario implemented with MonoGame/KNI |
|
main |
Part 3: A* Pathfinding in 2D Games: Side-View |
|
main |
Part 4: A* Pathfinding in 2D Games: Addendum about Cyclic Dependencies |
|
grid-navigator |
If you compare the applications, you'll notice that all projects have
similar classes like Cell
, Grid
or AStarPathfinder
with quite a bit of duplicated code.
Duplicated code is generally considered bad practice (see the DRY principle). However, it seems acceptable in this case because
- These are separate projects, each with its own set of requirements (e.g. a console application is meant to be called once, while a MonoGame application is meant to be interactive and game-like, e.g. you can step through the algorithm).
- Trying to avoid duplicated code by extracting superclasses into a separate project makes the relatively simple examples unnecessarily complicated.
- The code is unlikely to change.
In general, it's good practice to unsubscribe from events when you no longer need them. In this example, however, we'll skip the step of unsubscribing for simplicity's sake, because it's just one level, if you will, and the "game" is not progressing in the sense that a new level or area needs to be loaded while the current one is being unloaded, or new game objects are being created or existing ones are being destroyed. The only time we would need to unsubscribe is when the whole game ends, in which case everything will end up in data nirvana anyway.
You'll find a few rudimentary tests in the test projects. The coverage is probably not super high.