帮我编写一个贪吃蛇的c语言程序
时间: 2023-05-12 08:06:43 浏览: 75
好的,以下是一个简单的贪吃蛇C语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#define WIDTH 20
#define HEIGHT 20
int snake[WIDTH * HEIGHT][2];
int food[2];
int length = 3;
int direction = 0; // 0: up, 1: right, 2: down, 3: left
void init() {
srand(time(NULL));
snake[0][0] = WIDTH / 2;
snake[0][1] = HEIGHT / 2;
for (int i = 1; i < length; i++) {
snake[i][0] = snake[i - 1][0];
snake[i][1] = snake[i - 1][1] + 1;
}
food[0] = rand() % WIDTH;
food[1] = rand() % HEIGHT;
}
void draw() {
system("cls");
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
if (x == snake[0][0] && y == snake[0][1]) {
printf("O");
} else if (x == food[0] && y == food[1]) {
printf("*");
} else {
int flag = 0;
for (int i = 1; i < length; i++) {
if (x == snake[i][0] && y == snake[i][1]) {
printf("o");
flag = 1;
break;
}
}
if (!flag) {
printf(" ");
}
}
}
printf("\n");
}
}
void update() {
int dx = 0, dy = 0;
switch (direction) {
case 0: dy = -1; break;
case 1: dx = 1; break;
case 2: dy = 1; break;
case 3: dx = -1; break;
}
int nx = snake[0][0] + dx;
int ny = snake[0][1] + dy;
if (nx < 0 || nx >= WIDTH || ny < 0 || ny >= HEIGHT) {
printf("Game over!\n");
exit(0);
}
if (nx == food[0] && ny == food[1]) {
length++;
food[0] = rand() % WIDTH;
food[1] = rand() % HEIGHT;
}
for (int i = length - 1; i > 0; i--) {
snake[i][0] = snake[i - 1][0];
snake[i][1] = snake[i - 1][1];
}
snake[0][0] = nx;
snake[0][1] = ny;
for (int i = 1; i < length; i++) {
if (snake[i][0] == nx && snake[i][1] == ny) {
printf("Game over!\n");
exit(0);
}
}
}
int main() {
init();
while (1) {
draw();
update();
if (_kbhit()) {
char ch = _getch();
if (ch == 'w' && direction != 2) {
direction = 0;
} else if (ch == 'd' && direction != 3) {
direction = 1;
} else if (ch == 's' && direction != 0) {
direction = 2;
} else if (ch == 'a' && direction != 1) {
direction = 3;
}
}
Sleep(100);
}
return 0;
}
```
这个程序使用了 Windows 系统的控制台 API,所以在 Linux 或 Mac 上可能无法编译运行。如果你想在 Linux 或 Mac 上运行,可以使用 ncurses 库来实现控制台界面。