关于JavaScript骰子游戏的Stack Overflow上有很多帖子,但我找不到能回答我问题的帖子。此代码改编自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's current score is: 0
有人可以指出我正确的方向吗?谢谢。
答案 0 :(得分:3)
您获取玩家得分的值并将其保存在" playerScore"变量。但是,之后您不会更新该值,因此当您稍后点击console.log()
语句时,它仍然具有其原始值。更改console.log
来电,以便在播放器上记录调用.getScore()
的结果。
console.log(player.name + "'s current score is: " + player.getScore());
答案 1 :(得分: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);
//Add this line in
playerScore = player.getScore();
if (roll1 === roll2) {
console.log(player.name + "'s current score is: " +
playerScore);
} else {
console.log(player.name + "'s current score is: " +
playerScore);
}
// return score;
}
快乐的编码!如果您有任何问题,请发表评论。