- Home /
Checking an expression against 2D array elements behaving erratically
I'm working on a simple rogue-like game where I have a 2D array of integers, where each number corresponds to a different object.
0 - Empty Space
1 - Wall
2 - The player
3 - An enemy
I've set up the system so that when the level starts, the whole array is iterated through and one of these numbers is assigned. I wanted an algorithm to detect if the current cell of the array was a viable location for an enemy. Basically the algorithm would start from the current position and first go up until it hits a wall, and then go left from the current position until it hits the wall. If it didn't find any other enemies in both these lines, then it's a viable location.
But for some reason this system doesn't always work. When I load up a new level there's always some enemies in the same row/column between walls, but based on debug.Log calls I have determined that it prevents enemies spawning in nonviable spots sometimes. I'm kinda baffled about what could be screwing with this, so any help would be much appreciated.
Here's the code:
function Start () {
for (var i: int = 0; i < size; i++){
for (var j: int = 0; j < size; j++){
if ((calculateWallChance(i,j) + Random.Range(0.0,1.0)) > wallChance){
cells[i,j] = 1;
} else if ((calculateChaserChance(i,j) + Random.Range(0.0,1.0)) > chaserChance){
cells[i,j] = 3;
} else {
cells[i,j] = 0;
}
}
}
cells[1,1] = 2;
}
function calculateChaserChance(i: int, j: int){
var curr: int;
//By row
for (curr = i; curr > 0; curr--){
if (cells[curr,j] > 1){
return -5;
} else if (cells[curr,j] == 1){
break;
}
}
//By column
for (curr = j; curr > 0; curr--){
if (cells[i,curr] > 1){
return -5;
} else if (cells[i,curr] == 1){
break;
}
}
//If not already returned, return a low chance
return 0.2;
}