javascript - JavaScript 变量在定义后更改为输出行
问题描述
我正在努力创建一个可以在筷子上玩耍的计算机机器人。我发明了一个while
循环运行,直到其中一台计算机获胜。我将计算机存储gameState
在一个看起来像[[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();
以及 codepen pen 的链接:https ://codepen.io/gmoyer/pen/EeepbE
解决方案
的行为console.log
不规范。正如 MDN 所建议的,您应该序列化您的 object。
做这个
console.log(JSON.parse(JSON.stringify(obj)));
代替
console.log(obj);
以确保传递给console.log
的是对象在那个时刻的快照,而不是对对象的引用。我假设console.log
当您调用它并获得对您的数组的引用时,它没有正确执行。因此,您的数组会更改,稍后在console.log
执行时,它会记录更改的数组。
推荐阅读
- mysql - 在 MySQL 中存储 MD5
- firebase - 日期时间从颤振转移到 Firebase Firestore 时会丢失秒数
- python - 如何计算精巧图像中的欧几里得距离
- cuda - 如何将字符串从__global__函数返回到C CUDA中的主函数
- html - 反垃圾邮件问题已在联系 html 表单中实施,但仍然收到垃圾邮件,如何停止?
- python - CS50 check50 在 roster.py PSET7 上失败,只显示没有名称
- grub - 更新 grub grub2-mkconfig 抛出错误环境块太小
- python - 根据不同 numpy 数组中的索引将标量添加到 numpy 矩阵
- amazon-web-services - 是否可以在 AWS CDK 中定义多个 lambda 目标?
- python - 如何在同一文件中的python sqlitedict中使用多个表?