用javascript和inquirerJS编写一个程序来提问和玩游戏,如果不想玩好的话,如果想玩更多的游戏,如果想玩更多的话(询问猜测的数字并显示计算机生成的号码问候,如果下一次正确的话,运气会更好)
我试着解决了很多问题,但是有一些与程序逻辑和inquirerJS相关的技术问题,只要在编辑器中运行这段代码,您就会知道它的逻辑错误,而我不知道如何解决它。
`
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")
}
}) `
发布于 2022-10-30 07:27:14
问题在问题的顺序上。
我将修复JavaScript代码,并对其进行改进。首先,我们用async关键字将执行流封装在一个匿名函数中,这样我们就可以使用async和await语法而不是then。我们使用析构来获取由answer1方法返回的对象的inquirer.prompt(...)属性。我们使用match字符串方法来检查用户输入是'Y‘还是'y’。另外,我修正了getRandomInt函数;现在它不可能返回0。
尝试使用以下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.`)
})()https://stackoverflow.com/questions/74251103
复制相似问题