用c语言设计一个小游戏,知识点覆盖一维数组、二维数组、字符串、指针、链表或结构体、文件等知识点,代码在400行左右
时间: 2023-06-19 19:06:36 浏览: 94
以下是一个基于控制台的小游戏,它是猜数字游戏,玩家需要猜出随机生成的数字。代码涵盖了一维数组、字符串、指针、文件等知识点。
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define GUESS_NUM 5 // 猜测次数
#define MAX_NUM 100 // 最大数字
#define FILENAME "score.txt" // 存储分数的文件名
struct Score { // 分数记录结构体
char name[20];
int score;
};
void play_game(); // 游戏主体
int get_guess(); // 获取玩家猜测的数字
void print_result(int secret_num, int guess); // 输出猜测结果
void print_scores(); // 输出分数榜
void save_score(int score); // 保存分数
void sort_scores(struct Score scores[], int count); // 排序分数榜
int main() {
srand(time(NULL)); // 设置随机数种子
play_game(); // 开始游戏
return 0;
}
void play_game() {
printf("Welcome to Guess the Number!\n\n");
printf("I'm thinking of a number between 1 and %d.\n", MAX_NUM);
printf("You have %d tries to guess what it is.\n\n", GUESS_NUM);
int secret_num = rand() % MAX_NUM + 1; // 生成 1~MAX_NUM 的随机数
int guess_count = 0; // 猜测次数
int guess;
while (guess_count < GUESS_NUM) {
guess = get_guess();
print_result(secret_num, guess);
guess_count++;
if (guess == secret_num) {
printf("\nCongratulations! You guessed the number in %d tries.\n", guess_count);
save_score(GUESS_NUM - guess_count);
return;
}
}
printf("\nSorry, you didn't guess the number. It was %d.\n", secret_num);
}
int get_guess() {
int guess;
printf("Guess #%d: ", GUESS_NUM - (GUESS_NUM - 1));
scanf("%d", &guess);
while (getchar() != '\n') {} // 清除缓存区
return guess;
}
void print_result(int secret_num, int guess) {
if (guess < secret_num) {
printf("Too low!\n");
} else if (guess > secret_num) {
printf("Too high!\n");
} else {
printf("You got it!\n");
}
}
void print_scores() {
printf("Scoreboard\n");
printf("----------\n");
FILE *file = fopen(FILENAME, "r");
if (!file) { // 文件不存在
printf("No scores yet.\n");
return;
}
struct Score scores[100];
int count = 0;
while (!feof(file) && count < 100) { // 读取记录
fscanf(file, "%s %d", scores[count].name, &scores[count].score);
count++;
}
fclose(file);
sort_scores(scores, count); // 排序
for (int i = 0; i < count; i++) {
printf("%d. %s: %d\n", i + 1, scores[i].name, scores[i].score);
}
}
void save_score(int score) {
printf("\nYour score is %d.\n", score);
printf("Enter your name: ");
char name[20];
fgets(name, 20, stdin); // 获取姓名
name[strlen(name) - 1] = '\0'; // 删除换行符
FILE *file = fopen(FILENAME, "a");
if (file) {
fprintf(file, "%s %d\n", name, score); // 写入记录
fclose(file);
}
print_scores(); // 输出分数榜
}
void sort_scores(struct Score scores[], int count) {
for (int i = 0; i < count - 1; i++) {
for (int j = i + 1; j < count; j++) {
if (scores[i].score < scores[j].score) { // 按分数排序
struct Score temp = scores[i];
scores[i] = scores[j];
scores[j] = temp;
}
}
}
}
```
代码中使用了文件操作将玩家的得分记录保存下来,并可以在程序中查看分数榜。游戏的主要逻辑在 `play_game()` 中实现,包括生成随机数、获取玩家输入、判断猜测结果等。排序算法使用的是简单的冒泡排序。
阅读全文