You need to enable JavaScript to run this app. 双人JS Hangman游戏:输入目标词如何渲染为对应长度下划线占位符
优惠活动
大模型
产品
解决方案
定价
更多

双人JS Hangman游戏:输入目标词如何渲染为对应长度下划线占位符

双人版JS Hangman占位符展示问题排查与修复

核心代码问题梳理

  • 变量笔误触发运行时错误:randomWord()循环中给未定义的motArray赋值,而前面声明的空数组wordArray全程没有被写入值,JS遇到未定义变量会直接抛错中断后续执行,这就是控制台能打印目标词、但页面渲染不更新的直接原因。
  • 全局answer变量没有被赋值:获取到玩家1输入的目标词后,没有把值存入全局的answer变量,后续所有依赖answer的逻辑(生成占位符、判断猜词结果)拿到的都是初始的空字符串,根本没法正常计算。
  • 格式不匹配导致逻辑失效:
    • secretWord被转成大写存入后续逻辑,但按钮点击传参是小写字母,大小写不一致会导致猜中的字母无法被识别
    • 未猜的字符占位符带前后空格,最后拼接的wordStatus永远和原始无空格的answer字符串不相等,胜利判断不会触发
  • HTML结构生成错误:生成按钮的模板字符串中,id属性和onClick属性之间没有加空格,拼出来的HTML是无效格式,会导致按钮点击事件绑定失效。

修复后的可运行代码

let answer = '';
let maxWrong = 8;
let mistakes = 0;
let guessed = [];
let wordStatus = null;

function randomWord() {
    let secretWord = prompt("Player 1, enter a word to guess", "");
    // 兜底空输入/取消弹窗的场景,避免空值报错
    if (!secretWord) {
        secretWord = "TEST";
    }
    secretWord = secretWord.trim().toUpperCase();
    console.log("Word to guess: " + secretWord);
    // 核心修复:把获取到的目标词赋值给全局answer,供后续所有逻辑使用
    answer = secretWord;

    const secretWordArray = Array.from(secretWord);
    const wordArray = [];
    for (let i = 0; i < secretWordArray.length; i++) {
        wordArray[i] = " _ ";
    }
    return wordArray;
}

function generateButtons() {
    // 修复属性间缺失空格的问题,把点击传参统一转大写匹配answer格式
    let buttonsHTML = 'abcdefghijklmnopqrstuvwxyz'.split('').map(letter =>
        `<button class="btn btn-lg btn-primary m-2" id='${letter}' onClick="chooseLetter('${letter.toUpperCase()}')">${letter}</button>`
    ).join('');

    document.getElementById('keyboard').innerHTML = buttonsHTML;
}

function chooseLetter(chosenLetter) {
    chosenLetter = chosenLetter.toUpperCase();
    // 已经猜过的字母直接禁用跳过,不重复计数
    if (guessed.indexOf(chosenLetter) !== -1) {
        document.getElementById(chosenLetter.toLowerCase()).setAttribute('disabled', true);
        return;
    }
    guessed.push(chosenLetter);
    document.getElementById(chosenLetter.toLowerCase()).setAttribute('disabled', true);

    if (answer.indexOf(chosenLetter) >= 0) {
        guessedWord();
        checkIfGameWon();
    } else if (answer.indexOf(chosenLetter) === -1) {
        mistakes++;
        updateMistakes();
        checkIfGameLost();
        updateHangmanPicture();
    }
}

function updateHangmanPicture() {
    document.getElementById('hangmanPic').src = './images/' + mistakes + '.jpg';
}

function checkIfGameWon() {
    // 修复判断逻辑:去掉占位符的空格,用纯字符内容和answer对比,避免空格导致判断失效
    const pureWord = wordStatus.replaceAll(' ', '');
    if (pureWord === answer) {
        document.getElementById('keyboard').innerHTML = 'You Won!!!';
    }
}

function checkIfGameLost() {
    if (mistakes === maxWrong) {
        document.getElementById('wordSpotlight').innerHTML = 'The answer was: ' + answer;
        document.getElementById('keyboard').innerHTML = 'You Lost!!!';
    }
}

function guessedWord() {
    wordStatus = answer.split('').map(letter => (
        guessed.indexOf(letter) >= 0 ? letter : " _ "
    )).join('');

    document.getElementById('wordSpotlight').innerHTML = wordStatus;
}

function updateMistakes() {
    document.getElementById('mistakes').innerHTML = mistakes;
}

function reset() {
    mistakes = 0;
    guessed = [];
    document.getElementById('hangmanPic').src = './images/0.jpg';

    randomWord();
    guessedWord();
    updateMistakes();
    generateButtons();
}

// 页面初始化流程
document.getElementById('maxWrong').innerHTML = maxWrong;
randomWord();
generateButtons();
guessedWord();

修复后实现效果

  • 玩家1在prompt弹窗输入任意长度的目标词,页面会自动按照词的长度生成对应数量的下划线占位符,比如输入JAVASCRIPT会渲染为_ _ _ _ _ _ _ _ _ _ _
  • 玩家2点击虚拟键盘猜字母时,系统会自动匹配大小写,猜中的字母会替换对应位置的占位符
  • 猜完全部正确字母后触发胜利提示,猜错达到上限会展示正确答案
  • 点击重置按钮会重新唤起玩家1的输入弹窗,开启新一轮游戏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.24 02:15:03