猜拳游戏

#include
#include
#include
#include
using namespace std;
class Game
{
private:
int _player;
int _computer;
int _win;
int _draw;
int _count;
public:
Game();
void player();
void computer();
void compare();
void display();


};
Game::Game()
{
_player = 0;
_computer = 0;
_win = 0;
_draw = 0;
_count = 2;


}
void Game::display()
{


if (_win >= _count)
cout << "玩家赢" << _win << ",平" << _draw << ",负" << 3 - _win - _draw << ",你赢了" << endl;
else
{
if (_draw == 0)
cout << "玩家赢" << _win << ",平" << _draw << ",负" << 3 - _win - _draw << ",你输了" << endl;
else
cout << "本局结果无效" << endl;
}
}
void Game::computer()
{
srand((unsigned)time(NULL));//种子值
_computer = 1 + rand() % (1 - 3 + 1);// 生成1-3内的整数
switch (_computer)
{
case 1:
cout << "电脑选的石头" << endl;
break;
case 2:
cout << "电脑选的剪刀" << endl;
break;
case 3:
cout << "电脑选的布" << endl;
break;




}


}
void Game::player()
{
do //获取玩家的有效输入


{
cout << "请选择:1.石头 2.剪刀 3.布" << endl;
cout << "你选择: ";
cin >> _player;
if (_player<1 || _player>3)//选择无效


{
cout << "你的选择无效" << endl;


}
}
while (_player<1 || _player>3);//跑出循环
switch (_player)
{
case 1:
cout << "你选的石头" << endl;
break;
case 2:
cout << "你选的是剪刀" << endl;
break;
case 3:
cout << "你选的是布" << endl;
break;
}


}
//在获取玩家和电脑的选择后,下一步对两者进行比较,并保存结果,由函数compare()执行,代码如下。
void Game::compare()
{


if (_computer == _player)
cout << "我们出的一样" << endl;
else
{
if (_computer == 1)
{
if (_player == 2)
cout << "不好意思,你输了" << endl;
else if (_player == 3)
{
cout << "哈哈,你赢了" << endl;
_win++;


}
else
{
cout << "平局" << endl;
_draw++;


}
}
else if (_computer == 2)
{
if (_player == 1)
{
cout << "哈哈,你赢了" << endl;
_win++;


}
else if (_player == 3)
cout << "不好意思,你输了" << endl;
else
{
cout << "平局" << endl;
_draw++;
}
}
else if (_computer == 3)
{
if (_player == 1)
cout << "不好意思,你输了" << endl;
else if (_player == 2)
{
cout << "哈哈,你赢了" << endl;
_win++;


}
else 
{
cout << "平局" << endl;
_draw++;
}
 
}
}
}
//最后,列出main()函数的定义体,代码如下:
void main()
{
int j = 3;
char ch;
cout << "欢迎完剪刀石头游戏(三局两胜制)" << endl;
Game game;
while (j > 0)
{
game.player();//玩家选择
game.computer();//电脑选择
game.compare();//比较
if (j == 1)
{
game.display();//显示结果
cout << "是否再来一局,输入Y或N" << endl;
cin >> ch;
if (ch == 'Y')
j = 4;//因为之后有j减1,所以赋值为4
else
cout << "退出成功" << endl;


}
j--;//可再进行的局数减一
}
}

你可能感兴趣的:(猜拳游戏)