Wenquxing guessing game,the rules of which are simple,is not very easy for us.
In this game,computer gives a random number with four digits,each of which is different from the others,and we assumpt the top one can be 0.Then the player guesses it until he or she guesses rightly or guesses wrongly within a specific number of times determined by your inputing.Of course,there are hints after every guessing,which are like this,"xAyB".x is the number of digits guessed with right digits and positions,and there is/are y right digit(s) with wrong position(s).Do you want to write this game by yourself and play it?At least I do.
//Wenquxing Guessing Game
#include <stdio.h>
#include <time.h>
void MakeDigit(int a[4]);//Computer gives a random number
void InputDigit(int b[4]);//Player input a number
int IsRightPosition(int a[4],int b[4]);//Calculate how many correct digits guessed with right positions
int IsRightDigit(int a[4],int b[4]);//Calculate how many correct digits guessed with whether right or wrong positions
int main(void)
{
int level,count=0,rightPosition,rightDigit,a[4],b[4];
MakeDigit(a);
do
{
printf("How many times do you want to guess?Please input a positive integer:");
scanf("%d",&level);
}
while (level<=0);
do
{
printf("No.%d of %d times\n",count,level);
InputDigit(b);
count++;
rightPosition=IsRightPosition(a,b);
rightDigit=IsRightDigit(a,b)-rightPosition;
printf("%dA%dB\n",rightPosition,rightDigit);
}
while (rightPosition<4&&count<level );
if (rightPosition==4)
printf("Congratulations.You guessed the right number at No.%d.\n",count);
else
printf("Sorry.You didn't guess the right number.See you next time!\n");
printf("Correct answer is:");
for(count=0;count<4;count++)
printf("%d",a[count]);
return 0;
}
void MakeDigit(int a[4])
{
int i,j;
srand(time(NULL));
for (i=0;i<4;i++)
{
Repeata:
a[i]=rand()%10;
for (j=0;j<i;j++)
if (a[j]==a[i])
goto Repeata;
}
}
void InputDigit(int b[4])
{
int k,m,n;
do
{
Repeatb:
printf("Input your guess with four digits,each of which should be different from the others(top digit 0 allowed):");
scanf("%d",&k);
for (m=3;m>=0;m--)
{
b[m]=k%10;
k/=10;
for (n=3;n>m;n--)
if (b[n]==b[m])
goto Repeatb;
}
}
while (k<0||k>=10000);
}
int IsRightPosition(int a[4],int b[4])
{
int r,s=0;
for (r=0;r<4;r++)
if (a[r]==b[r])
s++;
return s;
}
int IsRightDigit(int a[4],int b[4])
{
int x,y,z=0;
for (x=0;x<4;x++)
for (y=0;y<4;y++)
if (a[x]==b[y])
z++;
return z;
}
Seems simple,right?Have fun with it!