所以我正在编写一个节点CLI应用程序,它包含一个卡片游戏,用户可以在其中抽取5张牌,然后可以选择在手中取出最多4张牌。
我在Javascript中写这个,我正在使用以下npm模块
我还为以下API http://deckofcardsapi.com/
创建了一个包装器使用询问者,用户可以从当前处理最多4张卡进行处理,但是我遇到了一些问题。我并不完全是如何将用户的当前指针传递给查询器提示符中的选择数组。我尝试了一些事情,但我不断收到以下错误:
(node:13764)UnhandledPromiseRejectionWarning:未处理的承诺 rejection(rejection id:2):TypeError:无法读取属性'then' undefined`
(节点:13764)[DEP0018]弃用警告:未处理 承诺拒绝被弃用。在未来,承诺拒绝 未处理的将使用a终止Node.js进程 非零退出代码。
这是我的代码
cli.js
用于解析命令行参数以通过调用node cli.js play
const
app = require('./app'),
yargs = require('yargs')
const flags = yargs.usage('$0: Usage <cmd> [options]')
.command({
command: 'play',
desc: 'play a 5 card draw game',
builder: (yargs) => {
return yargs.option('play', {
alias: 'play',
describe: 'shuffles deck and draws 5 random cards'
})
},
handler: (argv) => { app.play() }
})
.help('help')
.argv
app.js
包含用于运行应用程序的方法
const
cards = require('deckofcards'),
inquirer = require('inquirer')
const prompt = inquirer.createPromptModule();
const draw = (shuffle, n = 1) => {
cards.deck(shuffle)
.then(deck => cards.draw(deck.deck_id, n))
.then(result => {
console.log('-- CARDS --')
result.cards.forEach(card => {
console.log(`${card.value} of ${card.suit}`)
})
console.log('-- REMAING CARDS --')
console.log(result.remaining)
discardPrompt(result)
})
.catch(err => console.log(err))
}
const discardPrompt = (result) => {
return prompt([{
type: 'checkbox',
message: 'select cards to throw away',
name: 'cards',
choices: () => {
const cardsToThrow = []
result.cards.forEach(card => {
const obj = {number : card.value, face : card.suit}
cardsToThrow.push(obj)
}).then(
choices.push(cardsToThrow)
).catch(err => console.log(err))
},
validate: () => function(answer) {
if(answer.length < 1 && answer.length >= 5) {
return "invalid selection, you must select at least 1 card and no more than 4"
}
return true
}
}])
}
const play = () => {
draw(true, 5)
}
module.exports = {
play
}
这是我为Deck of Cards API创建的包装器 的 index.js
const
config = require('./config'),
superagent = require('superagent')
const _fetch = (command) => {
return superagent.get(`${config.url}/${command}`)
.then(response => response.body)
.catch(error => error.response.body)
}
exports.deck = (shuffle) => {
if (shuffle)
return _fetch('deck/new/shuffle/?deck_count=1')
else
return _fetch('deck/new/')
}
exports.draw = (deck, n) => {
return _fetch(`/deck/${deck}/draw/?count=${n}`)
}
exports.shuffle = (deck, n) => {
return _fetch(`deck/${deck}/shuffle/`)
}
当我运行它时,我得到以下输出
node cli.js play
-- CARDS --
ACE of CLUBS
6 of CLUBS
7 of HEARTS
2 of SPADES
QUEEN of CLUBS
-- REMAING CARDS --
47
我会承认我对Javascript很新,而且主要是用Java编写代码,事情的流程对我来说有点抽象,但任何建议都会非常感激