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

基于InquirerJS的JavaScript猜数字游戏逻辑问题求助

猜数字游戏代码问题排查与修复

你当前的代码存在几个逻辑和Inquirer使用上的问题,下面逐一说明并给出修复后的完整代码:

存在的问题

  • 提问流程错误:原代码会一次性弹出所有问题,不管用户选择不玩,都会强制让用户猜数字,不符合“不玩就结束”的需求。需要用Inquirer的条件式提问,先询问是否要玩,再根据回答决定是否继续展示猜数字的问题。
  • 随机数范围错误:Math.floor(Math.random() * 10)生成的是0-9的整数,但游戏要求是1-10的数字,需要调整为Math.floor(Math.random() * 10) + 1。
  • 类型匹配问题:用户通过list选择的是字符串类型的数字(如'5'),而随机数是数字类型,虽然==会隐式转换,但使用===严格相等更规范,建议统一类型。
  • 函数定义位置不合理:getRandomInt定义在回调内部,虽然不影响运行,但提前定义或直接内联生成更清晰。

修复后的代码

import inquirer from 'inquirer';

// 生成1-10的随机整数
function getRandomInt() {
    return Math.floor(Math.random() * 10) + 1;
}

// 先询问是否要玩的问题
const playQuestion = [
    {
        type: 'confirm',
        name: 'wantToPlay',
        message: '准备好玩猜数字游戏了吗?',
        default: true
    }
];

console.log("-------------------------------");
inquirer.prompt(playQuestion).then(answers => {
    if (!answers.wantToPlay) {
        console.log("不想玩也没关系,下次再来!");
        return;
    }

    // 用户要玩,再弹出猜数字的问题
    const guessQuestion = [
        {
            type: 'list',
            name: 'guessedNumber',
            message: '你猜的数字是?',
            choices: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
        }
    ];

    inquirer.prompt(guessQuestion).then(guessAnswers => {
        const userGuess = parseInt(guessAnswers.guessedNumber);
        const computerNumber = getRandomInt();

        console.log(`你猜的数字是:${userGuess}`);
        console.log(`电脑生成的数字是:${computerNumber}`);

        if (userGuess === computerNumber) {
            console.log('太棒了!你猜对了🎉');
        } else {
            console.log('很遗憾,猜错了,下次好运!');
        }
    });
});

修复说明

  1. 使用confirm类型的提问替代输入Y/N,更符合Inquirer的交互规范,用户直接按回车或选择即可。
  2. 采用嵌套的prompt实现条件流程:先判断是否要玩,再决定是否展示猜数字的问题。
  3. 修正了随机数生成范围,确保是1-10的整数。
  4. 将用户输入的字符串转成数字,用===进行严格相等判断,避免类型隐式转换的潜在问题。
  5. 把随机数生成函数提前定义,代码结构更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:50:31