标签:
#include <iostream>
#include <cstdlib>
#include <conio.h>
#include <ctime>
using namespace std;
//清屏
void ClearScreen()
{
system("cls");
}
//显示菜单
void ViewMenu()
{
cout<<"******************"<<endl;
cout<<"1.玩家自定数字"<<endl;
cout<<"2.系统随机数字"<<endl;
cout<<"3.规则"<<endl;
cout<<"4.退出游戏"<<endl;
cout<<"******************"<<endl;
}
//显示规则
void ViewRule()
{
cout<<"***********************************************"<<endl;
cout<<"本游戏分为玩家自定谜底和系统定义谜底"<<endl;
cout<<"玩家进行猜数字游戏,输入要猜的数字"<<endl;
cout<<"谜底是四位互不相同的0-9数字组成"<<endl;
cout<<"A提示的是其中一位与谜底对应位是相同的"<<endl;
cout<<"B提示的是其中一位数字与谜底中的一位相同但不对应"<<endl;
cout<<"4A0B表示所猜数字与谜底相同"<<endl;
cout<<"***********************************************"<<endl;
}
//是否有相等位
bool CheckNum(int a[])
{
if(a[0] != a[1] && a[2] != a[3] && a[0]!= a[3] && a[0] != a[2] && a[1] != a[3] && a[1] !=a[2])
return true;
else
return false;
}
//暂停一下
void HoldOn()
{
system("pause");
}
//游戏主程序
void NumberGame()
{
char n;//命令选择
int a=0,b=0;//回馈参数
int GasNumber[4];//要猜的数字
while(1)
{
ViewMenu();
n=getch();
ClearScreen();
switch(n)
{
case ‘1‘://玩家输入数字
{
//输入->检测->分解->相同则返回继续输入
cout<<"清输入要猜的四位数字"<<endl;
int temp;
cin>>temp;
loop:
while(temp<=999 || temp >= 10000 && !cin.fail())
{
cout<<"输入错误,清重新输入四位数字!"<<endl;
cin.clear();
cin.sync();
cin>>temp;
}
for(int i=1;i<=4;i++)
{
GasNumber[4-i]=temp%10;
temp=temp/10;
}
if(!CheckNum(GasNumber))
goto loop;
a=b=0;//重置
cin.clear();
cin.sync();
ClearScreen();
cout<<"请输入要猜的数字!"<<endl;
int Gas;
cin>>Gas;
while(1)
{
if(cin.fail())
{
cout<<"输入错误,清重新输入"<<endl;
}
else //计算a,b的值
{
int de[4];
for(int i=1;i<=4;i++)
{
de[4-i]=Gas%10;
Gas=Gas/10;
}
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
if(GasNumber[i]==de[j])
if(i==j)
a++;
else
b++;
}
}
}
if(a==4)
{
cout<<"所猜数字回馈:"<<a<<"A"<<b<<"B"<<endl;
cout<<"猜数字结束"<<endl;
HoldOn();
ClearScreen();
break;
}
else
cout<<"所猜数字回馈:"<<a<<"A"<<b<<"B"<<endl;
a=b=0;//重置
cout<<"请输入要猜的数字!"<<endl;
cin.clear();
cin.sync();
cin>>Gas;
}
break;
}
case ‘2‘://系统自定义
{
srand(time(0));
while(1)
{
GasNumber[0]=rand()%10;
GasNumber[1]=rand()%10;
GasNumber[2]=rand()%10;
GasNumber[3]=rand()%10;
if(CheckNum(GasNumber))
break;
}
a=b=0;//重置
cin.clear();
cin.sync();
ClearScreen();
cout<<"请输入要猜的数字!"<<endl;
int Gas;
cin>>Gas;
while(1)
{
if(cin.fail())
{
cout<<"输入错误,清重新输入"<<endl;
}
else //计算a,b的值
{
int de[4];
for(int i=1;i<=4;i++)
{
de[4-i]=Gas%10;
Gas=Gas/10;
}
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
if(GasNumber[i]==de[j])
if(i==j)
a++;
else
b++;
}
}
}
if(a==4)
{
cout<<"所猜数字回馈:"<<a<<"A"<<b<<"B"<<endl;
cout<<"猜数字结束"<<endl;
HoldOn();
ClearScreen();
break;
}
else
cout<<"所猜数字回馈:"<<a<<"A"<<b<<"B"<<endl;
a=b=0;//重置
cout<<"请输入要猜的数字!"<<endl;
cin.clear();
cin.sync();
cin>>Gas;
}
break;
}
case ‘3‘://显示规则
{
ViewRule();
HoldOn();
ClearScreen();
break;
}
case ‘4‘: //退出程序
{
cout<<"欢迎使用本程序"<<endl;
exit(0) ;
}
}
}
}
int main()
{
NumberGame();
return 0;
}
标签:
原文地址:http://www.cnblogs.com/chentingk/p/5089814.html