C语言字谜游戏
这是最简单的字谜游戏,通过函数嵌套可以将算法分为简单的“字母表遍历”、“单词抓取”、“单词比对”三个部分组成,由外到内将任务逐渐细化。
#include <stdio.h>
char cross_letters[4][4]={{'t','h','i','s'},{'w','a','t','s'},{'o','a','h','g'},{'f','g','d','t'}};
char *words[]={"this","two","fat","that"};
int direc[8][2]={1,0,1,-1,0,-1,-1,-1,-1,0,-1,1,0,1,1,1};
int main(int argc, char *argv[]) {
int i, j;
int words_catch(int, int);
for(i=0;i<4;i++)
for(j=0;j<4;j++)
words_catch(i, j);
return 0;
}
int words_catch(int i, int j){
int n, di;
int search(char [], int, int, int);
for(n=0;n<4;++n){
if(*(*(cross_letters+i)+j)==*words[n])
for(di=0; di<8; ++di){
if(search(words[n], i, j, di)==1)
printf("The [%d, %d] direction of cross[%d][%d] find out word: %s\n", direc[di][0], direc[di][1], i, j, words[n]);
}
}
}
int search(char s[], int i, int j, int di){
for(i+=direc[di][0],j+=direc[di][1]; (i>=0 && i<4)&&(j>=0 && j<4); i+=direc[di][0], j+=direc[di][1])
if(cross_letters[i][j]==*++s){
if(*(s+1)=='\0')
return 1;
else
continue;
}
else
break;
return 0;
}
代码运行结果:
|