node用模块化封装“石头剪刀布”游戏
时间: 2024-09-06 10:02:39 浏览: 26
Node.js中使用模块化封装一个“石头剪刀布”游戏,可以通过创建不同的JavaScript文件来实现各个功能的模块化,从而提高代码的可维护性和复用性。以下是一个简单的实现方法:
1. 创建一个主模块,用于控制游戏流程和用户交互。
2. 创建一个规则模块,定义游戏的规则,如判断胜负。
3. 创建一个随机出拳模块,模拟电脑随机出拳。
4. 创建一个输入处理模块,用于获取用户输入。
例如:
- 主模块(index.js):
```javascript
const getComputerChoice = require('./getComputerChoice');
const getUserChoice = require('./getUserChoice');
const determineWinner = require('./determineWinner');
const playAgain = require('./playAgain');
// 游戏主循环
function startGame() {
let userChoice = getUserChoice();
let computerChoice = getComputerChoice();
console.log(`你的选择是 ${userChoice}, 电脑的选择是 ${computerChoice}`);
const winner = determineWinner(userChoice, computerChoice);
console.log(`胜者是 ${winner}`);
if (playAgain()) {
startGame();
}
}
// 开始游戏
startGame();
```
- 规则模块(determineWinner.js):
```javascript
module.exports = (userChoice, computerChoice) => {
if (userChoice === computerChoice) {
return "平局";
} else if ((userChoice === "石头" && computerChoice === "剪刀") ||
(userChoice === "剪刀" && computerChoice === "布") ||
(userChoice === "布" && computerChoice === "石头")) {
return "你赢了";
} else {
return "电脑赢了";
}
};
```
- 随机出拳模块(getComputerChoice.js):
```javascript
const choices = ['石头', '剪刀', '布'];
module.exports = () => {
const randomIndex = Math.floor(Math.random() * choices.length);
return choices[randomIndex];
};
```
- 输入处理模块(getUserChoice.js):
```javascript
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
module.exports = () => {
return new Promise(resolve => {
rl.question('请选择石头、剪刀或布:', (choice) => {
rl.close();
resolve(choice.trim());
});
});
};
```
- 继续游戏模块(playAgain.js):
```javascript
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
module.exports = () => {
return new Promise(resolve => {
rl.question('是否再来一局?(y/n):', (answer) => {
rl.close();
resolve(answer.trim().toLowerCase() === 'y');
});
});
};
```
在上述示例中,通过模块化的方式,我们把不同的功能分散到不同的模块中,每个模块负责一块独立的功能。这样不仅使得代码更加清晰,也便于管理和扩展。