c语言怎么编程贪吃蛇

时间:2025-01-24 22:28:15 游戏攻略

贪吃蛇游戏可以通过C语言实现,以下是一个简单的代码示例,该示例基于控制台运行,使用方向键控制蛇的移动,游戏中蛇会吃食物并增长长度,碰到边界或者自身则游戏结束。

```c

include

include

include

include

define WIDTH 40

define HEIGHT 20

typedef struct SnakeNode {

int x;

int y;

struct SnakeNode *next;

} SnakeNode;

SnakeNode *snakeHead = NULL;

int foodX, foodY;

int score = 0;

int gameOver = 0;

void initSnake();

void createFood();

void drawMap();

void moveSnake(int direction);

int checkCollision();

void addNodeToSnake(int x, int y);

void freeSnake();

int main() {

srand(time(NULL));

initSnake();

createFood();

while (!gameOver) {

drawMap();

moveSnake(getch());

if (checkCollision()) {

gameOver = 1;

}

}

freeSnake();

return 0;

}

void initSnake() {

SnakeNode *newHead = (SnakeNode *)malloc(sizeof(SnakeNode));

newHead->x = WIDTH / 2;

newHead->y = HEIGHT / 2;

newHead->next = NULL;

snakeHead = newHead;

}

void createFood() {

foodX = rand() % WIDTH;

foodY = rand() % HEIGHT;

}

void drawMap() {

for (int y = 0; y < HEIGHT; y++) {

for (int x = 0; x < WIDTH; x++) {

if (x == 0 || x == WIDTH - 1 || y == 0 || y == HEIGHT - 1) {

printf("");

} else if (x == foodX && y == foodY) {

printf("*");

} else if (snakeHead->x == x && snakeHead->y == y) {

printf("o");

} else {

printf(" ");

}

}

printf("\n");

}

}

void moveSnake(int direction) {

SnakeNode *temp = snakeHead;

switch (direction) {

case 1: // Up

snakeHead->y--;

break;

case 2: // Down

snakeHead->y++;

break;

case 3: // Left

snakeHead->x--;

break;

case 4: // Right

snakeHead->x++;

break;

}

addNodeToSnake(snakeHead->x, snakeHead->y);

if (snakeHead->x < 0) snakeHead->x = 0;

if (snakeHead->x >= WIDTH) snakeHead->x = WIDTH - 1;

if (snakeHead->y < 0) snakeHead->y = 0;

if (snakeHead->y >= HEIGHT) snakeHead->y = HEIGHT - 1;

}

int checkCollision() {

SnakeNode *temp = snakeHead;

while (temp != NULL) {

if (temp->x == foodX && temp->y == foodY) {

foodX = rand() % WIDTH;

foodY = rand() % HEIGHT;

score += 10;

return 0;

}

temp = temp->next;

}

return 1;

}

void addNodeToSnake(int x, int y) {

SnakeNode *newNode = (SnakeNode *)malloc(sizeof(SnakeNode));

newNode->x = x;

newNode->y = y;

newNode->next = snakeHead;

snakeHead = newNode;

}

void freeSnake() {

SnakeNode *temp = snakeHead;

while (temp != NULL) {

SnakeNode *next = temp->next;

free(temp);

temp = next;

}

snakeHead = NULL;

}

```

代码说明:

初始化:

`initSnake`函数初始化蛇的位置在屏幕中心。

2.