CleverRaven/Cataclysm-DDA — pull request #9690 by BevapDin (2014-10-26 01:26:39+00:00)
Title: Fixes "Monsters can use stairs to teleport"

This is a genius bug and it toke me far to long to see it.

Fixes #9394

The typical situation is this: the house above the spider basement has *one* square with stairs, but there might be other stairs around (in my tests it was stairs leading into another basement some blocks away).
This means `stairdist` ends up with one entry near the player (the single stair tile leading into the spider basement) and some other entries far away.
The code (correctly) finds the nearest square (the index `si` point to it).
Than it extracts all entries that are as near as the entry `si` or at most one tile further (`stairdist[i] <= stairdist[si] + 1`). This is still correct, but in this situation it would only extract one entry (`found == 1`) as all the other stairs are much further away.

Now the critical code: `si = nearest[one_in(found)];`
This should select a random entry, but there is only one entry and `one_in` returns a `bool`, not an `int`. And `one_in` always return true when the chance is 1.
in this situation the chance is indeed 1, so `one_in` returns true, which becomes 1 when used as `int`, which selects the second entry in `nearest` array. That entry has not actually been written, but luckily the array has been initialized with all 0, therefor the second entry still contains the number 0, and `si` ends up being 0.

`si` is used as index into `stairx`/`stairy` to get the position of those stairs.
Now look at the top of the function to see how that vector is filled: the game loops through all squares in the reality bubble (west side first). If there are stairs to the left of the player character, they will be found and put into `stairx`/`stairy` first. And those stairs will be used here, not those that are nearest to the player.