Rock, Paper and Scissors in JS
Let’s build a fun and interactive **Rock, Paper, and Scissors** game using pure JavaScript. We'll start with a simple console-based version and then upgrade it to a web-based version with an interactive UI.
Skills You’ll Learn:
Random choice generationUser input handlingConditional statementsDOM manipulation
Step 1: Build a Console-Based Game
Before diving into the web version, let’s warm up with a simple console-based **Rock, Paper, and Scissors** game. Open your browser's developer console (F12 > Console) and try it out!
// Function to get the computer's choice
function getComputerChoice() {
const choices = ['stone', 'paper', 'scissor'];
const randomIndex = Math.floor(Math.random() * 3);
return choices[randomIndex];
}
// Function to determine the winner
function determineWinner(userChoice, computerChoice) {
if (userChoice === computerChoice) {
return "It's a tie!";
}
if (
(userChoice === 'stone' && computerChoice === 'scissor') ||
(userChoice === 'paper' && computerChoice === 'stone') ||
(userChoice === 'scissor' && computerChoice === 'paper')
) {
return "You win!";
} else {
return "Computer wins!";
}}
// Function to play the game
function playGame(userChoice) {
const computerChoice = getComputerChoice();
console.log(`You chose: ${userChoice}`);
console.log(`Computer chose: ${computerChoice}`);
console.log(determineWinner(userChoice, computerChoice));
}
// Example usage:
const userChoice = 'stone'; // You can change this to 'paper' or 'scissor'
playGame(userChoice);
How It Works:
The script generates a random number between 1 and 100.
The user guesses until they find the correct number.
It provides hints like "Too high" or "Too low".
When guessed correctly, it displays the number of attempts.
How It Works:
The script randomly selects a choice for the computer (rock, paper, or scissors). The user provides their choice. The script compares the choices and declares the winner or a tie.Step 2: Build a Web-Based Rock, Paper, and Scissors Game
Now, let’s create an interactive web version using HTML, CSS, and JavaScript.
Create three files:
(i.) `index.html` - The Game Structure
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>The Royal Coding - Rock Paper Scissors</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1 class="my-4">The Royal Coding - Rock Paper Scissors</h1>
<div class="d-flex justify-content-center gap-3">
<button class="btn btn-choice" data-choice="rock"> Rock</button>
<button class="btn btn-choice" data-choice="paper"> Paper</button>
<button class="btn btn-choice" data-choice="scissors"> Scissors</button>
</div>
<p id="result" class="alert alert-info mt-4"></p>
</div>
<script src="script.js"></script>
</body>
</html>
(ii.) `style.css` - The Game's Styling
body {
text-align: center;
font-family: Arial, sans-serif;
background: #fff;
padding: 20px;
}
h1 {
color: #ffa500;
}
.btn-choice {
background: #ffa500;
color: white;
border: none;
padding: 10px 20px;
margin: 5px; cursor: pointer;
font-size: 18px;
}
.btn-choice:hover {
background: grey;
}
#result {
font-size: 20px;
font-weight: bold;
color: black;
margin-top: 20px;
}
(iii.) `script.js` - The Game Logic
const choices = ["rock", "paper", "scissors"];
function getComputerChoice() {
return choices[Math.floor(Math.random() * choices.length)];
}
function determineWinner(userChoice, computerChoice) {
if (userChoice === computerChoice) return "It's a tie!";
if ((userChoice === "rock" && computerChoice === "scissors") ||
(userChoice === "paper" && computerChoice === "rock") ||
(userChoice === "scissors" && computerChoice === "paper")) {
return "You win!";
}
return "Computer wins!";
}
document.querySelectorAll(".btn-choice").forEach(button => {
button.addEventListener("click", () => {
let userChoice = button.getAttribute("data-choice");
let computerChoice = getComputerChoice();
document.getElementById("result").innerText = `You chose: ${userChoice}\nComputer chose: ${computerChoice}\n${determineWinner(userChoice, computerChoice)}`;
});
});
Congratulations! Your Game is Ready!
Open `index.html` in your browser and start playing!
What We Learned?
Random Choice Generation: `Math.floor(Math.random() * choices.length)`
User Input Handling: `button.getAttribute("data-choice")`
DOM Manipulation: Updating the result dynamically