我正在尝试构建要在命令行中玩的剪刀石头布游戏。在代码末尾,我console.log 3件事:人工选择,计算机选择(随机生成),然后是游戏的结果,例如“你赢了!摇滚击败了剪刀!”
问题在于,有时结果行会根据人和计算机的选择返回正确的结果,但是有时即使两个选择相同,也会产生不同的结果陈述。例如如果选择是人类=摇滚而计算机=摇滚,则可能返回“这是平局!”一次尝试,然后“失败了!纸胜过摇滚”,即使它仍然是摇滚还是摇滚。
我认为问题出在最后的3 console.log语句中。首先,人工选择始终保持“ Rock”不变,这很好。其次,我记录随机生成的计算机选择。第三,当我记录以人为选择和随机计算机选择作为参数的结果回合时,它将再次运行随机函数并为计算机拉出 different 随机选择。这意味着在前两个日志中作为人工和计算机选择记录的内容将与第三个日志(结果)不一致,因为它们提取不同的随机字符串,有时相同但有时不相同(因为他们是随机的)。
所以我想我的问题是:每次在代码中调用随机选择时,如何使它成为相同的字符串?
这是我的完整代码:
<script>
//human selection
const humanPlay = "Rock";
//randomly select for computer
function computerPlay() {
computerOptions = ["Rock", "Paper", "Scissors"];
return computerOptions[Math.floor(Math.random() * computerOptions.length)];
}
//play a round of human selection vs random computer selection and return a win/loss/tie statement
function playRound(humanPlay, computerPlay) {
//tie conditions
if (humanPlay == computerPlay){
return "It's a tie!"
//human win conditions
} else if (
(humanPlay == "Rock" && computerPlay == "Scissors") ||
(humanPlay == "Scissors" && computerPlay == "Paper") ||
(humanPlay == "Paper" && computerPlay == "Rock")
) {
return "You Win!" + ` ${humanPlay}` + " beats" + ` ${computerPlay}` + "!";
//computer win conditions
} else {
return "You Lose!" + ` ${computerPlay}` + " beats" + ` ${humanPlay}` + "!"
}
}
console.log(humanPlay);
console.log(computerPlay());
console.log(playRound(humanPlay, computerPlay()));
</script>