Clearing svg multiple children with a loop not working

57 views Asked by At

I am currently trying to create a reset code so that when the player collides with the enemy, it clears all of the collectibles (I called them pellets) from the svg and then remakes them with a loop I have. For some reason it is clearing every pellet but one. It also does not recreate the pellets like it is supposed to for some reason. The svg variables are score, player, ghost(the enemy) and pellet.

This is the reset code:

function destroyPlayer()
{
    alert("Game Over");
    score = 0;
    scoreElement.textContent = 'score: ' + score;
    pelletCount=0;
    constantCount = 1;
    //need code to take out all pellets from svg
    for(i = 0; i < 100; i++)
    {
        if(svg.children[i].id != "ghost" &&
           svg.children[i].id != "score" &&
           svg.children[i].id != "player")
        {
            svg.removeChild(svg.children[i]);
        }
    }
    positionPellet();
    positionGhost();
}

And this is the code that remakes the pellets: (the position pellet method)

function positionPellet() 
{  
    while(pelletCount < constantCount*3)
    {
        var pellet = document.createElementNS( xmlns, 'circle' );
        pellet.setAttribute( 'cx', Math.random() * 900 );
        pellet.setAttribute( 'cy', Math.random() * 400 );
        pellet.setAttribute( 'r' , 10 );
        pellet.className.baseVal = "pelClass";
        pelletCount++;
        svg.appendChild(pellet);
    }
}
1

There are 1 answers

0
Paul LeBeau On

Have you checked your browser developer console (press F12)? It should be displaying errors it finds in your Javascript.

If that's not helping much, you can log variables to the console to see why your code isn't working.

For instance, I can see immediately why your positionPellet() function isn't working. As a hint try adding some logging to check the value of pelletCount and constantCount.

function positionPellet() 
{
    console.log("pelletCount = "+pelletCount);
    console.log("constantCount= "+constantCount);
    while(pelletCount < constantCount*3)
    {
    ...

When you run the code again, you should see those debugging lines with values showing as undefined. Why would that be?

Your other problem is a little more subtle. I'll give you a hint and say that when you remove element 0 from an array, the array is updated immediately. The array item that used to be at children[1] is now at children[0]. But in your next time through the loop, you will be looking at children[1], which won't be the next child any more, it will actually be the one that was after that (originally children[2]).