Rock Paper Scissors Game in HTML: A Simple Guide
How to Make a Simple Rock Paper Scissors Game in HTML
Rock Paper Scissors is a classic game that's easy to create with HTML and JavaScript. This tutorial will guide you through building a basic version of the game.
Step 1: Creating the HTML Structure
Start by creating an HTML file and adding the basic structure. Inside the <body> tag, add three buttons for rock, paper, and scissors. Here's an example:
<!DOCTYPE html>
<html>
<head>
<title>Rock Paper Scissors Game</title>
</head>
<body>
<h1>Rock Paper Scissors Game</h1>
<button id='rock'>Rock</button>
<button id='paper'>Paper</button>
<button id='scissors'>Scissors</button>
</body>
</html>
Step 2: Adding JavaScript Interactivity
Now, let's add JavaScript code to make the buttons interactive. First, create a function to generate a random choice for the computer. Then, add event listeners to each button to compare the user's choice with the computer's choice and display the result.
Here's an example of the JavaScript code:
let userChoice;
document.getElementById('rock').addEventListener('click', function() {
userChoice = 'rock';
playGame();
});
document.getElementById('paper').addEventListener('click', function() {
userChoice = 'paper';
playGame();
});
document.getElementById('scissors').addEventListener('click', function() {
userChoice = 'scissors';
playGame();
});
function getComputerChoice() {
const choices = ['rock', 'paper', 'scissors'];
const randomNumber = Math.floor(Math.random() * 3);
return choices[randomNumber];
}
function playGame() {
const computerChoice = getComputerChoice();
if (userChoice === computerChoice) {
alert('It's a tie!');
} else if (userChoice === 'rock' && computerChoice === 'scissors' ||
userChoice === 'paper' && computerChoice === 'rock' ||
userChoice === 'scissors' && computerChoice === 'paper') {
alert(`You win! ${userChoice} beats ${computerChoice}.`);
} else {
alert(`You lose! ${computerChoice} beats ${userChoice}.`);
}
}
Step 3: Testing Your Game
Save both the HTML and JavaScript files. Open the HTML file in a web browser. Click each button to test the game and see the results.
Congratulations! You've successfully created a simple Rock Paper Scissors game using HTML and JavaScript.
原文地址: https://www.cveoy.top/t/topic/lmny 著作权归作者所有。请勿转载和采集!