My version of animal guessing game in C:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
struct tree_t
{
char* item;
struct tree_t* left;
struct tree_t* right;
};
void getstr(char* s, int n)
{
char* p;
fgets(s, n, stdin);
for (p=s; *p; ++p)
{
if (*p == '\n')
{
*p = '\0';
break;
}
}
}
int yes()
{
char buff[16];
fgets(buff, 16, stdin);
return (tolower(buff[0]) == 'y');
}
int main()
{
struct tree_t* tree;
char* guess;
char* animal;
char* ques;
tree = malloc(sizeof(struct tree_t));
tree->item = "bird";
tree->left = tree->right = 0;
while (1)
{
printf("Are you thinking of an animal? ");
if (! yes()) break;
while(tree->left)
{
printf("%s? ", tree->item);
if (yes())
tree = tree->right;
else
tree = tree->left;
}
guess = tree->item;
printf("Is it %s? ", guess);
if (yes())
{
printf("I rule!\n");
continue;
}
printf("What is the animal's name? ");
animal = malloc(64);
getstr(animal, 64);
printf("What question would distinguish a %s from a %s? ", animal, guess);
ques = malloc(256);
getstr(ques, 256);
tree->item = ques;
printf("If the animal were %s the answer would be? ", animal);
tree->left = malloc(sizeof(struct tree_t));
tree->right = malloc(sizeof(struct tree_t));
if (yes())
{
tree->left->item = guess;
tree->right->item = animal;
}
else
{
tree->left->item = animal;
tree->right->item = guess;
}
tree->left->left = tree->left->right = 0;
tree->right->left = tree->right->right = 0;
}
return 0;
}