c++实现用面向对象的方法设计一个电脑与人玩石头,剪刀,布的游戏,要求将数据成员设计为私有访问属性,同时需要提供构造函数来初始化成员;
时间: 2024-02-19 10:57:32 浏览: 22
好的,以下是用C++实现的电脑与人玩石头,剪刀,布游戏的示例代码,满足您的要求:
```cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class Game {
private:
string options[3] = {"rock", "scissors", "paper"};
int player_score = 0;
int computer_score = 0;
public:
Game() {
srand(time(NULL)); // 随机数种子
}
void print_options() {
cout << "Please choose one of the following: " << endl;
cout << "1. Rock" << endl;
cout << "2. Scissors" << endl;
cout << "3. Paper" << endl;
}
string get_player_choice() {
int choice;
cout << "Enter your choice (1-3): ";
cin >> choice;
return options[choice-1];
}
string get_computer_choice() {
int choice = rand() % 3;
return options[choice];
}
void determine_winner(string player_choice, string computer_choice) {
if (player_choice == computer_choice) {
cout << "It's a tie!" << endl;
} else if (player_choice == "rock" && computer_choice == "scissors") {
cout << "You win!" << endl;
player_score++;
} else if (player_choice == "scissors" && computer_choice == "paper") {
cout << "You win!" << endl;
player_score++;
} else if (player_choice == "paper" && computer_choice == "rock") {
cout << "You win!" << endl;
player_score++;
} else {
cout << "Computer wins!" << endl;
computer_score++;
}
}
void print_scores() {
cout << "Player score: " << player_score << endl;
cout << "Computer score: " << computer_score << endl;
}
void play_game() {
cout << "Welcome to the game!" << endl;
string play_again;
do {
print_options();
string player_choice = get_player_choice();
string computer_choice = get_computer_choice();
cout << "You chose: " << player_choice << endl;
cout << "Computer chose: " << computer_choice << endl;
determine_winner(player_choice, computer_choice);
print_scores();
cout << "Do you want to play again? (Y/N) ";
cin >> play_again;
} while (play_again == "y" || play_again == "Y");
cout << "Thanks for playing!" << endl;
}
};
int main() {
Game game;
game.play_game();
return 0;
}
```
在这个C++程序中,我们定义了一个名为Game的类,其中包含了私有访问属性options、player_score和computer_score,以及构造函数Game()。类还定义了打印选项、获取玩家选择、获取计算机选择、确定获胜者、打印得分和玩游戏等方法。通过调用play_game()方法,用户可以开始玩石头,剪刀,布游戏。