Tuesday, January 22, 2008

What's wrong with the following code:

var loop = levelNum * enemiesPerLevel;
if (level > 10) loop *= 1.5;
while (loop--) {
// spawn enemy
}


The code above was used in a game engine that I had to work with recently. It's used to spawn the number of enemies depending on the level. If the level has gone up to 10, the intention is to up the enemies count by 50%. However, there is a serious flaw to the code, where is it?

The problem is in the loop *= 1.5; The fractional multiplication will sometimes produce a floating number in the while condition. So it's possible for the condition to still pass when the loop count to skip past zero to negative value, which still passes the test!

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home