c++猜拳游戏代码面向对象
时间: 2024-03-16 11:39:49 浏览: 303
当然,我可以为您介绍一下C++猜拳游戏的面向对象代码。以下是一个简单的示例:
```cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
// 定义手势的枚举类型
enum Gesture {
ROCK,
PAPER,
SCISSORS
};
// 定义玩家类
class Player {
public:
Gesture chooseGesture() {
int choice;
std::cout << "请选择手势:(0-石头, 1-剪刀, 2-布): ";
std::cin >> choice;
return static_cast<Gesture>(choice);
}
};
// 定义电脑类
class Computer {
public:
Gesture chooseGesture() {
srand(time(0));
int choice = rand() % 3;
return static_cast<Gesture>(choice);
}
};
// 定义游戏类
class Game {
private:
Player player;
Computer computer;
public:
void play() {
Gesture playerGesture = player.chooseGesture();
Gesture computerGesture = computer.chooseGesture();
std::cout << "玩家选择了:";
printGesture(playerGesture);
std::cout << "电脑选择了:";
printGesture(computerGesture);
if (playerGesture == computerGesture) {
std::cout << "平局!" << std::endl;
} else if ((playerGesture == ROCK && computerGesture == SCISSORS) ||
(playerGesture == PAPER && computerGesture == ROCK) ||
(playerGesture == SCISSORS && computerGesture == PAPER)) {
std::cout << "玩家获胜!" << std::endl;
} else {
std::cout << "电脑获胜!" << std::endl;
}
}
void printGesture(Gesture gesture) {
switch (gesture) {
case ROCK:
std::cout << "石头";
break;
case PAPER:
std::cout << "剪刀";
break;
case SCISSORS:
std::cout << "布";
break;
}
std::cout << std::endl;
}
};
int main() {
Game game;
game.play();
return 0;
}
```
这个示例代码中,我们定义了三个类:`Player`、`Computer`和`Game`。`Player`类表示玩家,`Computer`类表示电脑,`Game`类表示游戏。玩家和电脑都有一个选择手势的方法`chooseGesture()`,游戏类有一个`play()`方法来进行游戏的逻辑处理。
在`play()`方法中,玩家和电脑分别选择手势,然后比较手势的结果来判断胜负。最后输出结果。
希望这个示例能够帮助您理解C++猜拳游戏的面向对象代码。
阅读全文