Linux c实现贪吃蛇
时间: 2024-02-12 13:00:01 浏览: 250
以下是Linux C语言实现贪吃蛇的基本步骤:
1. 定义蛇的结构体,包括蛇头、蛇身和蛇尾等信息。
2. 初始化蛇的位置和长度。
3. 定义食物的结构体,包括食物的位置和分值等信息。
4. 随机生成食物的位置。
5. 定义蛇的移动函数,包括蛇头的移动、蛇身的移动和蛇尾的删除等操作。
6. 定义蛇的死亡判断函数,包括蛇头是否撞墙和蛇头是否撞到蛇身等情况。
7. 定义游戏主循环,包括监听用户输入、移动蛇、判断蛇是否死亡、更新分数和重新生成食物等操作。
8. 在游戏结束后,清理蛇和食物的数据。
以下是一个简单的Linux C语言实现贪吃蛇的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <termios.h>
#define ROW 20
#define COL 20
struct snake {
int row;
int col;
struct snake *next;
};
struct food {
int row;
int col;
int score;
};
struct snake *head = NULL;
struct food food;
void init_snake() {
struct snake *p1 = (struct snake *)malloc(sizeof(struct snake));
p1->row = 5;
p1->col = 5;
p1->next = NULL;
head = p1;
struct snake *p2 = (struct snake *)malloc(sizeof(struct snake));
p2->row = 5;
p2->col = 6;
p2->next = NULL;
p1->next = p2;
}
void init_food() {
srand(time(NULL));
food.row = rand() % ROW;
food.col = rand() % COL;
food.score = 10;
}
void draw() {
system("clear");
printf("score: %d\n", food.score);
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
if (i == food.row && j == food.col) {
printf("*");
} else {
struct snake *p = head;
int flag = 0;
while (p != NULL) {
if (p->row == i && p->col == j) {
printf("#");
flag = 1;
break;
}
p = p->next;
}
if (flag == 0) {
printf(" ");
}
}
}
printf("\n");
}
}
void add_snake_node(int row, int col) {
struct snake *p = (struct snake *)malloc(sizeof(struct snake));
p->row = row;
p->col = col;
p->next = head;
head = p;
}
void delete_snake_node() {
struct snake *p = head;
while (p->next->next != NULL) {
p = p->next;
}
free(p->next);
p->next = NULL;
}
void move_snake(int direction) {
int row = head->row;
int col = head->col;
switch (direction) {
case 1:
row--;
break;
case 2:
row++;
break;
case 3:
col--;
break;
case 4:
col++;
break;
default:
break;
}
add_snake_node(row, col);
if (row == food.row && col == food.col) {
food.score += 10;
init_food();
} else {
delete_snake_node();
}
}
int snake_die() {
if (head->row < 0 || head->row >= ROW || head->col < 0 || head->col >= COL) {
return 1;
}
struct snake *p = head->next;
while (p != NULL) {
if (p->row == head->row && p->col == head->col) {
return 1;
}
p = p->next;
}
return 0;
}
int getch() {
struct termios tm, tm_old;
int fd = STDIN_FILENO, c;
if (tcgetattr(fd, &tm) < 0) {
return -1;
}
tm_old = tm;
cfmakeraw(&tm);
if (tcsetattr(fd, TCSANOW, &tm) < 0) {
return -1;
}
c = getchar();
if (tcsetattr(fd, TCSANOW, &tm_old) < 0) {
return -1;
}
return c;
}
int main() {
init_snake();
init_food();
int direction = 2;
while (1) {
draw();
int c = getch();
if (c == 'w' && direction != 2) {
direction = 1;
} else if (c == 's' && direction != 1) {
direction = 2;
} else if (c == 'a' && direction != 4) {
direction = 3;
} else if (c == 'd' && direction != 3) {
direction = 4;
}
move_snake(direction);
if (snake_die()) {
printf("Game Over!\n");
break;
}
usleep(200000);
}
return 0;
}
```
阅读全文