首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >InquirerJS问题

InquirerJS问题
EN

Stack Overflow用户
提问于 2022-10-30 06:57:34
回答 1查看 8关注 0票数 0

用javascript和inquirerJS编写一个程序来提问和玩游戏,如果不想玩好的话,如果想玩更多的游戏,如果想玩更多的话(询问猜测的数字并显示计算机生成的号码问候,如果下一次正确的话,运气会更好)

我试着解决了很多问题,但是有一些与程序逻辑和inquirerJS相关的技术问题,只要在编辑器中运行这段代码,您就会知道它的逻辑错误,而我不知道如何解决它。

`

代码语言:javascript
复制
import inquirer from 'inquirer';
const question =[
    {
      type : 'input' ,
      name : 'first_question' ,
      message : ' Are you ready to play this number guessing game ? \n If yes(Y) otherwise No(N) '
    },
    {
      type: 'list',
      name: 'input',
      message :  "So what's your guessed number   ? ",
      choices: ['1','2','3','4','5','6','7','8','9','10']
    }
  ] 
console.log("-------------------------------");
inquirer
.prompt(question)
.then((answers) => {
    const question1  = answers.first_question ;
    const choices = answers.input;
    // const question2  = answers.second_question ;
    let x = 0;
    x = getRandomInt();
    function getRandomInt() {
        return Math.floor(Math.random() * 10);
    }
    if(question1=== 'Y' || question1==='y'){
        console.log(`You choose this ${choices}`)
        if(choices == x){
        console.log(`Great yor answer is ${x} and its correct `)
        }else{
            console.log(`Your guessed ${choices} and computer generated  number is ${x}  \nBetter luck next time   ` )
        }
    }else if(question1==='N'|| question1 === 'n'){
        console.log("If you don't want to play OK")
    }
}) 

`

EN

回答 1

Stack Overflow用户

发布于 2022-10-30 07:27:14

问题在问题的顺序上。

我将修复JavaScript代码,并对其进行改进。首先,我们用async关键字将执行流封装在一个匿名函数中,这样我们就可以使用asyncawait语法而不是then。我们使用析构来获取由answer1方法返回的对象的inquirer.prompt(...)属性。我们使用match字符串方法来检查用户输入是'Y‘还是'y’。另外,我修正了getRandomInt函数;现在它不可能返回0。

尝试使用以下JavaScript代码:

代码语言:javascript
复制
import inquirer from 'inquirer';

function getRandomInt() {
  return Math.floor(Math.random() * 9 + 1);
}

(async () => {
  const { answer1 } = await inquirer.prompt({
    type: 'input',
    name: 'answer1',
    message: ' Are you ready to play this number guessing game ? \n If yes(Y) otherwise No(N) '
  })

  if (!answer1.match(/[yY]/)) return console.log("It's OK if you don't want to play the game.")

  const { answer2 } = await inquirer.prompt({
    type: 'list',
    name: 'answer2',
    message: "So what's your guessed number   ? ",
    choices: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
  })

  const randomInt = getRandomInt()
  if (randomInt == answer2) return console.log(`Great! Yor answer is ${answer2} and it's correct.`)
  console.log(`Your guessed ${answer2} and computer generated number is ${randomInt}. Better luck next time.`)
})()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74251103

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档