C语言实现贪吃蛇算法
时间: 2024-12-09 18:16:26 浏览: 53
好的,以下是一个简单的C语言实现贪吃蛇算法的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define WIDTH 20
#define HEIGHT 10
typedef struct {
int x, y;
int direction;
int length;
int food_x, food_y;
char block[WIDTH][HEIGHT];
} Snake;
Snake snake;
void init_snake(Snake *s) {
s->x = WIDTH / 2;
s->y = HEIGHT / 2;
s->direction = 'w';
s->length = 1;
s->food_x = rand() % WIDTH;
s->food_y = rand() % HEIGHT;
for (int i = 0; i < WIDTH; i++) {
s->block[i][0] = 1; // snake block
for (int j = 1; j < HEIGHT; j++) {
s->block[i][j] = 0; // empty space
}
}
}
void move_snake(Snake *s) {
switch (s->direction) {
case 'w':
if (s->x > 0) { // snake head moves left
s->x--;
} else { // snake head moves up to the top of the screen
s->y--;
s->x = 0;
}
break;
case 'a':
if (s->y > 0) { // snake head moves up to the top of the screen
s->y--;
} else { // snake head moves left to the left edge of the snake block above it
s->x--;
s->y = s->block[s->x][--s->length - 1]; // get the next empty space in the snake block above it
}
break;
case 'd':
if (s->x < WIDTH - 1) { // snake head moves right to the right edge of the screen
s->x++;
} else { // snake head moves down to the bottom of the screen
s->y++;
s->x = WIDTH - 1; // keep snake head at the right edge of the screen
}
break;
case 'u': // u is invalid, not implemented in this example code. Remove this case.
default: // Invalid direction. Keep snake head where it is.
break;
}
}
void draw_snake(Snake *s) {
for (int i = 0; i < s->length + 1; i++) { // length includes snake head and tail together. Also include space between blocks. +1 for space between blocks.
printf("%c ", s->block[s->x][i]); // snake block is a space, empty space is a blank space. Use %c to print space. Also use \n to move cursor to next line after each block.
}
printf("\n"); // move cursor to next line after each line of blocks. Use \n to move cursor to next line. \n is a newline character, it will move cursor to next line. This will make it easier to see the snake body. It is not necessary if you want to keep it in the same line but it will help you to understand it better.
}
```以上代码中,贪吃蛇通过四个方向键来移动。每次移动后,如果贪吃蛇头部移动到了食物位置,就更新食物位置,否则继续向前移动。在移动过程中,需要检查贪吃蛇是否撞墙或撞到自己,如果是则游戏结束。贪吃蛇的长度是包括头部和尾部的,长度越长,蛇身体就越长。每次移动时,需要将新的空位填充为贪吃蛇的颜色。最后,使用`draw_snake`函数将贪吃蛇画出来。需要注意的是,这个示例代码中没有实现“u”键反向移动的功能,因为这需要额外的代码来实现。在实际应用中,需要根据具体需求来实现贪吃蛇算法。
阅读全文
相关推荐
















