You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript实现Hangman游戏重复字母验证功能求助

Fixing Repeat Guess Validation in Your Hangman Game

Let's get that repeat guess check working smoothly in your game! The core idea is using a Set to track already guessed letters (since Sets make existence checks super fast), and inserting that validation at the right spot in your game loop.

Step-by-Step Integration

  1. Initialize your letters Set outside the game loop so it persists across guesses (don't reset it every loop iteration!).
  2. Inside the "valid single letter" branch, first check if the guess is already in the Set:
    • If yes: Show the repeat message and skip the rest of the loop iteration with continue.
    • If no: Add the guess to the Set, then proceed with checking if it's in the target word.

Full Integrated Code

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});

// Assuming these variables are defined elsewhere (adjust as needed)
const Word = "HANGMAN".split(''); // Example target word
let answerArray = Array(Word.length).fill('_');
let remainingLetters = Word.length;
let lives = 6;
const alphabets = Array.from({length:26},(_,i)=>String.fromCharCode(65+i)); // Full alphabet
const name = "Player";

// Initialize the Set to track guessed letters (outside the loop!)
let letters = new Set();

while (remainingLetters > 0 && lives > 0) {
  console.log("Current progress: " + answerArray.join(""));
  guess = readline.question(name+"'s guess (Enter 9 for lifelines or 0 to pass): ");
  guess = guess.toUpperCase();

  // Handle lifeline/pass first (add your custom logic here!)
  if (guess === "9") {
    console.log("Lifeline used! (Implement your lifeline functionality here)");
    continue;
  }
  if (guess === "0") {
    console.log("You passed this turn.");
    continue;
  }

  // Validate single letter input
  if (guess.length !== 1) {
    console.log("Please enter 1 letter only.");
  } 
  // Process valid single letter guess
  else {
    // Check for repeat guess FIRST
    if (letters.has(guess)) {
      console.log(`You have already picked ${guess} before.`);
      continue;
    } else {
      letters.add(guess);
    }

    correctGuess = 0;
    for (var j = 0; j < Word.length; j++) {
      if (Word[j] == guess) {
        answerArray[j] = guess;
        remainingLetters--;
        correctGuess = 1;
      }
    }
    if (correctGuess == 1){
      console.log("\nGood job! "+guess+" is one of the letters!\n");
      console.log(answerArray.join("")+"\n");
      console.log(`Remaining available letters: ${alphabets.filter(letter => !letters.has(letter)).join(" ")}\n`);
    } else {
      lives -= 1;
      console.log("\nSorry. "+guess+" is not a part of the word.\n");
      console.log(answerArray.join("")+"\n");
      console.log(`Remaining available letters: ${alphabets.filter(letter => !letters.has(letter)).join(" ")}\n`);
      console.log("You have "+lives+" lives remaining.\n");
    }
  }

  // Game end conditions
  if (remainingLetters == 0) {
    console.log("Congratulation! You managed to guess the word!\n");
    readline.close();
    break;
  }
  if (lives == 0) {
    console.log("Game Over... You failed to guess the word. The word is "+Word.join("")+".\n")
    readline.close();
  }
}

Quick Improvements I Added

  • Basic handling for the "9" lifeline and "0" pass options (you can expand these with your own logic easily)
  • Updated the alphabet display to only show unguessed letters (makes the game more intuitive for players)
  • Used template literals (${}) for cleaner string formatting instead of clunky + concatenation
  • Added readline.close() to prevent the program from hanging after the game ends

内容的提问来源于stack exchange,提问作者Wellington

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 18:27:31