Having fun with colors: Improving the Pathfinding System
The previous pathfinding system has been pretty straightforward, as it simply divided the terrain in walkable and unwalkable tiles. Rivers and buildings for example have been marked as unwalkable, to prevent your soldiers from crossing the deep water or from walking through walls. This works pretty well for 90 percent of the terrain, but we'll run into trouble as soon as we're introducing more complex areas like keeps with different courts. Your pikeman for example may stand inside the courtyard of your keep, surrounded by walkable tiles. As the gates to the outside are closed he should not be able to protect the villagers which are attacked by an enemy raid, although this happens in an area of walkable tiles, too. What, if the main gates of this court are closed, but are still opened at an adjacent courtyard? No question, get there and beat the hell out of them.
In order to make this possible, we need a system that understands whether areas are connected or separated by buildings or walls. More precisely: whether point B can be reached from point A after the construction of a wall.
For this purpose a specially written pathfinder is activated, which travels along the wall tiles until it has found the target point. As soon as a certain maximum of steps is exceeded by not finding the target point, it terminates the try, compares the two separated areas of point A and B and marks the smaller one as closed courtyard.
In the next step, we want to include gates that allow us to open or close the courtyards. As soon as a gate is built on a previously defined closed area, the Pathfinder will be activated again, assigning different ID's to the areas and storing them with the ID of the gate in a separate script. When opening or closing the gate, we only have to compare the ID's and activate or deactivate the corresponding tiles.
In the last step we check if different courtyards are connected by gates. As soon as a gate is closed or opened, all adjacent courtyards are updated. A connection between two courtyards is only finally declared closed once there is no longer any way over all other gate connections.
Finally, this enables us to build architecturally complex castles with different atriums, courtyards and gatehouses and to conquer or defend them in tactically challenging sieges.