写的一个猜拳小游戏,博大家一乐
#include<iostream>#include<ctime>
#include<string>
using namespace std;
class Game;
class Player
{
public:
Player(){score=0;}
int show_fist(int fist);
friend class Game;
private:
string name;
int fist;
int score;
};
class Computer
{
public:
Computer(){score=0;}
int show_fist();
friend class Game;
private:
string name;
int score;
};
class Game
{
public:
void show_result();
void newgame();
private:
Player player;
Computer computer;
static int count;
};
int Game::count=0;
int main() //主函数
{
Game game;
game.newgame();
game.show_result();
return 0;
}
int Player::show_fist(int fist)
{
switch(fist)
{
case 1:cout<<name<<"出的是剪刀!"<<endl;break;
case 2:cout<<name<<"出的是石头!"<<endl;break;
case 3:cout<<name<<"出的是布!"<<endl;break;
}
return fist;
}
int Computer::show_fist()
{
srand((unsigned)time(NULL));
int fist=rand()%3+1;
switch(fist)
{
case 1:cout<<name<<"出的是剪刀!"<<endl;break;
case 2:cout<<name<<"出的是石头!"<<endl;break;
case 3:cout<<name<<"出的是布!"<<endl;break;
}
return fist;
}
void Game::newgame()
{
int select;
string access;
cout<<"---------欢迎进入猜拳游戏-------------------"<<endl;
cout<<"猜拳规则:1.剪刀 2.石头 3.布"<<endl;
cout<<"请选择对手:1.刘备 2.曹操 3.孙权(请输入数字):"<<endl;
cin>>select;
switch(select)
{
case 1:computer.name="刘备";break;
case 2:computer.name="孙权";break;
case 3:computer.name="曹操";break;
}
cout<<"请输入您的尊姓大名:";
cin>>player.name;
cout<<"开始游戏吗?(yes or no):";
cin>>access;
while(access=="yes")//循环;
{
int fist;
cout<<"请出拳:";
cin>>fist;
int pfist=player.show_fist(fist);
int cfist=computer.show_fist();
if((pfist==1&&cfist==3)||(pfist==2&&cfist==1)||(pfist==3&&cfist==2))
{
cout<<player.name<<"获胜!"<<endl;
player.score+=10;
}
else if(pfist==cfist)
cout<<"本局打和!"<<endl;
else
{cout<<computer.name<<"获胜!"<<endl;
computer.score +=10;}
count++;
cout<<"还继续游戏吗?(yes or no):";
cin>>access;
}
}
void Game::show_result ()
{
cout<<"-----------------比赛结果------------------"<<endl;
cout<<"对战双方:"<<player.name<<"vs"<<computer.name<<endl;
cout<<"一共比赛"<<count<<"局"<<endl;
cout<<player.name<<"得分为:"<<player.score<<endl;
cout<<computer.name<<"得分为:"<< computer.score<<endl;
}