Reputation: 11
I'm trying to display the levels I'll have using this code...
levelArray[0] = ["player", "empty", "empty", "empty", "wall", "wall", "empty",
"empty", "wall", "wall", "empty", "empty", "empty","empty",
"empty", "empty", "empty", "wall", "empty", "wall", "wall",
"wall", "wall", "empty", "wall", "empty", "wall", "empty",
"box", "wall", "empty", "wall", "empty", "empty", "empty",
"empty", "empty", "empty", "wall", "wall", "wall", "empty",
"wall", "wall", "empty", "empty", "ghost", "wall","ghost"];
for(var i = 0; i < edge; i++)
{
for(var j = 0; j < edge; j++)
{
switch(levelArray[i])
{
case "empty": // empty location
ctx.drawImage(emptyTile, currentX, currentY);
break;
case "wall": // wall block
ctx.drawImage(wallTile, currentX, currentY);
break;
case "box": // box block
ctx.drawImage(boxTile, currentX, currentY);
break;
case "ghost": // enemy sprite
ctx.drawImage(ghostTile, currentX, currentY);
break;
case "player": // player sprite
ctx.drawImage(playerTile, currentX, currentY);
break;
}
currentX += elementEdge;
}
currentY += elementEdge;
}
however I receive an error on the switch line "Uncaught TypeError: Cannot read property '0' of undefined" and I don't really understand it.
Edit: edge is defined previously like this
edge = Math.sqrt(levelArray.length)
Upvotes: -1
Views: 132
Reputation: 71939
You're not using the inner loop. I believe you want this instead:
switch(levelArray[i][j])
In your source code, that snippet is inside a setupCanvas
function, with takes levelArray
as an argument. Since you're not passing anything when you call setupCanvas
, it's considered undefined
. Hence the errors you're getting.
Upvotes: 0
Reputation: 537
Try to access your array of levelArray like this:
switch(levelArray[0][i])
, because this levelArray[i] will return array in case i=0 for sure and other cases of i if you have placed more arrays!
Upvotes: 0