gpt4 book ai didi

javascript - 无法读取未定义的属性 'x' (JavaScript)

转载 作者:行者123 更新时间:2023-11-28 19:10:27 26 4
gpt4 key购买 nike

我目前正在尝试从 tutorial 构建一个贪吃蛇游戏。在 JavaScript 和 Canvas 中。目前我在这一行收到错误: grid.set(FOOD, randPos.x, randPos.y); 这是位于底部的 setFood 函数的一部分。我不明白 .x 来自哪里,因为我没有看到在该范围内定义的 X 或 Y。如果有人能给我指明正确的方向,这样我就可以完成我的第一款游戏,我将非常感激!谢谢。

<script>
//CONSTANTS
var COLS=26;
var ROWS=26;

//ID's
var EMPTY=0;
var SNAKE=1;
var FOOD=2;

//Direction
var LEFT=0;
var UP=1;
var RIGHT=2;
var DOWN=3;

var grid = {
width: null,
height: null,
_grid: null,

init: function(d,c,r){
this.width = c;
this.height = r;

this._grid = [];
for(var x=0; x<c; x++){
this._grid.push([]);
for(var y=0; y < r; y++){
this._grid[x].push(d);
}
}
},

set: function(val,x,y){
this._grid[x][y] = val;
},

get: function(x,y){
this._grid[x][y];
}
}

var snake = {
direction: null,
last: null,
_queue: null,

init: function(d,x,y){
this.direction = d;
this._queue = [];
this.insert(x,y);
},

insert: function(x,y){
this._queue.unshift({x:x, y:y});
this.last = this._queue[0];
},

remove: function(){
return this._queue.pop();
}
}

function setFood(){
var empty = [];
for(var x=0; x<grid.width; x++){
for(var y=0; y<grid.height; y++){
if(grid.get(x,y)===EMPTY){
empty.push({x:x, y:y});
}
}
}
var randPos = empty[Math.floor(Math.random()*empty.length)];
console.log("working");
grid.set(FOOD, randPos.x, randPos.y);
console.log("working???")
}

//Game objects
var canvas, ctx, keystate, frames;

function main(){
canvas = document.createElement('canvas');
canvas.width = COLS*20;
canvas.height = ROWS*20;
ctx = canvas.getContext('2D');
document.body.appendChild(canvas);

frames = 0;
keystate = {};

init();
loop();
}

function init(){
grid.init(EMPTY, COLS, ROWS);

var sp = {x:Math.floor(COLS/2), y:ROWS-1};
snake.init(UP, sp.x, sp.y);
grid.set(SNAKE, sp.x, sp.y);

setFood();
}

function loop(){
update();
draw();

window.requestAnimationFrame(loop, canvas);
}

function update(){
frames++;
}

function draw(){
var tw = canvas.width/grid.width;
var th = canvas.height/grid.height;

for(var x=0; x<grid.width; x++){
for(var y=0; y<grid.height; y++){
switch(grid.get(x,y)){
case EMPTY:
ctx.fillStyle = "#fff";
break;
case SNAKE:
ctx.fillStyle = "#0ff";
break;
case FOOD:
ctx.fillStyle = "#f00";
break;
}
ctx.fillRect(x*tw, y*th, tw, th);
}
}
}

main();
</script>

最佳答案

看一下 setFood 函数。在出现错误的行上方几行,有一个循环用同时包含 xy 字段的对象填充 empty 集合。这些对象之一被分配给 randPos 变量。

该错误可能是由于对 randPos 变量的值赋值无效引起的。它未定义,因此不包含必需的 x 字段。

更新

看来您刚刚错过了 grid.get(x,y) 函数中的 return 关键字,因此它应该如下所示:

get: function(x,y){
return this._grid[x][y];
}

请验证添加它是否可以解决您的问题。

关于javascript - 无法读取未定义的属性 'x' (JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30810054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com