我正在为RockPaperScisssors做游戏。我有一个生成计算机选择的函数,然后有一个对单击按钮做出反应的函数,然后有一个将这两个函数结合在一起进行游戏的函数。
我尝试过通过函数访问它,并且一直在进行研究,但是找不到找到将变量用于最后一个函数的方法。我是否必须将所有这些组合到一个函数中才能获取变量。
/*This function generates the computer's choice and then presents a rock image, removing it after 2 seconds.*/
function computerChoice() {
let compChoice = Math.random();
if (compChoice < 0.33) {
compChoice = "rock";
cpuChoice.classList.add(rockImage, rockImage2);
setTimeout(function () {
cpuChoice.classList.remove(rockImage, rockImage2);
}, 2000);
} else if (compChoice < 0.66 && compChoice > 0.33) {
compChoice = "paper";
cpuChoice.classList.add(paperImage, paperImage2);
setTimeout(function () {
cpuChoice.classList.remove(paperImage, paperImage2);
}, 2000);
} else {
compChoice = "scissors";
cpuChoice.classList.add(scissorImage, scissorImage2);
setTimeout(function () {
cpuChoice.classList.remove(scissorImage, scissorImage2);
}, 2000);
}
}
/*Here is the function thats having issues, I cant seem to get the gameResults innerHTML to change since it wont gather the compChoice.*/
function playGame(humanChoice, compChoice) {
if (humanChoice === compChoice) {
gameResults.innerHTML = "tie";
} else if (humanChoice === "rock" && compChoice === "scissor") {
gameResults.innerHTML = "You won!";
} else if (humanChoice === "rock" && compChoice === "paper") {
gameResults.innerHTML = "The computer won!";
} else if (humanChoice === "paper" && compChoice === "rock") {
gameResults.innerHTML = "You won!";
} else if (humanChoice === "paper" && compChoice === "scissor") {
gameResults.innerHTML = "The computer won!";
} else if (humanChoice === "scissor" && compChoice === "rock") {
gameResults.innerHTML = "The computer won!";
} else if (humanChoice === "scissor" && compChoice === "paper") {
gameResults.innerHTML = "You won!";
} else {
gameResults.innerHTML = "Not Possible";
}
}
/*This function generates the human's choice from a click and then presents an image of the choice, removing it after 2 seconds. Then calls for computerChoice(), and attempts to call the playGame functions.*/
allButtons.forEach(function (e) {
e.addEventListener("click", function () {
const choice = e.dataset.play;
if (choice === "rock") {
humanChoice = "rock";
computerChoice();
yourChoice.classList.add(rockImage, rockImage2);
setTimeout(function () {
yourChoice.classList.remove(rockImage, rockImage2);
}, 2000);
playGame(humanChoice, compChoice);
} else if (choice === "paper") {
humanChoice = "paper";
computerChoice();
yourChoice.classList.add(paperImage, paperImage2);
setTimeout(function () {
yourChoice.classList.remove(paperImage, paperImage2);
}, 2000);
playGame(humanChoice, compChoice);
} else if (choice === "scissors") {
humanChoice = "scissors";
computerChoice();
yourChoice.classList.add(scissorImage, scissorImage2);
setTimeout(function () {
yourChoice.classList.remove(scissorImage, scissorImage2);
}, 2000);
playGame(humanChoice, compChoice);
}
});
});
我期望gameResults.innerHTML会发生变化,但这不会,因为它不会收集CompChoice的变量与HumanChoices进行比较。