数据结构c语言贪吃蛇完整代码
时间: 2023-07-25 16:41:09 浏览: 132
数据结构课程设计之贪吃蛇(源代码)
5星 · 资源好评率100%
好的,下面是完整的 C 语言贪吃蛇游戏代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#include <windows.h>
#define BOARD_WIDTH 20
#define BOARD_HEIGHT 20
typedef struct {
int x;
int y;
} SnakePart;
typedef struct {
SnakePart parts[100];
int length;
} Snake;
int board[BOARD_WIDTH][BOARD_HEIGHT];
void init_board() {
for (int i = 0; i < BOARD_WIDTH; i++) {
for (int j = 0; j < BOARD_HEIGHT; j++) {
board[i][j] = 0;
}
}
}
void draw_snake(Snake* snake) {
for (int i = 0; i < snake->length; i++) {
board[snake->parts[i].x][snake->parts[i].y] = 1;
}
}
void move_snake(Snake* snake, int direction) {
SnakePart new_part = { snake->parts[0].x, snake->parts[0].y };
switch (direction) {
case 0: new_part.y--; break; // 上
case 1: new_part.x++; break; // 右
case 2: new_part.y++; break; // 下
case 3: new_part.x--; break; // 左
}
snake->length++;
for (int i = snake->length - 1; i > 0; i--) {
snake->parts[i] = snake->parts[i - 1];
}
snake->parts[0] = new_part;
board[snake->parts[snake->length - 1].x][snake->parts[snake->length - 1].y] = 0;
snake->length--;
}
int check_food(Snake* snake, SnakePart food) {
if (snake->parts[0].x == food.x && snake->parts[0].y == food.y) {
snake->length++;
snake->parts[snake->length - 1] = food;
return 1;
}
return 0;
}
int main() {
init_board();
Snake snake = { { {10, 10}, {10, 9}, {10, 8} }, 3 };
draw_snake(&snake);
SnakePart food = { 5, 5 };
board[food.x][food.y] = 2;
int direction = 0;
while (1) {
if (kbhit()) {
switch (getch()) {
case 'w': direction = 0; break;
case 'd': direction = 1; break;
case 's': direction = 2; break;
case 'a': direction = 3; break;
}
}
move_snake(&snake, direction);
if (check_food(&snake, food)) {
srand(time(NULL));
food.x = rand() % BOARD_WIDTH;
food.y = rand() % BOARD_HEIGHT;
board[food.x][food.y] = 2;
}
system("cls");
for (int i = 0; i < BOARD_WIDTH; i++) {
for (int j = 0; j < BOARD_HEIGHT; j++) {
if (board[i][j] == 0) {
printf(" ");
} else if (board[i][j] == 1) {
printf("O");
} else if (board[i][j] == 2) {
printf("*");
}
}
printf("\n");
}
Sleep(100);
}
return 0;
}
```
在这个代码中,我们使用了 Windows.h 库中的 Sleep 函数来控制游戏循环的速度,以保证游戏运行的流畅性。
阅读全文