基于类的猜拳游戏,不使用enum
时间: 2024-03-16 17:40:58 浏览: 20
好的,为了更好地封装和组织代码,我们可以使用类来实现猜拳游戏。这里不使用枚举类型,而是使用常量来表示剪刀、石头、布,代码如下:
```cpp
class Game {
public:
static const int SCISSORS = 1;
static const int ROCK = 2;
static const int PAPER = 3;
void start();
void play();
void result(int);
private:
int player;
int computer;
};
```
这里使用了静态成员变量来表示剪刀、石头、布,同时定义了三个公有函数start、play和result,以及两个私有成员变量player和computer。
接下来,我们来实现这三个函数。
start函数用于输出游戏开始的提示信息,代码如下:
```cpp
void Game::start() {
cout << "猜拳游戏开始!" << endl;
}
```
play函数用于获取玩家输入的出拳结果,以及生成电脑的出拳结果,代码如下:
```cpp
void Game::play() {
cout << "请出拳(1-剪刀,2-石头,3-布): ";
cin >> player;
srand(time(NULL));
computer = rand() % 3 + 1;
}
```
result函数用于根据玩家和电脑的出拳结果计算胜负,并输出相应的信息,代码如下:
```cpp
void Game::result(int result) {
switch (result) {
case 0:
cout << "平局!" << endl;
break;
case -1:
cout << "你输了!" << endl;
break;
case 1:
cout << "你赢了!" << endl;
break;
default:
break;
}
}
```
最后,我们可以在main函数中创建Game对象,然后调用start、play和result函数来完成猜拳游戏的逻辑,代码如下:
```cpp
int main() {
Game game;
game.start();
game.play();
int result;
if (game.player == game.computer) {
result = 0; // 平局
} else if (game.player == Game::SCISSORS && game.computer == Game::ROCK ||
game.player == Game::ROCK && game.computer == Game::PAPER ||
game.player == Game::PAPER && game.computer == Game::SCISSORS) {
result = -1; // 玩家输
} else {
result = 1; // 玩家赢
}
game.result(result);
return 0;
}
```
完整代码如下:
```cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class Game {
public:
static const int SCISSORS = 1;
static const int ROCK = 2;
static const int PAPER = 3;
void start();
void play();
void result(int);
private:
int player;
int computer;
};
void Game::start() {
cout << "猜拳游戏开始!" << endl;
}
void Game::play() {
cout << "请出拳(1-剪刀,2-石头,3-布): ";
cin >> player;
srand(time(NULL));
computer = rand() % 3 + 1;
}
void Game::result(int result) {
switch (result) {
case 0:
cout << "平局!" << endl;
break;
case -1:
cout << "你输了!" << endl;
break;
case 1:
cout << "你赢了!" << endl;
break;
default:
break;
}
}
int main() {
Game game;
game.start();
game.play();
int result;
if (game.player == game.computer) {
result = 0; // 平局
} else if (game.player == Game::SCISSORS && game.computer == Game::ROCK ||
game.player == Game::ROCK && game.computer == Game::PAPER ||
game.player == Game::PAPER && game.computer == Game::SCISSORS) {
result = -1; // 玩家输
} else {
result = 1; // 玩家赢
}
game.result(result);
return 0;
}
```