JavaScript猜拳游戏报错及优化求助:ReferenceError: prompt未定义
ReferenceError: prompt is not defined及代码优化建议 Hey there! Let's break down your issues and fix up that rock-paper-scissors game step by step.
First: Why the prompt is not defined error?
prompt() is a browser-only API — it pops up that little input box in your web browser. But you're running this code in a Node.js environment (the file path in your error confirms this), and Node doesn't have built-in support for prompt(). That's exactly why you're seeing that reference error.
What to do instead? (Best Practices)
You mentioned trying to skip prompt() and call the code directly — that's totally fine for testing your game logic! Once your logic works perfectly, you can add interactive input. Here are two solid options:
- Option 1 (For interactive play in Node): Use Node's built-in
readlinemodule to get user input from the terminal. - Option 2 (For quick testing): Pass hardcoded values directly to your functions (like you tried) to verify your win/loss logic works without needing user input.
Let's Fix Your Code's Other Issues
Your original code has a few small bugs (typos, mismatched variables, unencapsulated logic) that we'll iron out. Here's a breakdown of the key fixes plus an optimized version:
Key Bugs in Your Original Code
- Mismatched variable names:
getUserChoiceusesuserPromptas a parameter but referencesuserInputinside the function. - Inconsistent capitalization: Mixing
'rock','Paper', and'Scissors'will break your condition checks (strings are case-sensitive!). randomNumberwas wrapped in quotes (so it's a string, not a number calculation).- No
getComputerChoicefunction defined, but you tried to call it inplayGame. - Typos:
determineWinerinstead ofdetermineWinner,playgameinstead ofplayGame. - Unhandled user input cases (like uppercase entries) that would trigger errors.
Optimized, Working Code (Node.js Compatible)
// Option 1: Interactive version using Node's readline module const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout }); // Get user's choice, normalize input and handle valid options const getUserChoice = (userInput) => { const lowerInput = userInput.toLowerCase(); const validChoices = ['rock', 'paper', 'scissors', 'bomb']; if (validChoices.includes(lowerInput)) { return lowerInput; } else { console.log('Oops! Please enter rock, paper, scissors, or bomb (cheat code!).'); return null; } }; // Generate computer's random choice const getComputerChoice = () => { const randomNum = Math.floor(Math.random() * 3); switch (randomNum) { case 0: return 'rock'; case 1: return 'paper'; case 2: return 'scissors'; default: return 'rock'; // Fallback, just in case } }; // Determine who wins const determineWinner = (userChoice, computerChoice) => { if (!userChoice) return 'Invalid input — game over!'; // Bomb cheat code win if (userChoice === 'bomb') { return 'You dropped a bomb! Instant win! 🎉'; } // Tie scenario if (userChoice === computerChoice) { return 'It\'s a tie!'; } // Win/loss logic simplified with ternary operators if (userChoice === 'rock') { return computerChoice === 'paper' ? 'Computer wins!' : 'You win!'; } if (userChoice === 'paper') { return computerChoice === 'scissors' ? 'Computer wins!' : 'You win!'; } if (userChoice === 'scissors') { return computerChoice === 'rock' ? 'Computer wins!' : 'You win!'; } }; // Main game function const playGame = () => { readline.question('Enter your choice: rock, paper, scissors, or bomb\n', (userInput) => { const userChoice = getUserChoice(userInput); const computerChoice = getComputerChoice(); console.log(`You threw: ${userChoice}`); console.log(`Computer threw: ${computerChoice}`); console.log(determineWinner(userChoice, computerChoice)); readline.close(); }); }; // Start the game playGame(); // ------------------------------ // Option 2: Test version with hardcoded input (comment out above to use) // const testGame = () => { // const userChoice = getUserChoice('bomb'); // const computerChoice = getComputerChoice(); // console.log(`You threw: ${userChoice}`); // console.log(`Computer threw: ${computerChoice}`); // console.log(determineWinner(userChoice, computerChoice)); // }; // testGame();
What We Improved
- Fixed the prompt issue: Used
readlinefor Node.js interactive input, or included a test version with hardcoded values. - Normalized input: Converted all user input to lowercase to avoid case-sensitivity bugs.
- Encapsulated logic: Turned computer choice generation into a reusable function (
getComputerChoice). - Fixed typos: Corrected all misspelled function names and variables.
- Added error handling: Gave clear feedback for invalid inputs.
- Simplified logic: Used ternary operators to flatten nested if statements, making the code easier to read.
- Preserved the bomb cheat: Kept your fun instant-win feature and made it a valid input option.
内容的提问来源于stack exchange,提问作者Morgi0no_Atman

