前言
在上一篇文章中我们已经实现了猜数字游戏的基础功能,但是还有一要求没有实现就是查询历史成绩
(1)提供菜单选项,让用户进入游戏。玩得好的玩家记录应保存,并存入硬盘上的文件。 (2)提供菜单选项,查询玩家记录的前五名。
在这里我们就需要运用到C语言中文件相关的程序
一、代码思路:
游戏数据存储格式:
既需要玩家姓名又需要记录成绩,两种或多种不同格式的数据存储在C语言中主要有两种方式:
结构体
链表(针对数据量较大)
这里我们利用结构体来记录历史成绩
struct notes{
char name[20];
int times;
};
typedef struct notes notes;
为便于后期排序我们先将其初始化
notes player[5]={
[0]={
.name="空",
.times=0,
},
[1]={
.name="空",
.times=0,
},
[2]={
.name="空",
.times=0,
},
[3]={
.name="空",
.times=0,
},
[4]={
.name="空",
.times=0,
}
};
数据的读写
这自不必过多赘述
int ReadText(notes player[]){
int i=0;
FILE *fp;
fp=fopen("","r");
if(fp==0){
printf("score txt file error\n");
exit(1);
}
while (!feof(fp)){
fscanf(fp,"%s %d",player[i].name,&player[i].times);
i++;
}
fclose(fp);
for (int j = 0; j < i; ++j) {
printf("第%d名%s成绩为%d次。\n",j+1,player[j].name,player[j].times);
}
}
int WriteText(notes player[]){
FILE *fp;
fp=fopen("","w+");
if(fp==0){
printf("score txt file error\n");
exit(1);
}
for (int j = 0; j < 5; ++j) {
fprintf(fp,"%s %d",player[j].name,player[j].times);
}
fclose(fp);
}
数据排序
将每次的游戏数据与历史记录比较排序,保持排行榜前五
for (int i = 0; i <= 4; ++i) {
if (player[i].times <= socre_times && i != 4) {
if(player[i].times==0){
player[i].times = socre_times;
strcpy(player[i].name, name);
} else{
for (int j = 4; j > i; --j) {
player[j].times = player[j - 1].times;
strcpy(player[j].name, player[j - 1].name);
}
player[i+1].times = socre_times;
strcpy(player[i+1].name, name);
}
break;
} else {
if (i == 0) {
player[i].times = socre_times;
strcpy(player[i].name, name);
}
}
}
结尾:
还有一些选做要求: (可根据自身情况量力而行) (1)对用户的输入进行一定的正确性检查。 (2)除了玩家的猜测次数有限制之外,对玩家猜测的总时间进行限制。 (3)设计一个功能选项“AI 玩家”。当选中此功能后,用电脑模拟用户来玩猜数字游戏, 并将整个游戏的过程输出至屏幕或文本文件。
以上就是今天讲的C语言猜数字游戏进阶目标实现的基本思路,主要运用到了C语言文件相关的操作,希望对刚阅读本篇博客的你有所帮助,喜欢就点赞关注一波吧!!!