gpt4 book ai didi

JavaScript 骰子游戏返回 0

转载 作者:行者123 更新时间:2023-11-29 18:10:22 28 4
gpt4 key购买 nike

Stack Overflow 上有很多关于 JavaScript 骰子游戏的帖子,但我找不到能回答我问题的帖子。此代码改编自 CodeCademy:

function rollSingleDice() {
return Math.floor(Math.random()*6+1);
}

function rollDice(player) {
var score = 0;
var roll1; var roll2;
var playerScore = player.getScore();
do {
roll1 = rollSingleDice();
roll2 = rollSingleDice();
} while (roll1 === roll2);

score = roll1 + roll2;
player.addToScore(score);

if (roll1 === roll2) {
console.log(player.name + "'s current score is: " +
playerScore);
} else {
console.log(player.name + "'s current score is: " +
playerScore);
}
// return score;
}


function Player(name) {
this.name = name;
var score = 0; // this is a private attribute
this.addToScore = function(points) {
score = score + points;
};
this.getScore = function() {
return score;
};
}

var player1 = new Player("Bobby");
rollDice(player1);

我已经多次修改 do ... while 循环,我得到的唯一输出如下:

Bobby 的当前分数是:0

有人可以指出我正确的方向吗?谢谢。

最佳答案

您获取玩家得分的值并将其保存在“playerScore”变量中。但是,之后您不会更新该值,因此当您稍后点击 console.log() 语句时,它仍然具有其原始值。更改 console.log 调用,以便它记录在播放器上调用 .getScore() 的结果。

    console.log(player.name + "'s current score is: " + player.getScore());

关于JavaScript 骰子游戏返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27909707/

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