This Node.js script lets you challenge the computer in a classic match of Rock, Paper, Scissors. Simply enter your move, and the computer will randomly choose its move, with the game determining the winner based on standard rules.
Click to view script…
/*
* Rock, Paper, Scissors Game
*
* Instructions:
* 1. Enter your move: "rock", "paper", or "scissors".
* 2. The computer will randomly choose its move.
* 3. The game will then announce the winner:
* - Rock crushes scissors.
* - Scissors cuts paper.
* - Paper covers rock.
*
* Enjoy the game!
*/
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const choices = ["rock", "paper", "scissors"];
// Function to randomly select the computer's choice
function getComputerChoice() {
const randomIndex = Math.floor(Math.random() * choices.length);
return choices[randomIndex];
}
// Function to determine the result of the game
function getResult(userChoice, computerChoice) {
if (userChoice === computerChoice) {
return "It's a tie!";
}
if (userChoice === "rock") {
return computerChoice === "scissors" ? "You win! Rock crushes scissors." : "You lose! Paper covers rock.";
}
if (userChoice === "paper") {
return computerChoice === "rock" ? "You win! Paper covers rock." : "You lose! Scissors cuts paper.";
}
if (userChoice === "scissors") {
return computerChoice === "paper" ? "You win! Scissors cuts paper." : "You lose! Rock crushes scissors.";
}
}
// Main game loop
function playGame() {
rl.question("Enter your move (rock, paper, or scissors): ", (answer) => {
let userChoice = answer.trim().toLowerCase();
if (!choices.includes(userChoice)) {
console.log("Invalid move. Please choose rock, paper, or scissors.");
return playGame();
}
const computerChoice = getComputerChoice();
console.log(`Computer chose: ${computerChoice}`);
const result = getResult(userChoice, computerChoice);
console.log(result);
rl.question("Play again? (yes/no): ", (response) => {
if (response.trim().toLowerCase().startsWith("y")) {
playGame();
} else {
console.log("Thanks for playing!");
rl.close();
}
});
});
}
console.log("=== Rock, Paper, Scissors Game ===");
playGame();