数据结构石头剪刀布c++
时间: 2023-11-30 17:40:39 浏览: 89
以下是一个简单的石头剪刀布游戏的C++代码,使用了结构体和随机数生成器:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
struct Player {
string name;
int score;
int choice;
};
int main() {
srand(time(NULL)); // 初始化随机数生成器
Player player1, player2;
player1.name = "Player 1";
player2.name = "Player 2";
player1.score = 0;
player2.score = 0;
cout << "Welcome to Rock-Paper-Scissors game!" << endl;
cout << "Enter Player 1's name: ";
cin >> player1.name;
cout << "Enter Player 2's name: ";
cin >> player2.name;
int round = 1;
while (round <= 3) { // 进行三局比赛
cout << "Round " << round << endl;
cout << player1.name << ", enter your choice (1 for rock, 2 for paper, 3 for scissors): ";
cin >> player1.choice;
cout << player2.name << ", enter your choice (1 for rock, 2 for paper, 3 for scissors): ";
cin >> player2.choice;
int winner = (player1.choice - player2.choice + 3) % 3; // 计算胜者
if (winner == 1) {
cout << player1.name << " wins!" << endl;
player1.score++;
} else if (winner == 2) {
cout << player2.name << " wins!" << endl;
player2.score++;
} else {
cout << "It's a tie!" << endl;
}
round++;
}
if (player1.score > player2.score) {
cout << player1.name << " wins the game!" << endl;
} else if (player2.score > player1.score) {
cout << player2.name << " wins the game!" << endl;
} else {
cout << "The game is tied!" << endl;
}
return 0;
}
```
阅读全文