c语言打袋鼠游戏,c语言"猜动物"游戏

#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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值