用c语言写一个用二叉树的游戏
时间: 2023-12-19 15:04:53 浏览: 24
好的,下面是一个简单的用二叉树实现的猜数字游戏,用C语言编写。
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct node {
int value;
struct node* left;
struct node* right;
};
typedef struct node Node;
Node* createNode(int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->value = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
Node* insert(Node* root, int value) {
if (root == NULL) {
return createNode(value);
} else if (value < root->value) {
root->left = insert(root->left, value);
} else {
root->right = insert(root->right, value);
}
return root;
}
Node* generateTree() {
Node* root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 70);
insert(root, 20);
insert(root, 40);
insert(root, 60);
insert(root, 80);
return root;
}
int playGame(Node* root) {
int guess;
Node* current = root;
printf("我正在想一个介于1和100之间的数字,你可以猜一下:\n");
while (1) {
scanf("%d", &guess);
if (guess == current->value) {
printf("你猜对了!\n");
return 1;
} else if (guess < current->value) {
printf("猜的数字太小了,请再试一次:\n");
if (current->left == NULL) {
current->left = createNode(rand() % 100 + 1);
}
current = current->left;
} else {
printf("猜的数字太大了,请再试一次:\n");
if (current->right == NULL) {
current->right = createNode(rand() % 100 + 1);
}
current = current->right;
}
}
}
int main() {
srand(time(NULL));
Node* tree = generateTree();
playGame(tree);
return 0;
}
```
游戏规则:程序会生成一个介于1和100之间的随机数字,并且将其存储在一个二叉树中。玩家需要猜测这个数字,程序会根据玩家猜的数字提示玩家继续猜测,直到玩家猜对为止。如果玩家猜到的数字比程序随机生成的数字小,程序会在二叉树的左子树上创建一个新节点,节点值为另一个随机生成的数字;如果玩家猜到的数字比程序随机生成的数字大,程序会在二叉树的右子树上创建一个新节点,节点值同样为另一个随机生成的数字。