贪吃蛇c语言程序代码
时间: 2023-06-22 19:26:14 浏览: 148
贪吃蛇C语言代码
5星 · 资源好评率100%
下面是一个简单的贪吃蛇C语言程序代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#define WIDTH 50
#define HEIGHT 20
int x, y, fruit_x, fruit_y, score;
int tail_x[100], tail_y[100], tail_len = 0;
char map[HEIGHT][WIDTH];
void init_map() {
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++)
map[i][j] = ' ';
}
for (int i = 0; i < tail_len; i++)
map[tail_y[i]][tail_x[i]] = 'o';
map[y][x] = 'O';
map[fruit_y][fruit_x] = 'X';
}
void draw_map() {
system("cls");
printf("Score: %d\n", score);
for (int i = 0; i <= WIDTH + 1; i++)
printf("-");
printf("\n");
for (int i = 0; i < HEIGHT; i++) {
printf("|");
for (int j = 0; j < WIDTH; j++)
printf("%c", map[i][j]);
printf("|\n");
}
for (int i = 0; i <= WIDTH + 1; i++)
printf("-");
printf("\n");
}
void move_snake() {
int prev_x = x, prev_y = y;
if (_kbhit()) {
switch (_getch()) {
case 'w':
y--;
break;
case 's':
y++;
break;
case 'a':
x--;
break;
case 'd':
x++;
break;
}
}
if (x == fruit_x && y == fruit_y) {
tail_len++;
score++;
fruit_x = rand() % WIDTH;
fruit_y = rand() % HEIGHT;
}
for (int i = 0; i < tail_len; i++) {
int tmp_x = tail_x[i], tmp_y = tail_y[i];
tail_x[i] = prev_x;
tail_y[i] = prev_y;
prev_x = tmp_x;
prev_y = tmp_y;
}
for (int i = 0; i < tail_len; i++) {
if (x == tail_x[i] && y == tail_y[i])
exit(1);
}
if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT)
exit(1);
}
int main() {
srand(time(NULL));
x = WIDTH / 2;
y = HEIGHT / 2;
fruit_x = rand() % WIDTH;
fruit_y = rand() % HEIGHT;
while (1) {
init_map();
draw_map();
move_snake();
}
return 0;
}
```
这个程序使用了Windows系统下的conio.h库来实现键盘输入的检测,因此只能在Windows系统下运行。如果需要在其他系统上运行,需要使用其他方式来检测键盘输入。
阅读全文