用c语言和easyx编写游戏:输入游戏者名字:该名字用于显示在游戏界面上,并在通关后记录该游戏者的得分数,将用户名和得分数记录到highscore.dat文件中,并倒序显示得分最高的前十名信息。
时间: 2024-05-07 10:18:42 浏览: 124
这个任务需要用到 C 语言的文件操作和 EasyX 绘图库,下面是一个简单的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <graphics.h>
#define MAX_NAME_LEN 20 // 最大名字长度
#define MAX_SCORES 10 // 最多记录的得分数
typedef struct {
char name[MAX_NAME_LEN + 1]; // 游戏者名字
int score; // 得分数
} Player;
void save_score(Player* players, int num_players) {
FILE* fp = fopen("highscore.dat", "wb");
if (fp == NULL) {
printf("Error: cannot open file!\n");
exit(1);
}
fwrite(players, sizeof(Player), num_players, fp);
fclose(fp);
}
int compare_scores(const void* p1, const void* p2) {
Player* player1 = (Player*)p1;
Player* player2 = (Player*)p2;
return player2->score - player1->score; // 倒序排列
}
void draw_high_scores(Player* players, int num_players) {
cleardevice();
settextstyle(32, 0, "宋体");
outtextxy(100, 50, "得分最高的前十名:");
int y = 100;
for (int i = 0; i < num_players; i++) {
char text[100];
sprintf(text, "%d. %s: %d 分", i+1, players[i].name, players[i].score);
outtextxy(100, y, text);
y += 50;
}
}
int main() {
initgraph(640, 480);
char name[MAX_NAME_LEN + 1];
printf("请输入游戏者名字:");
scanf("%s", name);
Player player = { .score = 100, .name = name }; // 假设得分为 100
Player players[MAX_SCORES];
int num_players = 0;
FILE* fp = fopen("highscore.dat", "rb");
if (fp) {
num_players = fread(players, sizeof(Player), MAX_SCORES, fp);
fclose(fp);
qsort(players, num_players, sizeof(Player), compare_scores);
}
int i;
for (i = 0; i < num_players; i++) {
if (player.score > players[i].score) {
break;
}
}
if (i < MAX_SCORES) {
for (int j = num_players-1; j >= i; j--) {
players[j+1] = players[j];
}
players[i] = player;
num_players++;
if (num_players > MAX_SCORES) {
num_players = MAX_SCORES;
}
save_score(players, num_players);
}
draw_high_scores(players, num_players);
getch();
closegraph();
return 0;
}
```
这个程序首先让用户输入游戏者名字,然后读取 highscore.dat 文件中已有的得分记录,并按得分倒序排列。然后将新的得分记录插入到合适的位置,保存到文件中。最后在屏幕上绘制前十名得分的信息。
阅读全文