#include
#include
#include
#define MAX_STR 2048
typedef struct tag_Question Question;
typedef struct tag_Question {
char *ask;
Question *yes;
Question *no;
}Question;
typedef struct tag_QuestionNode QuestionNode;
typedef struct tag_QuestionNode {
Question question;
QuestionNode *next;
} QuestionNode;
QuestionNode *head = NULL;
Question *root;
Question *lastBranch;
Question *lastLeaf;
Question* newQuestion(char *q)
{
QuestionNode *newNode = (QuestionNode*)malloc(sizeof(QuestionNode));
char *s = malloc(strlen(q)+1);
strcpy(s, q);
newNode->question.ask = s;
newNode->question.no = newNode->question.yes = NULL;
newNode->next = head;
head = newNode;
return &(newNode->question);
}
void destroyQuestions()
{
QuestionNode *p = head;
while (p)
{
QuestionNode *next = p->next;
free(p->question.ask);
free(p);
p = next;
}
}
int anwswerIsYes()
{
char anwser[MAX_STR];
gets(anwser);
return anwser[0] == 'y' || anwser[0] == 'Y';
}
int question(Question *qst)
{
if (!qst) return 0;
if (qst->ask[0] == '!')
{
printf("我猜是%s,我猜得对吗?", qst->ask+1);
return anwswerIsYes();
}
printf("%s", qst->ask);
lastBranch = qst;
lastLeaf = anwswerIsYes() ? qst->yes : qst->no;
return question(lastLeaf);
}
void rememberNewAnimal(char *name)
{
char anwser[MAX_STR], qname[MAX_STR];
Question *q, *lfq;
printf("请输入一个问题,可以把%s和%s区分开/n", lastLeaf->ask+1, name);
gets(anwser);
q = newQuestion(anwser);
if (lastBranch->yes == lastLeaf)
{
lastBranch->yes = q;
}
else
{
lastBranch->no = q;
}
printf("对于%s,%s(Y/N)", name, q->ask);
qname[0] = '!';
strcpy(qname+1, name);
lfq = newQuestion(qname);
if (anwswerIsYes())
{
q->yes = lfq;
q->no = lastLeaf;
}
else
{
q->yes = lastLeaf;
q->no = lfq;
}
}
#define N(x) base + x
#define LEAF(s) {"!" s, NULL, NULL}
#define BRANCH(s, a, b) {s, N(a), N(b)}
int main()
{
Question base[] = {
BRANCH("是哺乳动物吗?", 1, 4),
BRANCH("比猫大吗?", 2, 3),
LEAF("袋鼠"),
LEAF("老鼠"),
BRANCH("生活在水中吗?", 5, 6),
LEAF("鳄鱼"),
LEAF("知更鸟"),
};
char anwser[MAX_STR];
root = base;
printf("请在心里想好一种动物,让我来猜一猜/n");
for(;;)
{
if(question(root))
{
printf("我猜对了!/n"
"继续玩吗?"
);
if (!anwswerIsYes()) break;
}
else
{
printf("我认输了,是什么?/n");
gets(anwser);
rememberNewAnimal(anwser);
printf("噢,我明白了/n"
"退出游戏吗?");
if (anwswerIsYes()) break;
}
}
destroyQuestions();
return 0;
}