I am making a 2D tower defense game. So far I have a 2d array which acts as a grid for my game. I'm able to place towers on it, run enemies and some dragging and tower firing stuff.
Now I am facing a problem in tower placement logic. I want that there's always a walkable path for enemies, meaning that the user should not be able to block the way completely by placing towers. Eg. if the user places towers vertically on a map, the algorithm must prevent the placement of a tower that will complete the vertical line. Or in any other way there must be at least one free (walkable) space so that the enemy can escape.
My current logic checks in all directions whenever tower has placed. If there is a tower upwards it calls the same function again on that upper tower until it hits a wall. It returns 1 for upward wall and 5 for downward wall and returns function(up/down tower) if there is a tower. here is the code:
int checkCollision(tower)
{
if( there is a tower up)
return checkCollision(up tower);
if(there is a tower down)
return checkCollision(down tower);
......all directions.....
if( there is a wall on UP )
return 1;
if( there is a wall DOWN )
return 5;
....all walls......
return 0;
}
Now what I want is, simultaneously check if there is a northern wall and southern wall or check any other directions with any other possibility (like up-down, up-diagonal, down diagonal... and so on) to not let the user place a tower as there should be one place left for enemy.
I am unhappy with my code at the moment. I mean my code tells me that a wall is found but how can I check that a wall is found in one direction and a wall also found in another direction? I dont want to go into possibilities like:
if(checkCollision(tower) == 1 && checkCollision(tower) == 5)
"You cannot place"
I want something like:
if( any combination of more than 2 wall found and there is entry/exit point in between) //so it is wall to wall
"You cant place"
I have also tried pre-calculating flags if there are walls on two sides (like up-down, up-diagonal etc.) then don't let the user place the tower but that still doesn't work.