这是上一个小游戏的升级版,这版本主要是使用commonJs规范以及使用了nodejs中的杀进程的方法。
首先,我们将上个版本的内容进行提取,将处理的逻辑写在一个单独的js(lib.js)中: module.exports = function(player) { var radom = Math.random() * 3; if (radom < 1) { var computer = "剪刀" console.log("电脑出剪刀") } else if (radom > 2) { var computer = '石头' console.log("电脑出石头") } else { var computer = "布" console.log("电脑出布") } if (computer === player) { console.log("玩家出" + player) console.log("平局"); } else if ( (computer == "石头" && player == "布") || (computer == "剪刀" && player == "石头") || (computer == "布" && player == "剪刀") ) { console.log("玩家出" + player) console.log("玩家赢了") } else { console.log("玩家出" + player) console.log("电脑赢了") } } 然后我们在index.js中引用这个js文件 var player = process.argv[process.argv.length - 1] const game = require('./lib'); game(player); 这样我们就能够如同之前 的小游戏一样正常操作。 接下来我们还要做的是在玩家赢电脑三次之后,电脑的小脾气是将自身的进程杀掉,这要怎么做呢?首先我们要统计电脑输给玩家三次,所以我们就需要将其统计起来。 module.exports = function(player) { var radom = Math.random() * 3; if (radom < 1) { var computer = "剪刀" console.log("电脑出剪刀") } else if (radom > 2) { var computer = '石头' console.log("电脑出石头") } else { var computer = "布" console.log("电脑出布") } if (computer === player) { console.log("玩家出" + player) console.log("平局"); return 0; } else if ( (computer == "石头" && player == "布") || (computer == "剪刀" && player == "石头") || (computer == "布" && player == "剪刀") ) { console.log("玩家出" + player) console.log("玩家赢了") return -1; } else { console.log("玩家出" + player) console.log("电脑赢了") return 1; } } 我在双方平局时返回一个0,玩家赢时返回一个 -1,电脑赢时返回一个1。然后我们就需要进行统计。 不过在这里有个问题需要解决的是,我们需要在玩家输入三次之后才能进行进程关闭,那么我们就需要让这个进行之前一直存在,知道玩家赢了电脑三次之后才能关闭进程。我们就是会用到process.stdin来进行获取用户的标准输入,转换成字符串输出出来。 process.stdin.on('data', e => { const player = e.toString().trim(); const result = game(player); console.log(result) }) 完整的判断逻辑就是 process.stdin.on('data', e => { const player = e.toString().trim(); const result = game(player); console.log(result) if (result == -1) { count++; } if (count == 3) { console.log("你太厉害了,我不玩了") process.exit(); } }) 接下来就是这个小游戏的完整代码(前边是libs.js,后边是Index.js): module.exports = function(player) { var radom = Math.random() * 3; if (radom < 1) { var computer = "剪刀" console.log("电脑出剪刀") } else if (radom > 2) { var computer = '石头' console.log("电脑出石头") } else { var computer = "布" console.log("电脑出布") } if (computer === player) { console.log("玩家出" + player) console.log("平局"); return 0; } else if ( (computer == "石头" && player == "布") || (computer == "剪刀" && player == "石头") || (computer == "布" && player == "剪刀") ) { console.log("玩家出" + player) console.log("玩家赢了") return -1; } else { console.log("玩家出" + player) console.log("电脑赢了") return 1; } } var player = process.argv[process.argv.length - 1] const game = require('./lib'); var count = 0; process.stdin.on('data', e => { const player = e.toString().trim(); const result = game(player); console.log(result) if (result == -1) { count++; } if (count == 3) { console.log("你太厉害了,我不玩了") process.exit(); } }) |
|
沙发#
发布于:2019-11-25 15:35
这次新增了使用commonJs规范进行代码编写,然后增加在nodejs中进行进程长期存在和进行进程关闭。
|
|