JavaScript变量在定义后更改为结果行
我正致力于创建一个电脑机器人,它可以玩筷子。我发明了一个JavaScript变量在定义后更改为结果行,javascript,Javascript,我正致力于创建一个电脑机器人,它可以玩筷子。我发明了一个while循环,直到其中一台计算机获胜。我将计算机的游戏状态存储在一个类似[[1,1],[1,1]]的变量中。列表中的第一项是玩家1,他的左手和右手值为1。第二个玩家也是这样。但是,在我定义gameState之后的行,我定义console.log()gameState变量并获得游戏的最终结果,在我将其定义为[[1,1],[1,1]]之后的行。问题是,在while循环期间,我无法获得有关计算机正在进行的移动的信息。救命啊 这是我的密码: fu
while
循环,直到其中一台计算机获胜。我将计算机的游戏状态
存储在一个类似[[1,1],[1,1]]
的变量中。列表中的第一项是玩家1,他的左手和右手值为1。第二个玩家也是这样。但是,在我定义gameState
之后的行,我定义console.log()
gameState变量并获得游戏的最终结果,在我将其定义为[[1,1],[1,1]]
之后的行。问题是,在while循环期间,我无法获得有关计算机正在进行的移动的信息。救命啊
这是我的密码:
function makeMove(s, player, m) { //source, player, move
//if it is player 2, flip it around
if (player == 2) {
var s = [s[1], s[0]];
}
var target;
var source;
//move 0 is when the left hand targets the opponent's right hand
//move 1 is when the right hand targets the opponent's left hand
//move 2 is when the left hand targets the opponent's left hand
//move 3 is when the right hand targets the opponent's right hand
//the state [[1,1],[1,1]] stores the values of each hand and each opponent
if (m == 0 || m == 3) {
target = [1, 0];
} else {
target = [1, 1];
}
if (m == 0 || m == 2) {
source = [0, 0];
} else {
source = [0, 1];
}
s[target[0]][target[1]] += s[source[0]][source[1]];
s[target[0]][target[1]] %= 5;
if (player == 2) {
s = [s[1], s[0]];
}
return s;
}
function playmatch() {
//the original state,
var gameState = [[1, 1], [1, 1]];
//right after I create the value, for some reason it changes to the end result when I log it the next line.
console.log(gameState);
var winner = -1;
while (winner == -1) {
var choice = [0,1,2,3];
var move = choice[Math.floor(Math.random() * choice.length)];
gameState = makeMove(gameState, 1, move);
var move = choice[Math.floor(Math.random() * choice.length)];
gameState = makeMove(gameState, 2, move);
if (gameState[0][0] == 0 && gameState[0][1] == 0) {
winner = 2;
}
if (gameState[1][0] == 0 && gameState[1][1] == 0) {
winner = 1;
}
console.log(gameState);
}
return winner;
}
playmatch();
还有一个指向代码笔的链接:的行为没有标准化。正如MDN所建议的,您应该这样做
这样做
console.log(JSON.parse(JSON.stringify(obj)));
而不是
console.log(obj);
确保传递给console.log的是当时对象的快照,而不是对象的引用。我假设调用console.log时,
没有正确执行,并且给出了对数组的引用。因此,您的数组会发生更改,稍后当执行console.log
时,它会记录更改的数组。的行为没有标准化。正如MDN所建议的,您应该这样做
这样做
console.log(JSON.parse(JSON.stringify(obj)));
而不是
console.log(obj);
确保传递给console.log的是当时对象的快照,而不是对象的引用。我假设调用
console.log时,
没有正确执行,并且给出了对数组的引用。因此,您的数组会发生更改,稍后当执行console.log
时,它会记录更改的数组。非常感谢!非常感谢你!