Simple Rock Paper Scissors Game in HTML
Simple Rock Paper Scissors Game
To make a simple Rock Paper Scissors game in HTML, we will need to create a basic structure with HTML, style it with CSS, and add interactivity with JavaScript.
HTML Structure
We will create a simple HTML structure with three buttons representing rock, paper, and scissors. Each button will have an ID to reference it in JavaScript.
<!DOCTYPE html>
<html>
<head>
<title>Rock Paper Scissors Game</title>
<style>
/* Add some basic styling to the buttons */
button {
padding: 10px;
font-size: 20px;
margin: 10px;
}
</style>
</head>
<body>
<h1>Rock Paper Scissors Game</h1>
<p>Choose your weapon:</p>
<button id='rock'>Rock</button>
<button id='paper'>Paper</button>
<button id='scissors'>Scissors</button>
</body>
</html>
JavaScript
We will use JavaScript to add interactivity to our game. We will first create a function that generates a random choice for the computer. We will then create an event listener for each button that calls a function to determine the winner based on the choices made by the player and the computer.
// Function to generate random choice for computer
function computerPlay() {
const weapons = ['rock', 'paper', 'scissors'];
return weapons[Math.floor(Math.random() * weapons.length)];
}
// Function to determine the winner
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return 'It's a tie!';
} else if ((playerSelection === 'rock' && computerSelection === 'scissors') ||
(playerSelection === 'paper' && computerSelection === 'rock') ||
(playerSelection === 'scissors' && computerSelection === 'paper')) {
return 'You win!';
} else {
return 'Computer wins!';
}
}
// Event listeners for each button
const rockButton = document.querySelector('#rock');
rockButton.addEventListener('click', () => {
const result = playRound('rock', computerPlay());
alert(result);
});
const paperButton = document.querySelector('#paper');
paperButton.addEventListener('click', () => {
const result = playRound('paper', computerPlay());
alert(result);
});
const scissorsButton = document.querySelector('#scissors');
scissorsButton.addEventListener('click', () => {
const result = playRound('scissors', computerPlay());
alert(result);
});
CSS
Finally, we will add some CSS to style our game. We will add a background color, change the font, and add some padding to the body.
body {
background-color: #f2f2f2;
font-family: Arial, sans-serif;
padding: 20px;
}
And that's it! You now have a simple Rock Paper Scissors game in HTML. Have fun playing!
原文地址: https://www.cveoy.top/t/topic/lmnB 著作权归作者所有。请勿转载和采集!