gpt4 book ai didi

javascript - JS - 石头、剪刀、布、按钮而不是提示

转载 作者:行者123 更新时间:2023-11-28 18:25:36 24 4
gpt4 key购买 nike

我有 JS 中的基本“石头、剪刀、布”游戏的代码。它可以与提示一起使用,但我希望能够通过按钮做出选择。我想使用“getElementById”和“addEventListener(“click”)”。有人能指出我正确的方向吗?

HTML:

  <button id ="rock"> Rock </button>

纸 剪刀

JavaScript:

var userChoice = prompt("Do you choose rock, paper or scissors?");



var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";

} else if(computerChoice <= 0.67) {
computerChoice = "paper";

} else {
computerChoice = "scissors";
} console.log("Computer: " + computerChoice);


var compare = function (choice1, choice2) {
if (choice1 === choice2) {
return "The result is a tie!";
}

else if (choice1 === "rock") {
if (choice2 === "scissors") {
return "rock wins";
}
else {
return "paper wins";


} if (choice1 === "paper") {
if (choice2 === "rock") {
return "paper wins";
}
else {
return "scissors wins";


} if (choice1 === "scissors") {
if (choice2 === "rock") {
return "rock wins";

} else if (choice2 === "paper") {
return "scissors wins";
}
}
}
}
}
compare (userChoice, computerChoice);

最佳答案

在多个 block 中使用 onclick 事件处理程序 ( documentation ),如下所示:

document.getElementById('rock').onclick = function(e){
userChoice = 'rock'
}

关于javascript - JS - 石头、剪刀、布、按钮而不是提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39230557/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com