在c++中用类实现石头剪刀布
时间: 2023-12-25 16:03:22 浏览: 83
好的,可以的!我可以为您提供一个基本的类实现石头剪刀布游戏的示例代码,如下所示:
```c++
#include <iostream>
#include <ctime>
using namespace std;
class RockPaperScissors {
private:
int playerScore, computerScore, tieScore;
// 0: 石头, 1: 剪刀, 2: 布
int playerChoice, computerChoice;
string choices[3] = {"石头", "剪刀", "布"};
public:
RockPaperScissors() {
playerScore = 0;
computerScore = 0;
tieScore = 0;
}
void play() {
while (true) {
cout << "请出拳: (0)石头 (1)剪刀 (2)布" << endl;
cin >> playerChoice;
if (playerChoice < 0 || playerChoice > 2) {
cout << "输入无效,请重新输入!" << endl;
continue;
}
computerChoice = rand() % 3;
cout << "电脑出拳: " << choices[computerChoice] << endl;
int result = (playerChoice - computerChoice + 3) % 3;
if (result == 0) {
cout << "平局!" << endl;
tieScore++;
} else if (result == 1) {
cout << "你赢了!" << endl;
playerScore++;
} else {
cout << "你输了!" << endl;
computerScore++;
}
cout << "当前比分: " << playerScore << "-" << computerScore << "-" << tieScore << endl;
char again;
cout << "是否再来一局?(Y/N)" << endl;
cin >> again;
if (again != 'Y' && again != 'y') {
break;
}
}
}
};
int main() {
srand(time(NULL));
RockPaperScissors game;
game.play();
return 0;
}
```
这个类实现了一个简单的石头剪刀布游戏,玩家通过在控制台输入数字表示出拳,电脑随机生成出拳结果,然后判断胜负,并记录比分。玩家可以选择是否再来一局。
阅读全文