2 回答
TA贡献1765条经验 获得超5个赞
您可以使用 eventListener 获取 playerChoice 并将选择与 game() 函数进行比较
function game(userChoice) {
const computerChoice = computerChoice();
switch (userChoice + computerChoice) {
case "rockscissors":
case "paperrock":
case "scissorspaper":
win(userChoice, computerChoice);
break;
case "rockpaper":
case "paperscissors":
case "scissorsrock":
lose(userChoice, computerChoice);
break;
case "rockrock":
case "paperpaper":
case "scissorscissors":
draw(userChoice, computerChoice);
break;
}
}
function main() {
rock.addEventListener("click",function() {
game("rock");
})
paper.addEventListener("click",function() {
game("paper");
})
scissors.addEventListener("click",function() {
game("scissors");
})
}
main();
TA贡献1836条经验 获得超13个赞
您在这里不需要事件侦听器。好像你把它复杂化了。
由于我不知道您的 HTML 是什么样子,因此我假设玩家可以选择三个按钮:
HTML:
<img src="images/rock.png" onClick="playerChoice('rock');">
<img src="images/paper.png" onClick="playerChoice('paper');">
<img src="images/scissors.png" onClick="playerChoice('scissors');">
记者:
let playerScore = 0;
let computerScore = 0;
function playerChoice(pChoice) {
const playerChoice = document.getElementById('player-choice');
const rock = document.getElementById('rock-btn');
const paper = document.getElementById('paper-btn');
const scissors = document.getElementById('scissors-btn');
if (pChoice== "rock") {
playerChoice.src = 'images/rock.png';
} else if (pChoice == "paper") {
playerChoice.src = 'images/paper.png';
} else if (pChoice == "scissors") {
playerChoice.src = 'images/scissors.png';
}
var cChoice = computerChoice() ;
// do your pChoice vs cChoice comparison:
// increment playerScore/computerScore
}
function computerChoice() {
const options = document.querySelectorAll('.options-btn button');
const randomPick = ['rock', 'paper', 'scissors'];
const randomNumber = Math.floor(Math.random() * 3);
return randomPick[randomNumber];
}
添加回答
举报