我想在玩石头剪刀布游戏(steen, papier, schaar === rock, paper, scissor)时添加无数可供选择的选项。我查看了 Stackoverflow 并找到了一些解决方案,但我不知道如何在我自己的代码中实现它。
这是解决方案的链接,没有在我自己的代码中实现它:
let userScore = 0;
let computerScore = 0;
let userScore_span = document.getElementById("user-score");
let computerScore_span = document.getElementById("computer-score");
let scoreMessage = document.getElementById("score-message");
const schaar_div = document.getElementById("schaar");
const steen_div = document.getElementById("steen");
const papier_div = document.getElementById("papier");
// Computer choice
function getRandomChoise() {
const choises = ["schaar", "steen", "papier"];
const randomNumber = Math.floor(Math.random() * choises.length);
return choises[randomNumber];
}
function win() {
userScore++;
userScore_span.innerHTML = userScore;
scoreMessage.innerHTML = "<span style='color: green;'>You Won!</span>";
}
function lose() {
computerScore++;
computerScore_span.innerHTML = computerScore;
scoreMessage.innerHTML = "<span style='color: red;'>You Lost!</span>"
}
function draw() {
scoreMessage.innerHTML = "It's a Draw!"
}
function Game(userChoise) {
const computerChoise = getRandomChoise();
if (userChoise + computerChoise === "steenschaar") {
win();
} else if (userChoise + computerChoise === "papiersteen") {
win();
} else if (userChoise + computerChoise === "schaarpapier") {
win();
} else if (userChoise + computerChoise === "steenpapier") {
lose();
} else if (userChoise + computerChoise === "papierschaar") {
lose();
} else if (userChoise + computerChoise === "schaarsteen") {
lose();
} else if (userChoise + computerChoise === "schaarschaar") {
draw();
} else if (userChoise + computerChoise === "steensteen") {
draw();
} else if (userChoise + computerChoise === "papierpapier") {
draw();
}
}
function main() {
schaar_div.addEventListener("click", function () {
Game("schaar");
})
我希望能够为游戏添加无限数量的选项(lizzard、spock 等),而无需一遍又一遍地编写 else if 声明。
函数式编程
肥皂起泡泡
RISEBY
相关分类