0

我需要为我学校的一个项目制作一个基于图块的游戏,但遇到了一个我似乎无法解决的“严重”错误。

这是我的脚本:

function init(){
var speelVeldBreedte;
var speelVeldHoogte;
var speelVeld = [
    [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1],
    [1,0,1,0,1,0,1,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,1,1,1]
];

var speelTerrein = document.getElementById("speelterrein");
}

speelVeldBreedte=speelVeld[0].length; 
speelVeldHoogte=speelVeld.length;

var schaalTerrein = 20;
speelTerrein.width = speelVeldBreedte * schaalTerrein; 
speelTerrein.height = speelVeldHoogte * schaalTerrein;


var ctx = speelTerrein.getContext("2d");
ctx.fillStyle = "white";
ctx.fillRect(0,0,speelTerrein.width,speelTerrein.height);
    for (var y=0; y<speelVeldHoogte;y++){
        for (var x=0;x<speelVeldBreedte;x++){
            var steen = speelVeld[y][x];
            if (steen> 01){
                ctx.fillStyle = "rgb(100,0,0)";
                ctx.fillRect(x*schaalTerrein,y*schaalTerrein,schaalTerrein,schaalTerrein);
            }
        }
    }

这是我得到的错误:

uncaughtReferenceError: speelVeld is not defined.

它指的是第 32 行,即:

speelVeldBreedte=speelVeld[0].length;

我希望有人能告诉我如何解决这个错误以及究竟是什么问题。

在此先感谢,雷米

4

2 回答 2

1

您已经speelVeld在函数体中进行了init()定义,并且您在第 32 行的调用在该函数之外——因此,JS 无法“看到”该变量,因为它超出了范围。

于 2012-12-03T14:10:45.597 回答
0

spelVeld(以及与此相关的所有变量)的范围在 init() 函数内。

您可以在此处阅读有关范围的信息:http: //coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/

于 2012-12-03T14:10:11.697 回答