Hồi đó cũng làm thử cái Guess number nhưng code ngu nên dài dòng quá.
Đoán số nằm trong đoạn từ 1 - 100 thì máy đoán kiểu nhị phân 7 lần là ra thôi.
#include<iostream>
#include<stdlib.h>
#include<time.h>
#include<windows.h>
using namespace std;
void Win(int choice)
{
cout<<"==================================="<<endl;
switch(choice)
{
case 1: cout<<"Computer win"<<endl;
break;
case 2: cout<<"User win"<<endl;
}
cout<<"==================================="<<endl;
exit(0);
}
void Lose(int choice,int so)
{
cout<<"==================================="<<endl;
switch(choice)
{
case 1: cout<<"Computer lose"<<endl;
break;
case 2: cout<<"User lose"<<endl;
break;
}
cout<<"So duoc dua ra la: "<<so<<endl;
cout<<"==================================="<<endl;
exit(0);
}
void goiy(int doan,int so)
{
cout<<endl;
cout<<"Nguoi choi doan so: "<<doan<<endl;
if(doan>so)
cout<<"So nay lon hon so duoc dua ra"<<endl;
else if(doan < so)
cout<<"So nay be hon so duoc dua ra"<<endl;
}
void Computer(int &left,int &right, int &mid, int choice,int &doan,int so,int &solandoan,int n)
{
Sleep(900);
mid = (left + right) / 2;
if(solandoan < n - 1)
doan = mid;
else
{
srand(time(NULL));
int temp = right - left;
doan = rand()%temp + left;
}
solandoan++;
goiy(doan,so);
if(doan > so)
right = mid - 1;
else
left = mid + 1;
if(doan == so)
Win(choice);
}
void User(int choice,int &doan, int so, int &solandoan)
{
cout<<"Moi ban nhap so: ";
cin>>doan;
solandoan++;
goiy(doan,so);
if(doan == so)
Win(choice);
}
int main(void)
{
int choice;
int n,left = 0, right = 100, mid;
int solandoan = 0;
int so,doan;
cout<<"==================================="<<endl;
cout<<"TRO CHOI DOAN SO"<<endl;
cout<<"==================================="<<endl;
cout<<"\n[1] User - Computer"<<endl;
cout<<"[2] Computer - User"<<endl;
do
{
cout<<"Choose: ";
cin>>choice;
}while(choice != 1 && choice != 2);
switch(choice)
{
case 1:
{
do
{
cout<<"Enter number (1 - 100): ";
cin>>so;
cin.ignore();
}while(so < 1 || so > 100);
do
{
cout<<"Nhap so lan doan duoc cho phep (5-8 lan): ";
cin>>n;
}while(n<5 || n>8);
while(solandoan < n)
{
Computer(left,right,mid,choice,doan,so,solandoan,n);
}
Lose(choice,so);
}
break;
case 2:
{
srand(time(NULL));
so = rand()%100;
n = rand()%7+3;
cout<<"Ban duoc quyen doan "<<n<<" lan"<<endl;
while(solandoan < n)
{
User(choice,doan,so,solandoan);
}
Lose(choice,so);
}
break;
}
}