我目前正在为我的石头剪刀布游戏制作简单的 UI。我在 getComputerChoice 函数中使用随机数,然后该函数用于显示图像并决定游戏的结果。我尝试将 getComputerChoice 的结果设置为变量,但后来遇到了这样的问题:每次运行新游戏时,计算机的选择都会保持不变。
const model = {
wins: 0,
losses: 0,
draws: 0,
getCompChoice: function() {
var num = Math.floor(Math.random() * 3);
var choices = ["rock", "paper", "scissors"];
var choice = choices[num];
return choice;
},
gameLogic: function(player, computer) {
if (player === false) {
return alert("Please enter a valid guess");
} else if (player === computer) {
this.draws++;
return "draw";
} else if (
(player === "rock" && computer === "paper") ||
(player === "paper" && computer === "scissors") ||
(player === "scissors" && computer === "rock")
) {
this.losses++;
return "lose";
} else {
this.wins++;
return "win";
}
}
};
const view = {
updateScore: function() {
document.getElementById("wins").textContent = "Wins:" + " " + model.wins;
document.getElementById("losses").textContent =
"Losses:" + " " + model.losses;
document.getElementById("draws").textContent = "Draws:" + " " + model.draws;
return;
},
displayRollComputer: function() {
var computer = document.getElementById("computer");
computer.classList.remove("rock", "paper", "scissors");
computer.classList.add(controller.compChoice);
console.log(controller.compChoice);
},
displayRollUser: function() {
var user = document.getElementById("user");
user.classList.remove("rock", "paper", "scissors");
user.classList.add(processPlayer());
}
};
const controller = {
compChoice: model.getCompChoice(),
play: function() {
model.gameLogic(processPlayer(), this.compChoice);
view.updateScore();
view.displayRollComputer();
view.displayRollUser();
}
};
// Helper Functions
function processPlayer() {
const player = document.getElementById("guess").value;
if (player === "rock" || player === "paper" || player === "scissors") {
return player;
} else {
return false;
}
}
最佳答案
这是因为 controller.compChoice
并不是在每次调用 gameLogic()
时计算,而是在初始化期间只计算一次。将其更改为:
const controller = {
compChoice: model.getCompChoice(),
play: function() {
this.compChoice = model.getCompChoice(); <
model.gameLogic(processPlayer(), this.compChoice);
view.updateScore();
view.displayRollComputer();
view.displayRollUser();
}
};
一切都应该按预期进行。
关于javascript - 同步随机变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59175000/