本文共 2070 字,大约阅读时间需要 6 分钟。
今天我们将使用Node.js开发一个经典的小游戏——剪刀石头布。这个游戏不仅简单有趣,还能帮助我们了解Node.js的基本功能和流程。
剪刀石头布的规则非常简单:
游戏将进行三局两胜制,先达到三局胜利的一方获胜。
const readline = require('readline');const clear = require('clear');const chalk = require('chalk');const act = ['剪刀', '石头', '布']; let num = 1; // 回合数let score = 0; // 总得分const rl = readline.createInterface({ input: process.stdin, output: process.stdout});clear();const beginText = chalk.green('开始游戏,请输入:【剪刀】、【石头】、【布】,退出游戏请输入: quit');console.log(beginText); rl.on('line', function(input) { if (input === 'quit') { rl.close(); } else if (act.indexOf(input) !== -1) { const idx = Math.floor(Math.random() * act.length); const gamer = act[idx]; const curScore = scoreRule(input, gamer); score += curScore; const win = curScore === 1 ? '玩家获胜' : curScore === -1 ? '电脑获胜' : '打平'; const result = `第${num}回合:玩家出${input},电脑出${gamer},${win}`; console.log(result); num++; if (num > 3) { rl.close(); } } else { console.log('请正确输入剪刀、石头、布或quit'); }});rl.on('close', () => { if (score > 0) { console.log('玩家获得了最终胜利'); } else if (score < 0) { console.log('玩家最后还是输了'); } else { console.log('游戏结局:平局'); } process.exit(0);});function scoreRule(player, npc) { if (player === npc) return 0; const win = (player === '剪刀' && npc === '布') || (player === '石头' && npc === '剪刀') || (player === '布' && npc === '石头'); return win ? 1 : -1;} readline用于处理用户输入,clear用于清屏,chalk用于终端样式,act数组存储了游戏的动作选项。readline实例,清屏并打印游戏开始提示。通过这个简单的游戏,我们学习了Node.js的基本流程和readline的使用方法,同时也掌握了如何通过代码模拟游戏逻辑。这只是Node.js的应用之一,随着学习的深入,你会发现它在开发中有无数可能性。
转载地址:http://pbquz.baihongyu.com/