在HTML5蛇游戏中为食物生成随机位置时发生未捕获的TypeError
Uncaught TypeError while generating a random position for the food in a HTML5 snake game
我目前正在用Javascript在HTML5 Canvas中制作一款多人Snake游戏。
下面的代码是处理蛇食物随机放置的函数。这段代码的问题是,它给了我while中的x和y(map[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);
}
下面是定义映射的另一个代码片段。
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);
}
this.map
和map
不是一回事。
如果您在对象内部,则this.map
是该对象的公共变量,map
是局部变量。
试试这样的东西:
this.map = [];
// Map positions
for (var i = 0; i < 10; i++){
this.map[i] = [];
}
并且在CCD_ 5函数中也使用CCD_。
这里有两种可能的方法:
//using public variable
function SnakeGame() {
this.map = [];
// Map positions
for (var i = 0; i < 10; i++){
this.map[i] = [];
}
function rand_food() {
// refer to this.map here
this.map[0];
}
};
// using local variable
function SnakeGame() {
var map = [];
// Map positions
for (var i = 0; i < 10; i++){
map[i] = [];
}
function rand_food() {
// refer to map here
map[0];
}
};
如果没有定义映射,通常会得到ReferenceError,所以定义了映射,但可能是:
- 未分配给任何内容
- 使用后定义/分配
- 通过在不执行的条件下定义的直线吊装
示例
if (0) {
var foo = 1;
}
console.log(foo) //= undefined
console.log(foo[20]) // TypeError…
console.log(bar) // ReferenceError…
相关文章:
- jquery试图按名称获取按钮位置
- 我可以获得相对于被点击元素的确切点击位置吗
- 谷歌地图固定位置覆盖
- 在单击任何位置时隐藏元素,而不检查每次DOM单击
- TypeError:无法读取属性'推'未定义的JavaScript
- 未捕获的TypeError无法读取未定义的属性socialsharing
- 扩展SVGTextElement时出现Typescript Uncaught TypeError
- 循环比赛位置算法
- TypeError:在不兼容的接收器nodejs上调用了方法Uint8Array.length
- es6 相当于下划线查找位置
- jQuery循环在特定位置暂停
- 引导程序:在导航栏中,显示悬停在单个位置的基于Li Link的不同内容
- 自定义函数中的光标位置
- 安卓平台上的QWebView HTML5地理位置
- DIV并排,位置不正确
- 使用jQuery更改元素的顶部位置
- 在谷歌地图上绘制位置数据库
- TypeError:_this.store.getState在使用来自Redux的连接时不是函数
- 跟踪jqplot垂直折线图的鼠标位置
- 在HTML5蛇游戏中为食物生成随机位置时发生未捕获的TypeError