当前位置:千优问>常见问答>用C语言编写一个单词接龙的小游戏

用C语言编写一个单词接龙的小游戏

2022-09-10 23:22:20 编辑:join 浏览量:659

用C语言编写一个单词接龙的小游戏

用C语言编写一个单词接龙的小游戏

//囧,代码写好回来一看居然已经有推荐答案了.....#include #include #include #include #include #define MAX 80char buff[MAX+1];char first[4];char last;bool spellCheck(){ int p = 0; while(buff[p] != 0) { if(buff[p] > 'z'||buff[p] < 'a') return false; p++; } return true;}bool syntaxCheck(){ int len = strlen(first); if(len == 3) { if(strncmp(first,buff,3) == 0) return true; else if(strncmp(&first[1],buff,2) == 0) return true; else if(strncmp(&first[2],buff,1) == 0) return true; } else if(len == 2) { if(strncmp(&first[0],buff,2) == 0) return true; else if(strncmp(&first[1],buff,1) == 0) return true; } else if(len == 1) { if(strncmp(&first[0],buff,1) == 0) return true; } return false;}void getWord(){ do { printf("请输入一个全小写的单词,和%s匹配\n",first); scanf("%s",buff); if(!spellCheck()) { printf("拼写错误,请输入一个全小写的单词......\n"); continue; } if(strlen(buff) == 0) { printf("请输入一个单词......\n"); continue; } return; }while(true);}void start(){ FILE *fp = fopen("D:\\1.txt","w");//<--------这里改输出文件的路径 int len; first[0] = rand()%26+'a'; first[1] = 0; last = rand()%26+'a'; printf("a1:%c a2:%c\n",first[0],last); while(true) { getWord(); if(!syntaxCheck()) { printf("输入的单词不符合要求,请重新输入......\n"); continue; } else { fprintf(fp,"%s\n",buff); len = strlen(buff); if(buff[len-1] == last) { printf("%s末尾和a2:%c匹配,所以游戏结束\n",buff,last); break; } else { if(len >= 3) strcpy(first,&buff[len-3]); else strcpy(first,buff); printf("匹配成功,请继续输入......\n"); } } } fclose(fp);}int main(){ srand(GetTickCount()); start(); system("pause");}

标签:C语言,接龙,小游戏