Play Rock Paper Scissors Online - Free Game
<!DOCTYPE html>
<html>
<head>
<title>Rock Paper Scissors</title>
<style>
#game {
width: 400px;
margin: 0 auto;
text-align: center;
}
</style>
</head>
<body>
<div id="game">
<h1>Rock Paper Scissors</h1>
<p>Choose one:</p>
<button id="rock">Rock</button>
<button id="paper">Paper</button>
<button id="scissors">Scissors</button>
<p id="result"></p>
</div>
<pre><code><script type="text/javascript">
// Get the buttons
const rockBtn = document.getElementById('rock');
const paperBtn = document.getElementById('paper');
const scissorsBtn = document.getElementById('scissors');
const result = document.getElementById('result');
// Array of choices
const choices = ['Rock', 'Paper', 'Scissors'];
// Get a random choice
const randomChoice = () => {
const randomNumber = Math.floor(Math.random() * 3);
return choices[randomNumber];
}
// Compare choices
const compareChoices = (userChoice, computerChoice) => {
// Tie
if (userChoice === computerChoice) {
return 'It is a tie!';
}
// Rock
if (userChoice === 'Rock') {
if (computerChoice === 'Paper') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
// Paper
if (userChoice === 'Paper') {
if (computerChoice === 'Scissors') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
// Scissors
if (userChoice === 'Scissors') {
if (computerChoice === 'Rock') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
}
// Event listener
rockBtn.addEventListener('click', () => {
const computerChoice = randomChoice();
const userChoice = 'Rock';
result.innerHTML = compareChoices(userChoice, computerChoice) +
'<br>You chose ' + userChoice + '.<br>Computer chose ' + computerChoice + '.';
});
paperBtn.addEventListener('click', () => {
const computerChoice = randomChoice();
const userChoice = 'Paper';
result.innerHTML = compareChoices(userChoice, computerChoice) +
'<br>You chose ' + userChoice + '.<br>Computer chose ' + computerChoice + '.';
});
scissorsBtn.addEventListener('click', () => {
const computerChoice = randomChoice();
const userChoice = 'Scissors';
result.innerHTML = compareChoices(userChoice, computerChoice) +
'<br>You chose ' + userChoice + '.<br>Computer chose ' + computerChoice + '.';
});
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lmnK 著作权归作者所有。请勿转载和采集!