所以我正在制作一个石头、剪刀、布游戏。我想让 math.random() 给我一个随机结果,我将其与用户选择的结果进行比较。
它基本上有效。我什至认为它在一段时间内完全有效,但在某些时候我失去了随机性。
为了尝试它,我输入了一个固定的“用户”选择,并使用 setInterval(myfunction, 20) 运行代码数百次。他们总是取得一边倒的胜利,而且总是有相同的结果:
如果我使用playerPick = 1运行它,计算机总是获胜。
如果我使用playerPick = 2或3运行它,用户总是获胜。
谁能看到我哪里出错了?
//Global variable and constants.
const ROCK = 1;
const PAPER = 2;
const SCISSORS = 3;
//This is the game.
function whoWins(){
const playerPick = 2; //for debugging, it can be 1, 2, or 3.
const computer = computerPick();
if (playerPick == computer){
return draw();
} else if (playerPick == 1 && computer == 2){
return lose();
} else if (playerPick == 2 && computer == 3){
return lose();
} else if (playerPick == 3 && computer == 1){
return lose();
} else {
return win();
}
}
//These are the inputs for the game.
rockButton.addEventListener('click', () => {
playerPick = ROCK;
return whoWins()});
paperButton.addEventListener('click', () => {
playerPick = PAPER;
return whoWins()});
scissorsButton.addEventListener('click', () => {
playerPick = SCISSORS;
return whoWins()});
function computerPick() {
let computerChoice = '';
const getRandom = Math.random;
if (getRandom() >= 2/3) {
computerChoice = ROCK;
} else if (getRandom() >= 1/3){
computerChoice = PAPER;
} else {
computerChoice = SCISSORS;
}
return computerChoice;
}
我对这一切都很陌生,但这仍然不是随机的。
最佳答案
这应该是一个简单的修复,正如评论中提到的,您需要调用 Math.random 一次,否则概率会出现偏差。
我认为在原始代码中,PAPER 的概率为 0.66 * 0.66 = ~ 44%,SCISSORS 的概率为 0.66 * 0.33 = ~ 22%。新功能应该可以解决这个问题。
const ROCK = 1;
const PAPER = 2;
const SCISSORS = 3;
// Original computerPick function
function computerPickOriginal() {
let computerChoice = '';
const getRandom = Math.random;
if (getRandom() >= 2/3) {
computerChoice = ROCK;
} else if (getRandom() >= 1/3){
computerChoice = PAPER;
} else {
computerChoice = SCISSORS;
}
return computerChoice;
}
// Fixed computerPick function.
function computerPick() {
let computerChoice = '';
const choice = Math.random();
if (choice >= 2/3) {
computerChoice = ROCK;
} else if (choice >= 1/3){
computerChoice = PAPER;
} else {
computerChoice = SCISSORS;
}
return computerChoice;
}
function decodeChoice(choice) {
if (choice == ROCK) return "Rock";
if (choice == PAPER) return "Paper";
if (choice == SCISSORS) return "Scissors";
}
// Check the distribution of each version of the code.
console.log("Checking distributions (10000 picks)..");
let original_counts = {};
let counts = {};
for(let i = 0; i < 10000; i++) {
let k = computerPick();
counts[k] = (counts[k] || 0) + 1;
let k2 = computerPickOriginal();
original_counts[k2] = (original_counts[k2] || 0) + 1;
}
console.log('Computer Pick Distribution (original): ', Object.entries(original_counts).map(([key,value]) => `${decodeChoice(key)}: ${value}`));
console.log('Computer Pick Distribution (fixed): ', Object.entries(counts).map(([key,value]) => `${decodeChoice(key)}: ${value}`));
关于javascript - 我在哪里失去了随机性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57412238/