guess.c
来自「c 语言 实例」· C语言 代码 · 共 177 行
C
177 行
#include<time.h>
#include<stdlib.h>
main()
{
int i,iLen,iWord,iCh,words,hits,number;
int bPicked,bRight;
char c,word[20];
char *dictionary="censure center century count country counter counterwise good goose god obsolete rummage meddle best bet is eradicate hope water think your thank thing thin things fat fatter fattest watch watching watchdog";
srand(time(NULL));
for(i=0;dictionary[i]!='\0';i++);
iLen=i;
printf("\Let's begin to play games!\n");
bPicked=0;
i=0;
words=0;
hits=0;
iCh=0;
while((c=getch())!='.')
{
number=rand();
if(number<1)
{
number=1;
}
number=number%iLen;
/*Pick a word.*/
if(!bPicked)
{
iWord=pick(dictionary,word,number,iLen);
if(iWord<1)
{
printf("\n Dictionary error!\n");
break;
}
bPicked=1;
}
/*Judge the character.*/
bRight=judge(word,c,iCh);
switch(bRight)
{
case 9:printf("\nCongratulations!Next,please!\n");
hits++;
words++;
bPicked=0;
iCh=0;
break;
case -1:printf("\nIt is a pity!Next,please!\n");
words++;
bPicked=0;
iCh=0;
break;
default:printf("%c",word[iCh]);
iCh++;
break;
}
}
printf("\n %d words,you hit %d.Thank you!Hope to see you again!\n",words,hits);
getch();
}
int pick(char *from,char *picked,int number,int length)
{
int i,j,step,bPicked,bLetter;
char c;
bPicked=-1;
/* Get a letter for picking a word.*/
step=0;
do
{
if(number+step<length)
{
c=from[number+step];
bLetter=c>=65&&c<=90||c>=97&&c<=122;
if(bLetter)
{
number=number+step;
break;
}
}
if(!bLetter&&number-step>=0)
{
c=from[number-step];
bLetter=c>=65&&c<=90||c>=97&&c<=122;
if(bLetter)
{
number=number-step;
break;
}
}
step++;
}while(!bLetter&&step<length);
if(bLetter)
{
/* Locate the first letter of the word.*/
while(number>0)
{
c=from[number-1];
if(c>=65&&c<=90||c>=97&&c<=122)
{
number--;
}
else
{
break;
}
}
/*Pick the word's letters.*/
j=0;
for(i=number;i<length;i++)
{
c=from[i];
if(c>=65&&c<=90||c>=97&&c<=122)
{
picked[j]=c;
}
else
{
break;
}
j++;
}
picked[j]='\0';
bPicked=j;/* Word's length.*/
}
return bPicked;
}
int judge(char *word,char c,int number)
{
int i,bRight;
bRight=-1;
for(i=0;word[i]!='\0';i++);
if((c=='.'||c==' ')&&number==i)
{
return 9;/*Completely right.*/
}
if(number<i)
{
if(c==word[number])
{
return 8;/*Character is right.*/
}
else
{
return 1;/*Letter is wrong.*/
}
}
else
{
return -1; /*Too many letters.*/
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?