【发布时间】:2012-03-08 10:29:53
【问题描述】:
我目前正在使用 Javascript 在 HTML5 Canvas 中制作多人 Snake 游戏。
下面的代码是处理蛇食物随机放置的函数。这段代码的问题在于它在 while(map[x][y]); 中给了我 x 和 y。回到他无法阅读的东西,即使它确实生成了一个随机数。
这是确切的错误:
"Uncaught TypeError: Cannot read property '20' of undefined"
“20”是随机生成的数字(将是二维数组中食物的网格位置),每次我重新启动程序或刷新网页时都会发生变化。有人可以解释我需要改变什么来定义 x 和 y 并放置我的食物吗?
function rand_food(){
var x, y;
do {
x = MR() * this.rect_w|0;
y = MR() * this.rect_h|0;
}
while (map[x][y]); <-- Here is the error
map[x][y] = 1;
this.ctx.strokeRect(x * 10+1, y * 10+1, 8, 8);
}
这是另一个定义地图的代码 sn-p。
this.map = [];
// Map positions
//*
for (i = 0; i < this.rect_w; i++){
map[i] = [];
}//*/
在尝试了 Sean 的建议后,我的代码现在看起来像这样:但它仍然给我同样的错误。还有什么建议吗?
function SnakeGame(){
this.map = [];
for (i = 0; i < this.rect_w; i++){
this.map[i] = [];
}
function rand_food(){
var x, y;
console.log("Map length: " + this.map.length);
do {
x = MR() * this.rect_w|0;
y = MR() * this.rect_h|0;
console.log("x: " + x);
console.log("y: " + y);
}
while (this.map[x][y]);
this.map[x][y] = 1;
this.ctx.strokeRect(x * 10+1, y * 10+1, 8, 8);
}
【问题讨论】:
标签: javascript html canvas scope while-loop