node 全局变量 process
在node的全局变量 process下面有个 process.argv的数组,这个里面可以获取到用户传入的参数,比如: node index.js hello,这个hello就可以获取到,然后就可以玩游戏了.石头 剪刀 布
const argvCommand = process.argv[ process.argv.length - 1 ] //你输入的
const random = Math.random() * 3
if (random < 1) {
robotAction = '石头'
} else if (random > 2) {
robotAction = '剪刀'
} else {
robotAction = '布'
}
if (robotAction === argvCommand) {
console.log('平局')
} else if ((argvCommand === '石头' && robotAction === '布') || (argvCommand === '石头' && robotAction === '剪刀')
|| (argvCommand === '剪刀' && robotAction === '布')) {
console.log('你赢了!')
} else {
console.log('你输了!')
}
命令行交互
为了提升用户体验,最好有一个交互界面,直接安装引入 inquirer
var inquirer = require('inquirer');
const promptList = [
{
type: 'checkbox',
message: '请选择你要出什么:',
name: 'name',
choices: [
{
name: "石头"
},
new inquirer.Separator(), // 添加分隔符
{
name: "剪刀",
},
new inquirer.Separator(), // 添加分隔符
{
name: "布"
}
]
}
];
inquirer
.prompt(promptList)
.then(answers => {
const peopleAction = answers.name[0]
if (random < 1) {
robotAction = '石头'
} else if (random > 2) {
robotAction = '剪刀'
} else {
robotAction = '布'
}
if (robotAction === peopleAction) {
console.log('平局')
} else if ((peopleAction === '石头' && robotAction === '布') || (peopleAction === '石头' && robotAction === '剪刀')
|| (peopleAction === '剪刀' && robotAction === '布')) {
console.log('你赢了!')
} else {
console.log('你输了!')
}
})
.catch(error => {
if(error.isTtyError) {
// Prompt couldn't be rendered in the current environment
} else {
// Something else went wrong
}
});
可以了,一个精彩有趣的游戏就写好了,可以愉快的玩一整天了...