gpt4 book ai didi

JavaScript 变量在定义后更改为结果行

转载 作者:行者123 更新时间:2023-11-30 09:19:58 24 4
gpt4 key购买 nike

我正在努力创建一个可以自己玩筷子的计算机机器人。我发明了一个 while 循环来运行直到其中一台计算机获胜。我将计算机的 gameState 存储在一个看起来像 [[1,1],[1,1]] 的变量中。列表中的第一项是玩家一,他的左手和右手值都为1。第二个玩家也是如此。然而,在我定义 gameState 之后的那一行,我 console.log() gameState 变量并得到游戏的最终结果,我将其定义为 [[1,1],[1,1]] 之后的行。这样做的问题是,在 while 循环期间,我无法获得有关计算机正在执行的 Action 的信息。帮助!

这是我的代码:

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();

以及 codepen 笔的链接:https://codepen.io/gmoyer/pen/EeepbE

最佳答案

console.log 的行为不规范。根据 MDN 的建议,您应该 serialize your object .

这样做

console.log(JSON.parse(JSON.stringify(obj)));

代替

console.log(obj);

确保传递给 console.log 的是对象当时的快照,而不是对象的引用。我假设 console.log 在您调用它时没有正确执行,并且给出了对您的数组的引用。因此,您的数组会更改,稍后当 console.log 执行时,它会记录更改的数组。

关于JavaScript 变量在定义后更改为结果行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52378771/

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