C-结构体栗子


结构体概念

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//  声明一个Monster名字的结构体,里面可以有许多其他类型的变量或者数组
struct Monster
{
// 血量
float blood;
// 数量
int num;
// 等级
int level;
// 坐标
float coordinate[3];
// 名字
char name[10];
};

// 定义a,实体化
struct Monster a;

打怪的结构体实现的栗子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <windows.h>


//声明一个游戏中的怪物结构体
struct Monster
{
// 血量
float blood;
// 数量
int num;
// 等级
int level;
// 坐标
float coordinate[3];
// 名字
char name[10];
};

// 定义a,实体化
struct Monster a;


// 怪物初始化函数
void InitializationMonster() {
a.num = 1;
a.level = 10;
a.blood = 100.0;
a.coordinate[0] = 1.0;
a.coordinate[1] = 2.0;
a.coordinate[2] = 3.0;
strcpy(a.name, "Monster1");
}


// 打印怪物相关信息函数
void PrintMonster() {
printf("怪物数量:%d------怪物坐标:%.2f , %.2f , %.2f------怪物等级:%d------怪物血量:%.2f------怪物名称:%s",
a.num, a.coordinate[0], a.coordinate[1], a.coordinate[2], a.level, a.blood, a.name);
}

void Monster_attacked() {
a.blood -= 20;
}

int main() {
InitializationMonster();
PrintMonster();
// 设置窗口标题
SetConsoleTitleA("Game V1.0");

printf("欢迎来到本游戏!本游戏将带你进行全新的体验!\n\n\n");
printf("初始化ing.");
for (int i = 0; i < 6; i++)
{
printf(".");
Sleep(500);
}
Sleep(2000);
// 初始化怪物数据
InitializationMonster();
printf("\n\n\n初始化完成!!!\n\n\n-----------------------------------------------------------------------------------------------------------------\n\n\n\n");
printf("怪物结构体地址:0x%X \n\n", &a);
printf("进入地图----[地狱之眼]:\n\n");
printf("发现怪物!血量是否进行攻击 (Y/N):");
while (1) {
char Getkey;
scanf_s("%c", &Getkey);
switch (Getkey) {
case 'Y':
do
{
PrintMonster();
Monster_attacked();
} while (a.blood>0);
PrintMonster();
printf("\n怪物已经死亡!获得经验:200 \n\n");
break;
case 'N':
printf("你取消了打怪!\n\n");
break;
default:
break;
}
}
getchar();
return 0;
}