用c语言写一个贪食蛇代码
时间: 2023-05-22 16:06:07 浏览: 215
用c语言编写的贪吃蛇的c代码
以下是一个使用 C 语言编写的贪吃蛇游戏的基本框架,希望这可以帮助您:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
// 常量定义
#define MAX_HEIGHT 20
#define MAX_WIDTH 40
#define MAX_LENGTH (MAX_HEIGHT * MAX_WIDTH)
// 方向定义
#define DIRECTION_UP 'w'
#define DIRECTION_DOWN 's'
#define DIRECTION_LEFT 'a'
#define DIRECTION_RIGHT 'd'
// 蛇身定义
typedef struct NODE
{
int x;
int y;
} Node;
// 蛇定义
typedef struct SNAKE
{
int length;
Node nodes[MAX_LENGTH];
} Snake;
// 食物定义
typedef struct FOOD
{
int x;
int y;
} Food;
int board[MAX_HEIGHT][MAX_WIDTH]; // 地图数组,0 表示空,1 表示蛇身,2 表示食物
// 初始化地图
void init_board()
{
int i, j;
for (i = 0; i < MAX_HEIGHT; ++i)
{
for (j = 0; j < MAX_WIDTH; ++j)
{
board[i][j] = 0;
}
}
}
// 画面输出
void draw_board()
{
system("cls"); // 清屏
int i, j;
for (i = 0; i < MAX_HEIGHT; ++i)
{
for (j = 0; j < MAX_WIDTH; ++j)
{
if (board[i][j] == 0)
{
printf(" ");
}
else if (board[i][j] == 1)
{
printf("*");
}
else if (board[i][j] == 2)
{
printf("#");
}
}
printf("\n");
}
}
// 生成初始蛇身
void init_snake(Snake *snake)
{
*(snake->nodes) = (Node){MAX_HEIGHT / 2, MAX_WIDTH / 2};
snake->length = 1;
board[snake->nodes[0].x][snake->nodes[0].y] = 1;
}
// 判断果实是否被吃掉
int detect_food(Snake *snake, Food *food)
{
if (snake->nodes[0].x == food->x && snake->nodes[0].y == food->y)
{
return 1;
}
return 0;
}
// 生成新的果实
void generate_food(Food *food)
{
food->x = rand() % MAX_HEIGHT;
food->y = rand() % MAX_WIDTH;
board[food->x][food->y] = 2;
}
// 更新蛇身位置
int update_snake(Snake *snake, char direction)
{
// 计算新蛇头位置
Node newhead = snake->nodes[0];
switch (direction)
{
case DIRECTION_UP:
newhead.x--;
break;
case DIRECTION_DOWN:
newhead.x++;
break;
case DIRECTION_LEFT:
newhead.y--;
break;
case DIRECTION_RIGHT:
newhead.y++;
break;
}
// 判断是否追尾
int i;
for (i = 1; i < snake->length; ++i)
{
if (newhead.x == snake->nodes[i].x && newhead.y == snake->nodes[i].y)
{
return 0; // 蛇头追尾,游戏结束
}
}
// 判断是否吃到果实
if (detect_food(snake, &((Food){newhead.x, newhead.y})))
{
board[snake->nodes[snake->length].x][snake->nodes[snake->length].y] = 1;
snake->length++;
generate_food(&((Food){newhead.x, newhead.y}));
}
// 蛇身移动
for (i = snake->length - 1; i > 0; --i)
{
snake->nodes[i] = snake->nodes[i - 1];
}
snake->nodes[0] = newhead;
board[newhead.x][newhead.y] = 1;
return 1;
}
int main()
{
srand(GetTickCount()); // 初始化随机数生成器
init_board(); // 初始化地图
Snake snake = {0}; // 新建蛇
init_snake(&snake); // 初始化蛇身
generate_food(&((Food){0, 0})); // 生成第一个果实
char direction = DIRECTION_RIGHT;
while (1)
{
draw_board(); // 刷新画面
if (!_kbhit()) // 暂停一段时间
{
Sleep(100);
continue;
}
char input = _getch(); // 读取输入
if (input == DIRECTION_UP || input == DIRECTION_DOWN || input == DIRECTION_LEFT || input == DIRECTION_RIGHT)
{
direction = input;
}
else if (input == 'q') // 按下 q 键退出游戏
{
break;
}
int result = update_snake(&snake, direction); // 更新蛇身位置
if (!result) // 判断游戏是否结束
{
printf("Game over!\n");
break;
}
}
return 0;
}
```
阅读全文