0% found this document useful (0 votes)
3 views2 pages

js game 2

This document contains a JavaScript function for a Rock, Paper, Scissors game. It prompts the user for their choice, generates a random choice for the computer, and determines the winner based on the rules of the game. The function logs the results of the game and concludes with a game over message.

Uploaded by

Chanchal Dey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

js game 2

This document contains a JavaScript function for a Rock, Paper, Scissors game. It prompts the user for their choice, generates a random choice for the computer, and determines the winner based on the rules of the game. The function logs the results of the game and concludes with a game over message.

Uploaded by

Chanchal Dey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

// --- Rock, Paper, Scissors Game ---

function playGame() {
// 1. Get user's choice
let userChoice;
while (true) {
// Use prompt for browser, or simulate/use readline-sync for Node.js
// For simplicity, this example assumes a browser or you'll mentally input.
// In a browser, uncomment the line below:
// userChoice = prompt("Choose Rock, Paper, or Scissors:").toLowerCase();

// For this example, let's simulate a user's choice for a quick run:
// You can change this line to 'rock', 'paper', or 'scissors' to test:
userChoice = "rock"; // <-- CHANGE THIS TO TEST DIFFERENT CHOICES

if (userChoice === "rock" || userChoice === "paper" || userChoice === "scissors") {


break; // Valid input, exit loop
} else {
console.log("Invalid choice! Please type 'Rock', 'Paper', or 'Scissors'.");
// If using prompt, the loop would ask again. For this static example, it just logs.
return; // Exit function if invalid simulated input
}
}
console.log(`You chose: ${userChoice}`);

// 2. Generate computer's choice


const choices = ["rock", "paper", "scissors"];
const computerChoice = choices[Math.floor(Math.random() * choices.length)];
console.log(`Computer chose: ${computerChoice}`);

// 3. Determine the winner


if (userChoice === computerChoice) {
console.log("It's a tie!");
} else if (
(userChoice === "rock" && computerChoice === "scissors") ||
(userChoice === "paper" && computerChoice === "rock") ||
(userChoice === "scissors" && computerChoice === "paper")
){
console.log("You win!");
} else {
console.log("Computer wins!");
}

console.log("--- Game Over ---");


}

// Call the game function to start


playGame();

You might also like