贪吃蛇c语言18行代码
时间: 2023-10-17 19:15:55 浏览: 102
以下是一个简单的贪吃蛇的 C 语言代码,共 18 行:
```c
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#define W 20
#define H 20
int x[W * H], y[W * H], len = 3, fx, fy, speed = 150, fx1, fy1, fx2, fy2, fx3, fy3, fx4, fy4, fx5, fy5;
char map[W][H];
void init() {
srand(time(NULL));
fx = rand() % (W - 2) + 1, fy = rand() % (H - 2) + 1;
fx1 = rand() % (W - 2) + 1, fy1 = rand() % (H - 2) + 1;
fx2 = rand() % (W - 2) + 1, fy2 = rand() % (H - 2) + 1;
fx3 = rand() % (W - 2) + 1, fy3 = rand() % (H - 2) + 1;
fx4 = rand() % (W - 2) + 1, fy4 = rand() % (H - 2) + 1;
fx5 = rand() % (W - 2) + 1, fy5 = rand() % (H - 2) + 1;
for(int i = 0; i < W; i++) {
for(int j = 0; j < H; j++) {
if(i == 0 || j == 0 || i == W - 1 || j == H - 1) map[i][j] = '#';
else map[i][j] = ' ';
}
}
for(int i = 0; i < len; i++) {
x[i] = W / 2 + i, y[i] = H / 2;
map[x[i]][y[i]] = '*';
}
map[fx][fy] = '$', map[fx1][fy1] = '$', map[fx2][fy2] = '$', map[fx3][fy3] = '$', map[fx4][fy4] = '$', map[fx5][fy5] = '$';
}
void draw() {
system("cls");
for(int i = 0; i < W; i++) {
for(int j = 0; j < H; j++) {
printf("%c", map[i][j]);
}
printf("\n");
}
}
void move(int dx, int dy) {
int nx = x[len - 1] + dx, ny = y[len - 1] + dy;
if(nx == fx && ny == fy) {
len++, fx = rand() % (W - 2) + 1, fy = rand() % (H - 2) + 1;
map[fx][fy] = '$';
speed -= 3;
}
if(nx == fx1 && ny == fy1) {
len++, fx1 = rand() % (W - 2) + 1, fy1 = rand() % (H - 2) + 1;
map[fx1][fy1] = '$';
speed -= 3;
}
if(nx == fx2 && ny == fy2) {
len++, fx2 = rand() % (W - 2) + 1, fy2 = rand() % (H - 2) + 1;
map[fx2][fy2] = '$';
speed -= 3;
}
if(nx == fx3 && ny == fy3) {
len++, fx3 = rand() % (W - 2) + 1, fy3 = rand() % (H - 2) + 1;
map[fx3][fy3] = '$';
speed -= 3;
}
if(nx == fx4 && ny == fy4) {
len++, fx4 = rand() % (W - 2) + 1, fy4 = rand() % (H - 2) + 1;
map[fx4][fy4] = '$';
speed -= 3;
}
if(nx == fx5 && ny == fy5) {
len++, fx5 = rand() % (W - 2) + 1, fy5 = rand() % (H - 2) + 1;
map[fx5][fy5] = '$';
speed -= 3;
}
if(map[nx][ny] == '*' || map[nx][ny] == '#') exit(0);
map[nx][ny] = '*';
x[len - 1] = nx, y[len - 1] = ny;
map[x[0]][y[0]] = ' ';
for(int i = 0; i < len - 1; i++) {
if(x[i] == nx && y[i] == ny) exit(0);
x[i] = x[i + 1], y[i] = y[i + 1];
map[x[i]][y[i]] = '*';
}
}
int main() {
init();
while(1) {
if(_kbhit()) {
int c = _getch();
if(c == 'a') move(0, -1);
if(c == 'd') move(0, 1);
if(c == 'w') move(-1, 0);
if(c == 's') move(1, 0);
}
else move(0, 0);
draw();
Sleep(speed);
}
return 0;
}
```
该代码使用了 Windows 下的 conio.h 库,因此只能在 Windows 系统下运行。如果需要在其他系统下运行,需要进行相应的修改。
阅读全文