游戏规则为:参与游戏的两方,一方出数字,另一方猜数字。例如,正确答案为5346,猜数字的人若猜5238,则提示1A1B,其中有一个5位置对了记为1A,而数字3对了,而位置不对同,记为B,合起来就是1A1B。接下来,猜数者继续猜,直到出现4A0B为止。
// ConsoleApplication12.cpp : 定义控制台应用程序的入口点。
//
#include <stdio.h>
#include <time.h>//time(NULL)
#include<windows.h>// Sleep(5);
#include<iostream>
using namespace std;
void guess(int n);//光标定位
void gotoxy(int &&x, int &&y);
int main()
{
int i;//选项
int n;//生成随机数的位数
while(1)
{
system("cls");
gotoxy(15, 6);
cout << "1.start game";
gotoxy(15, 8);
cout << "2.Rule" ;
gotoxy(15, 10);
cout << "3.exit\n";
gotoxy(25, 15);
cout << "\t\tplease choose:";
cin >> i;
switch(i)
{
case 1:
system("cls");
cout << "please input the digits(1 to n):\n";//猜数字的位数,如5。则代表猜的数为5位
cin >> n;
guess(n);//开始猜测
Sleep(5);
break;
case 2:
system("cls");
cout << "\t\tthe Rules Of The Game\n";
cout << "step1: input the number of digits\n";
cout << "step2: input the number,separated by a space between two number\n";
cout << "step3: A represent location and date are correct\n";
cout << "\tB represent location is correct but data is wrong!\n";
Sleep(8000);//停留
break;
case 3:
exit(0);
default:
break;
}
}
return 0;
}
void guess(int n)//猜测
{
int flag;// 判断生成的随机数是否有重复 如:2344
int a[10];
do
{
flag = 0;
srand((unsigned)time(NULL));//srand函数是随机数发生器的初始化函数。
//它需要提供一个种子,这个种子会对应一个随机数,如果使用相同的种子后面的rand()函数会出现一样的随机数。
//如: srand(1); 直接使用1来初始化种子。不过为了防止随机数每次重复,常常使用系统时间来初始化,即使用 time函数来获得系统时间,
for(int i = 0; i < n; i++)
a[i] = rand() % 10;
for(int i = 0; i < n - 1; i++)
{
for(int j = i + 1; j < n; j++)
if(a[i] == a[j])//比较生成的随机数是否有重复
{
flag = 1;//有则 flag=1,重新生成
break;
}
}
}
while(flag == 1);
// for(int i = 0; i < n; i++)
// cout << a[i]; //测试生成的随机数
int NumOfGuess = 0;// 猜测的次数
int acount;//数字和位置都相同的个数
int bcount;//数字相同位置不同的个数
int b[10];
do
{
NumOfGuess++;// 猜测次数加1
acount = 0;
bcount = 0;
cout << "guess:";
for(int i = 0; i < n; i++)
cin >> b[i];//输入猜测的数
for(int i = 0; i < n; i++)// 开始对比
for(int j = 0; j < n; j++)
{
if(a[i] == b[i])//若位置和数值都相同,acount++,跳出第二层循环,开始从a数组的第下一位进行对比
{
acount++;
break;
}
if(a[i] == b[j] && i != j)//若仅数值相同,则bcount++,跳出第二层循环,开始从a数组的第下一位进行对比
{
// 若 a 4 5 6 7
bcount++;// b 4 6 2 6 当a[2]和b中的每个数开始比较时,当判断到a[2]==b[1]时,就跳出当前循环,
break;// a[2]==b[3]将不作判断,即输出结果为 1A1B
}
}
cout << "clue on:" << acount << "A " << bcount << "B\n\n";
if(acount == n)
{
if(NumOfGuess == 1)
cout << "you are the topmost rung of Fortune's ladder!!\n\n";
else if(NumOfGuess <= 5)
cout << "you are genius!!\n\n";
else
cout << "you need try hard!!\n\n";
getchar();
cout << "Enter anypress to continue!";
getchar();
break;
}
}
while(1);
}
void gotoxy(int &&x, int &&y)
{
COORD coord = {x, y};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
运行结果:
please input the digits(1 to n):
3
guess:1 2 3
clue on:0A 0B
guess:4 5 6
clue on:1A 0B
guess:4 5 7
clue on:1A 0B
guess:4 5 8
clue on:1A 0B
guess:4 5 9
clue on:1A 1B
guess:4 0 9
clue on:1A 2B
guess:0 4 9
clue on:0A 3B
guess:4 9 0
clue on:3A 0B
you need try hard!!
Enter anypress to continue!