linux c语言写一个贪吃蛇游戏
时间: 2023-08-02 18:18:59 浏览: 127
好的,下面是一个简单的 Linux C 语言贪吃蛇游戏的代码,希望能够帮到您:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <termios.h>
#include <unistd.h>
#define WIDTH 80
#define HEIGHT 25
int map[WIDTH][HEIGHT] = {0}; // 地图
int head_x, head_y; // 蛇头坐标
int tail_x, tail_y; // 蛇尾坐标
int snake_len = 3; // 蛇的长度
int food_x, food_y; // 食物坐标
int score = 0; // 得分
void init_map() // 初始化地图
{
for (int i = 0; i < WIDTH; i++) {
map[i][0] = map[i][HEIGHT-1] = 1;
}
for (int i = 0; i < HEIGHT; i++) {
map[0][i] = map[WIDTH-1][i] = 1;
}
}
void init_snake() // 初始化蛇
{
head_x = WIDTH / 2;
head_y = HEIGHT / 2;
tail_x = head_x - 2;
tail_y = head_y;
for (int i = tail_x + 1; i <= head_x; i++) {
map[i][head_y] = snake_len--;
}
}
void show_map() // 显示地图
{
system("clear");
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (map[j][i] == 0) {
printf(" ");
} else if (map[j][i] == -1) {
printf("*");
} else {
printf("#");
}
}
printf("\n");
}
printf("score: %d\n", score);
}
void generate_food() // 生成食物
{
srand(time(NULL));
do {
food_x = rand() % (WIDTH - 2) + 1;
food_y = rand() % (HEIGHT - 2) + 1;
} while (map[food_x][food_y] != 0);
map[food_x][food_y] = -1;
}
int get_direction() // 获取方向
{
struct termios oldt, newt;
int ch;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return ch;
}
void update_snake() // 更新蛇
{
int new_head_x = head_x, new_head_y = head_y;
switch (get_direction()) {
case 'w': new_head_y--; break;
case 's': new_head_y++; break;
case 'a': new_head_x--; break;
case 'd': new_head_x++; break;
default: break;
}
if (map[new_head_x][new_head_y] != 0) {
printf("Game over!\n");
exit(0);
}
if (new_head_x == food_x && new_head_y == food_y) {
snake_len++;
score++;
generate_food();
} else {
map[tail_x][tail_y] = 0;
tail_x += map[head_x][head_y] / abs(map[head_x][head_y]);
tail_y += map[head_x][head_y] % abs(map[head_x][head_y]);
}
head_x = new_head_x;
head_y = new_head_y;
map[head_x][head_y] = snake_len;
}
int main()
{
init_map();
init_snake();
generate_food();
while (1) {
show_map();
update_snake();
usleep(100000);
}
return 0;
}
```
这个贪吃蛇游戏是基于 Linux 系统的终端实现的。您可以将代码复制到 Linux 终端中,使用 `gcc` 命令进行编译运行。
阅读全文