I am making a rogue-like game and I am using a random walk within a grid to form a ‘cave’ system. However, the random walk I have came up with gets stuck– in particular when the walker is near the edge of the grid and is surrounded with ‘holes.’
This isn’t the exact code I am using in my project, I cannot access my code from work. However, I re-wrote a sample of the same algorithm I am using at home.
Essentially, I took a 20×20 grid of integers and filled it with 1’s. As I walk I punch a 0 on each step I take.
void walk(int grid[][20]){
int x = rand() % 10 + 9;
int y = rand() % 10 + 9;
int walk_count;
for(walk_count = rand() % 1000 + 500; walk_count >= 0; walk_count--){
switch(rand() % 4){
case 0: if(grid[x][y - 1] == 1 && y - 1 >= 1){ y--; grid[x][y] = 0;} break;
case 1: if(grid[x][y + 1] == 1 && y + 1 < 20){ y++; grid[x][y] = 0;} break;
case 2: if(grid[x - 1][y] == 1 && x - 1 >= 1){ x--; grid[x][y] = 0;} break;
case 3: if(grid[x + 1][y] == 1 && x + 1 < 20){ x++; grid[x][y] = 0;} break;
default: break;
}
}
}
First, explain the asymmetry in your code. In case 1, you have
&& y + 1 < 20. In case 3, you have&& x + 1 >= 1, which I would expect to be&& x + 1 < 20.I’m going to chalk that up as a transcription error / typo and not the source of your problem. As I understand it, your problem is that you have a random walker who paints the floor and is painting itself into a corner. This behavior is expected, isn’t it?
The problem is that you are simply doing a random walk and expecting a behavior that is more intelligent than random. If you want to avoid painting yourself into a corner, put that into your algorithm. Assuming these random walkers want to be able to reach the player, just check that each direction, if filled, would still have a path to the player. Then randomly choose from the directions where that holds true.