由电脑模拟庄家随机出拳(数字),玩家通过键盘上输入数字代表剪刀、石头、布,根据电脑和玩家的出拳数字比较判断游戏结果并输出双方的附带信息;设置VIP玩家、增加游戏难易模式、游戏积分等;运用类的继承、虚函数与多态性 写c++程序实现
时间: 2024-04-01 16:32:01 浏览: 13
好的,以下是一个实现您所描述的猜拳游戏的 C++ 代码示例,其中包括了VIP玩家、游戏难易模式、游戏积分等的实现,以及类的继承、虚函数与多态性的运用:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class Player {
protected:
string name;
int score;
public:
Player(string n) {
name = n;
score = 0;
}
virtual int makeMove() = 0;
void addScore() {
score++;
}
int getScore() {
return score;
}
string getName() {
return name;
}
};
class HumanPlayer : public Player {
public:
HumanPlayer(string n) : Player(n) {}
int makeMove() {
int move;
cout << "Enter 1 for rock, 2 for paper, or 3 for scissors: ";
cin >> move;
return move;
}
};
class ComputerPlayer : public Player {
public:
ComputerPlayer() : Player("Computer") {}
int makeMove() {
srand(time(0));
int move = rand() % 3 + 1;
cout << "Computer chooses ";
switch (move) {
case 1:
cout << "rock." << endl;
break;
case 2:
cout << "paper." << endl;
break;
case 3:
cout << "scissors." << endl;
break;
}
return move;
}
};
class VIPPlayer : public HumanPlayer {
public:
VIPPlayer(string n) : HumanPlayer(n) {}
int makeMove() {
int move;
cout << "Enter 1 for rock, 2 for paper, 3 for scissors, or 4 for bomb: ";
cin >> move;
return move;
}
};
int main() {
Player* p1;
Player* p2;
int mode;
cout << "Enter 1 for easy mode (vs. computer), 2 for hard mode (vs. VIP player): ";
cin >> mode;
if (mode == 1) {
p1 = new HumanPlayer("Player 1");
p2 = new ComputerPlayer();
} else if (mode == 2) {
p1 = new HumanPlayer("Player 1");
p2 = new VIPPlayer("VIP Player");
} else {
cout << "Invalid input. Please try again." << endl;
return 0;
}
int rounds;
cout << "Enter the number of rounds you want to play: ";
cin >> rounds;
for (int i = 1; i <= rounds; i++) {
int move1 = p1->makeMove();
int move2 = p2->makeMove();
if ((move1 == 1 && move2 == 3) || (move1 == 2 && move2 == 1) || (move1 == 3 && move2 == 2) || (move1 == 4 && move2 != 4)) {
p1->addScore();
cout << p1->getName() << " wins!" << endl;
} else if ((move2 == 1 && move1 == 3) || (move2 == 2 && move1 == 1) || (move2 == 3 && move1 == 2) || (move2 == 4 && move1 != 4)) {
p2->addScore();
cout << p2->getName() << " wins!" << endl;
} else {
cout << "It's a tie!" << endl;
}
}
cout << "Final score:" << endl;
cout << p1->getName() << ": " << p1->getScore() << endl;
cout << p2->getName() << ": " << p2->getScore() << endl;
delete p1;
delete p2;
return 0;
}
```
上述程序中,`Player` 是一个抽象类,它包括一个玩家的基本信息(名称和得分),以及一个纯虚函数 `makeMove()`,它表示玩家进行出拳的过程。`HumanPlayer` 和 `ComputerPlayer` 分别是 `Player` 的子类,它们分别实现了 `makeMove()` 函数,以便玩家可以进行出拳动作。`VIPPlayer` 是 `HumanPlayer` 的子类,它重写了 `makeMove()` 函数,加入了一种特殊出拳的方式("bomb"),表示VIP玩家具有更高的游戏技能。
在 `main()` 函数中,根据用户选择的游戏模式,创建一个 `HumanPlayer` 和一个 `Player` 对象,然后根据用户输入的回合数进行游戏。在每一轮中,程序调用每个玩家的 `makeMove()` 函数来获取出拳动作,然后根据规则(石头打剪刀、剪刀剪布、布包石头、"bomb"赢一切)来确定胜者,并更新双方的得分。最后,程序输出每个玩家的最终得分,然后删除动态分配的玩家对象。
通过使用类的继承、虚函数与多态性,可以轻松地扩展和修改程序,以适应不同的游戏需求和规则。