```c
include
include
include
define MAX_NAME_LEN 50
define MAX_PLAYERS 10
typedef struct {
char name[MAX_NAME_LEN];
int score;
} Player;
void print_menu() {
printf("猜数字游戏排行榜\n");
printf("1. 开始游戏\n");
printf("2. 退出游戏\n");
printf("请输入您的选择: ");
}
int play_game() {
int target, guess, attempts = 0;
srand(time(NULL));
target = rand() % 100 + 1;
while (1) {
printf("请输入您的猜测: ");
scanf("%d", &guess);
attempts++;
if (guess == target) {
printf("恭喜您,猜对了!\n");
return attempts;
} else if (guess < target) {
printf("太小了!\n");
} else {
printf("太大了!\n");
}
if (attempts >= MAX_PLAYERS) {
printf("游戏结束!\n");
return attempts;
}
}
}
void update_leaderboard(Player *players, int score) {
int i;
for (i = 0; i < MAX_PLAYERS - 1; i++) {
if (players[i].score > score) {
players[i] = players[i + 1];
}
}
players[i].score = score;
}
int main() {
Player players[MAX_PLAYERS];
int num_players = 0;
int choice;
print_menu();
scanf("%d", &choice);
while (choice != 2) {
if (choice == 1) {
if (num_players >= MAX_PLAYERS) {
printf("排行榜已满,无法添加新玩家!\n");
} else {
printf("请输入您的名字: ");
scanf("%s", players[num_players].name);
players[num_players].score = play_game();
num_players++;
update_leaderboard(players, players[num_players - 1].score);
printf("排行榜更新成功!\n");
}
} else {
printf("请重新输入您的选择: ");
}
print_menu();
scanf("%d", &choice);
}
printf("排行榜:\n");
for (int i = 0; i < num_players; i++) {
printf("%s: %d次\n", players[i].name, players[i].score);
}
return 0;
}
```
代码说明:
数据结构:
使用`Player`结构体来存储玩家的名字和分数。
菜单:
`print_menu`函数用于显示游戏菜单。
游戏逻辑:
`play_game`函数用于进行猜数字游戏,并返回猜测次数。
排行榜更新:
`update_leaderboard`函数用于更新排行榜,确保分数最高的玩家排在最前面。
主函数:
`main`函数负责处理用户输入,调用游戏逻辑和排行榜更新函数,并打印最终排行榜。
运行环境:
需要C编译器,如GCC。
可以在Windows或Linux环境下运行。
建议:
可以根据需要扩展程序,例如增加更多的游戏模式或排行榜功能。
代码中使用了`system("cls")`来清屏,这在某些环境下可能不适用,可以考虑使用其他方法来清除屏幕。