gpt4 book ai didi

javascript - 我访问的 JavaScript 对象是否错误(或者为什么这不起作用)?

转载 作者:行者123 更新时间:2023-11-29 17:13:36 25 4
gpt4 key购买 nike

对于我用 JavaScript 创建的第一个(正确的)游戏,我正在制作贪吃蛇游戏。我将所有关于蛇的信息存储在这样的类中:

var snake={

//The width and height of each "segment" of the snake (in pixels)
size : 20,


/*Direction that the snake's moving in

Left=0
Right=1
Up=2
Down=3*/
direction : rand_int_between(0,3),


/*Positions of the snake's "segments" (1 is the snake's head, then 2 (when it's created) will be the next segment of the snake,
then 3 will be the next, and so on*/
positions : {
1 : {
"x" : rand_int_between(0, 35)*snake.size, //There are 36 possible "columns" that the snake can be in
"y" : rand_int_between(0, 23)*snake.size
}
},


//Will be set to False if the game hasn't started or of it's paused
moving : false
}

//Alert(snake.size);

现在这出于某种原因破坏了我的代码。当我将随机整数乘以“snake.size”时,我已将其精确定位,因为如果我将这些行更改为简单地将其乘以 20,则脚本可以正常工作。

我感觉这是其中一个问题,一旦您听到它,您将无法相信自己错过了它!

有人可以帮忙吗,因为这让我发疯了,哈哈。我认为我没有错误地访问“size”属性,因为如果我取消注释该代码的最后一行,然后从 positions 属性中删除“snake.size”位,它会像您一样提醒“20”期待。

这里是 rand_int_between():

function rand_int_between(min, max) { //Will include min and max
return Math.floor(Math.random() * (max - min + 1)) + min;
}

最佳答案

您不能在声明对象时访问对象的元素 (snake)。尝试移动位置声明:

var snake={

//The width and height of each "segment" of the snake (in pixels)
size : 20,


/*Direction that the snake's moving in

Left=0
Right=1
Up=2
Down=3*/
direction : rand_int_between(0,3),


//Will be set to False if the game hasn't started or of it's paused
moving : false
};


/*Positions of the snake's "segments" (1 is the snake's head, then 2 (when it's created) will be the next segment of the snake,
then 3 will be the next, and so on*/
snake.Positions = {
1 : {
"x" : rand_int_between(0, 35)*snake.size, //There are 36 possible "columns" that the snake can be in
"y" : rand_int_between(0, 23)*snake.size
}
};

关于javascript - 我访问的 JavaScript 对象是否错误(或者为什么这不起作用)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19915539/

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