#include<bits/stdc++.h> //猜数主体部分。
#include <cstdlib> //产生随机数
#include <ctime> //产生随机数
using namespace std;
void _computer_guess(); //电脑猜数
void _player_guess(); //玩家猜数
void _computer_guess() { //二分猜数法
short int smaller=1,biger=10000,time=1,pn; //time作为计数器
cout<<"Please think about a number in 1 to 10000. I can guess it in 15 times."<<endl;
while(time<=15&&smaller<=biger) {
cout<<time<<". I think your numeber is :"<<(biger+1)/2<<endl<<"The number is 1.Biger 2.Smaller 3.Right Please in:(1 or 2 or 3)"<<endl;
cin>>pn;
cout<<endl<<endl;
if(pn==1)biger=(biger+smaller)/2;
if(pn==2)smaller=(biger+smaller)/2;
if(pn==3){cout<<"I win!"<<endl;break;} //胜利
time+=1;
}
cout<<"My time(s): "<<time<<endl;
}
void _player_guess() {
srand((int)time(0)); //产生随机数种子
short int cn=rand()%10000+1,pn,time=1; //time作为计数器
cout<<"I will think about a number in 1 to 10000. Can you use 15 times to guess right it?"<<endl;
while(1) {
cout<<time<<". You think my number is : ";
cin>>pn;
if (pn<cn)cout<<pn<<" is smaller than my number."<<endl<<endl;
if (pn>cn)cout<<pn<<" is biger than my number."<<endl<<endl;
if (pn==cn){cout<<pn<<" is my number."<<endl<<" You win!"<<endl<<endl;break;} //胜利
if (time>=15){cout<<"You lose!"<<endl<<"My number is : "<<cn<<endl<<endl;break;} //次数超过15,停止计数
time+=1; //次数+1
}
cout<<"Your time(s): "<<time<<endl;
}
int main() {
int number; //玩家选择游戏方式
while(1) { //选择游戏(初始界面)
cout<<"GUESS NUMBER GAME"<<endl;
cout<<"1.I guess your number"<<endl<<"2.You guess my number"<<endl<<"Please in:";
cin>>number;
system("cls");
if(number==1)_computer_guess();
if(number==2)_player_guess();
system("pause");
system("cls");
}
return 0;
}