用node.js石头剪刀布小游戏
时间: 2024-09-06 09:03:05 浏览: 77
Node.js创建石头、剪刀、布(Rock Paper Scissors,RPS)游戏的基本步骤如下:
1. **安装所需库**:首先,你需要安装`prompt-sync`模块用于用户交互,可以使用npm进行安装:`npm install prompt-sync`
```bash
npm install prompt-sync
```
2. **创建主程序**:引入所需的库并定义游戏循环。这里我们使用函数来模拟玩家的选择和电脑随机选择。
```javascript
const prompt = require('prompt-sync')();
function getUserChoice() {
return prompt('请选择(r)ock, (p)aper, or (s)cissors: ');
}
function getRandomChoice() {
const choices = ['rock', 'paper', 'scissors'];
return choices[Math.floor(Math.random() * choices.length)];
}
// 游戏主循环
function playGame() {
const userChoice = getUserChoice().toLowerCase();
const computerChoice = getRandomChoice();
console.log(`你选择了 ${userChoice}`);
console.log(`电脑选择了 ${computerChoice}`);
// 判断胜负
if (compareChoices(userChoice, computerChoice)) {
console.log('你赢了!');
} else if (compareChoices(computerChoice, userChoice)) {
console.log('你输了!');
} else {
console.log('平局!');
}
}
```
3. **比较选择函数**:这里通过逻辑判断游戏结果,比如石头打剪刀,剪刀包布等。
```javascript
function compareChoices(choice1, choice2) {
switch (choice1) {
case 'rock':
return choice2 === 'scissors';
case 'paper':
return choice2 !== 'rock';
case 'scissors':
return choice2 !== 'paper';
default:
throw new Error('无效的选择');
}
}
// 开始游戏
playGame();
```
4. **运行游戏**:运行上述代码,用户将能够与电脑进行RPS游戏。
阅读全文
相关推荐


















