Rock Paper Scissors Game: Play Online & Learn the Code
<html>
<head>
<title>Rock Paper Scissors Game: Play Online & Learn the Code</title>
</head>
<body>
<h1>Rock Paper Scissors Game</h1>
<div class='game'>
<button id='rock'>Rock</button>
<button id='paper'>Paper</button>
<button id='scissors'>Scissors</button>
</div>
<h2 id='result'></h2>
<script>
const rock = document.querySelector('#rock');
const paper = document.querySelector('#paper');
const scissors = document.querySelector('#scissors');
const result = document.querySelector('#result');
<pre><code> const computerChoice = () => {
const choices = ['rock', 'paper', 'scissors'];
const randomChoice = Math.floor(Math.random() * 3);
return choices[randomChoice];
}
const determineWinner = (userChoice, computerChoice) => {
if (userChoice === computerChoice) {
return 'It's a tie!';
} else if (userChoice === 'rock') {
if (computerChoice === 'paper') {
return 'Computer wins!';
} else {
return 'You win!';
}
} else if (userChoice === 'paper') {
if (computerChoice === 'scissors') {
return 'Computer wins!';
} else {
return 'You win!';
}
} else if (userChoice === 'scissors') {
if (computerChoice === 'rock') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
}
const playGame = (userChoice) => {
let computerChoice = computerChoice();
result.innerHTML = `You chose ${userChoice}. Computer chose ${computerChoice}. ${determineWinner(userChoice, computerChoice)}`;
}
rock.addEventListener('click', () => {
playGame('rock');
});
paper.addEventListener('click', () => {
playGame('paper');
});
scissors.addEventListener('click', () => {
playGame('scissors');
});
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmnD 著作权归作者所有。请勿转载和采集!