用c语言写出贪吃蛇代码,包括数组,指针,文件,结构体
时间: 2024-03-24 15:37:23 浏览: 60
以下是一个简单的贪吃蛇游戏的代码,包含了数组、指针、文件和结构体:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#define MAX_X 20
#define MAX_Y 20
typedef struct {
int x;
int y;
} Point;
typedef struct {
int length;
Point body[MAX_X * MAX_Y];
} Snake;
int map[MAX_X][MAX_Y];
Snake snake;
void initMap() {
int i, j;
for (i = 0; i < MAX_X; i++) {
for (j = 0; j < MAX_Y; j++) {
if (i == 0 || i == MAX_X - 1 || j == 0 || j == MAX_Y - 1) {
map[i][j] = -1;
} else {
map[i][j] = 0;
}
}
}
}
void printMap() {
int i, j;
for (i = 0; i < MAX_X; i++) {
for (j = 0; j < MAX_Y; j++) {
switch (map[i][j]) {
case 0:
printf(" ");
break;
case -1:
printf("#");
break;
case 1:
printf("*");
break;
default:
printf("?");
break;
}
}
printf("\n");
}
}
void addFood() {
int x, y;
do {
x = rand() % (MAX_X - 2) + 1;
y = rand() % (MAX_Y - 2) + 1;
} while (map[x][y] != 0);
map[x][y] = 1;
}
void initSnake() {
int x = MAX_X / 2;
int y = MAX_Y / 2;
snake.length = 2;
snake.body[0].x = x;
snake.body[0].y = y;
snake.body[1].x = x;
snake.body[1].y = y - 1;
map[x][y] = 2;
map[x][y - 1] = 2;
}
void moveSnake(int dx, int dy) {
int i;
int x = snake.body[snake.length - 1].x + dx;
int y = snake.body[snake.length - 1].y + dy;
if (map[x][y] == 1) {
snake.length++;
snake.body[snake.length - 1].x = x;
snake.body[snake.length - 1].y = y;
map[x][y] = 2;
addFood();
} else if (map[x][y] == 0) {
map[snake.body[0].x][snake.body[0].y] = 0;
for (i = 0; i < snake.length - 1; i++) {
snake.body[i].x = snake.body[i + 1].x;
snake.body[i].y = snake.body[i + 1].y;
}
snake.body[snake.length - 1].x = x;
snake.body[snake.length - 1].y = y;
map[x][y] = 2;
} else {
printf("Game over!\n");
exit(0);
}
}
void saveGame() {
FILE *fp;
fp = fopen("snake.dat", "wb");
fwrite(&snake, sizeof(Snake), 1, fp);
fclose(fp);
}
void loadGame() {
FILE *fp;
fp = fopen("snake.dat", "rb");
if (fp == NULL) {
printf("No saved game!\n");
return;
}
fread(&snake, sizeof(Snake), 1, fp);
fclose(fp);
int i;
for (i = 0; i < snake.length; i++) {
map[snake.body[i].x][snake.body[i].y] = 2;
}
}
int main() {
srand(time(NULL));
initMap();
initSnake();
addFood();
char key;
while (1) {
system("cls");
printMap();
key = getch();
switch (key) {
case 'w':
moveSnake(-1, 0);
break;
case 's':
moveSnake(1, 0);
break;
case 'a':
moveSnake(0, -1);
break;
case 'd':
moveSnake(0, 1);
break;
case 'p':
saveGame();
break;
case 'r':
loadGame();
break;
case 'q':
printf("Game over!\n");
exit(0);
default:
break;
}
}
return 0;
}
```
这个代码使用了一个结构体 Snake 来表示贪吃蛇的身体,包含了一个整数 length 表示身体的长度和一个 Point 类型的数组 body 表示每个身体部分的位置。使用了数组来表示地图,使用了指针来操作贪吃蛇的身体,使用了文件来保存和加载游戏,使用了结构体来组织游戏数据。
阅读全文