assigning varying inputs to varying positions in a 4 by 4 array

31 views Asked by At

I am writing a JavaScript program that is supposed to generate a number (2 90% of the time, 4 for the other 10%). This works fine, however the number is then supposed to randomly replace one of the spots in the array that had previously had a value of zero. As far as I can tell, my code that should work but it does not and I get this error message:

                             Cannot read property '0' of undefined

I've included my code below but it may look weird because I am using Khan Academy's JavaScript teaching tool which might not be the same as normal JavaScript (I am not sure about this since I am new to the language).

var M=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]];
var NewTile=function(M){
    var open=0;                         // checks all tiles to see whitch ones are 0's
    var available=[];                   // while recorfing the number of zeros and
    for (var p=0; p<=3; p+=1){          // thier positions
        for (var q=0; q<=3; q+=1){
            var i=M[p][q];
            if (i===0){
                open=open+1;
                available.push([p,q]);            
            }
        }
    }
    var TwoOrFour=random(1,10);
    var NewValue;
    if (TwoOrFour===10){                // generates the new value 
        NewValue=4;
    }else{
        NewValue=2;
    }
    var NewPos;
    if (open===0){                      // decides whether the game is lost
        var over=true;
        return over;
    }else{                              // replaces the correct spot in the array
    var GetPos=random(0,open);
    var NewPos=available[GetPos];
    M[NewPos[0]][NewPos[1]]=NewValue;   // THIS IS WHERE THE ERROR SEEMS TO CAUSE AN ISSUE
    }
    return M;
};
var M=NewTile(M);
println(M[0]);
println(M[1]);
println(M[2]);
println(M[3]);

Can anyone tell me what I am doing wrong and why I am getting this error?

0

There are 0 answers