iDevGames Forums
Odd javascript bug - Printable Version

+- iDevGames Forums (http://www.idevgames.com/forums)
+-- Forum: Development Zone (/forum-3.html)
+--- Forum: Programming Languages & Scripting (/forum-8.html)
+--- Thread: Odd javascript bug (/thread-8349.html)



Odd javascript bug - anthony - Nov 27, 2010 01:06 PM

Hi,

I've been tricking around with HTML5 and I'm making a snake clone. When ever a piece of food is eaten the code calculates a new empty location in the world. This works fine for a good portion (~90%) of the play testing I've done so far.

However, at seemingly random points food items stop being placed in the world and when I check the javascript console (Chrome's developer tools) I get an error message that reads

Quote:"Uncaught TypeError: Cannot read property '5' of undefined"

It's not always '5' either so there's no pattern there. The game continues to play (everything is rendered and I can move the snake around) but no more food appears on screen.

I'm using a 2D array (an array of arrays) to represent the game world in grid form. My code for placing a new food item is:
Code:
// find a row and column in the world that is empty
function FindFreeLocation()
{
    var _r;
    var _c;

    do
    {
        _r = GenerateRandomNumber(0, worldWidth);
        _c = GenerateRandomNumber(0, worldHeight);

    } while (world[_r][_c] != 0); // error is generated here!

    return {row:_r, col:_c};
}

function GenerateRandomNumber(min, max)
{
    // var range = max – min + 1;
    var range = max - min + 1;
    // .floor() a bit more 'random' than round...
    return Math.floor(Math.random() * range + min);
}

Does anyone have any ideas?

Thanks,

Anthony


RE: Odd javascript bug - OneSadCookie - Nov 27, 2010 01:22 PM

GenerateRandomNumber(0, N) sometimes returns N. You should either pass worldWidth - 1 & worldHeight - 1, or you should set range to max - min (no + 1) in GenerateRandomNumber.


RE: Odd javascript bug - anthony - Nov 28, 2010 08:29 AM

(Nov 27, 2010 01:22 PM)OneSadCookie Wrote:  GenerateRandomNumber(0, N) sometimes returns N. You should either pass worldWidth - 1 & worldHeight - 1, or you should set range to max - min (no + 1) in GenerateRandomNumber.

D'oh Blush I can't believe I didn't pick that up. I ran a few tests and that's solved the problem.

Thank you very much!