This script randomly selects a word from a list, reverses it, and challenges the player to guess the original word. It demonstrates basic Node.js functionality, including using the readline
module for handling terminal input.
Click to view script…
// reverseWordPuzzle.js
// List of words for the puzzle
const words = ['apple', 'banana', 'orange', 'strawberry', 'grape', 'pineapple', 'kiwi'];
// Function to reverse a given word
function reverseWord(word) {
return word.split('').reverse().join('');
}
// Function to pick a random word from the array
function getRandomWord() {
return words[Math.floor(Math.random() * words.length)];
}
// Main function to run the game
function playGame() {
const originalWord = getRandomWord();
const reversedWord = reverseWord(originalWord);
console.log("=== Reverse Word Puzzle ===");
console.log(`Unscramble this reversed word: ${reversedWord}`);
// Create an interface for user input
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Ask the user for their guess
rl.question("Your guess: ", (answer) => {
if(answer.trim().toLowerCase() === originalWord.toLowerCase()){
console.log("Correct! Well done.");
} else {
console.log(`Incorrect. The correct word was: ${originalWord}`);
}
rl.close();
});
}
// Start the game
playGame();