gpt4 book ai didi

javascript - 如何在 Javascript 中将对象包装在网格上?

转载 作者:行者123 更新时间:2023-12-03 05:18:17 24 4
gpt4 key购买 nike

我目前正在研究火星漫游者卡塔。我创建了一个 10x10 网格,漫游者可以向前和向后移动并改变方向 ['N'、'E'、'S'、'W']。因为网格实际上代表一个球形行星,所以漫游车应该环绕 10x10 网格而不是完全离开。我正在尝试对包装进行编码。包含更多上下文的对象。我目前正在使用 if/else 语句来确定漫游器应该换行的情况,但我知道我把它弄得太复杂了。 switch 语句会更有效吗?或者我可以以某种方式使用循环吗?我是 JavaScript 新手。非常感谢。

var myRover = {
position: [[0],[0]],
direction: 'N',
roverDirections = ['N', 'E', 'S', 'W'],
marsGrid: [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
obstacles: [];
};

if (command === 'f') {

if ((myRover.position[[0],[0]]) && (myRover.direction === 'S')) {
myRover.position[[10],[0]];
}

else if ((myRover.position[[0],[0]]) && (myRover.direction === 'W')) {
myRover.position[[0],[10]];
}

if ((myRover.position[[0],[10]]) && (myRover.direction === 'E')) {
myRover.position[[0],[0]];
}

else if ((myRover.position[[0],[10]]) && (myRover.direction === 'S')) {
myRover.position[[10],[10]];
}

if ((myRover.position[[10],[0]]) && (myRover.direction === 'N')) {
myRover.position[[0],[0]];
}

else if ((myRover.position[[10],[0]]) && (myRover.direction === 'W')) {
myRover.position[[10],[10]];
}

if ((myRover.position[[10],[10]]) && (myRover.direction === 'N')) {
myRover.position[[0],[10]];
}

else if ((myRover.position[[0],[0]]) && (myRover.direction === 'E')) {
myRover.position[[10],[0]];
}


}

最佳答案

您可以使用一个对象来计算给定方向的漫游器的新位置。

directions = {
N: [0, 9], // 9 because length of x - 1 and the positive remainder operator
W: [9, 0], // 9 because length of y - 1
O: [1, 0],
S: [0, 1]
};

然后你可以确定新的位置

direction = 'S';
newPos = [
(oldPos[0] + directions[direction][0]) % 10,
(oldPos[1] + directions[direction][1]) % 10
];

关于javascript - 如何在 Javascript 中将对象包装在网格上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41514476/

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