帮我编写一个c语言贪吃蛇小游戏
时间: 2023-04-06 15:01:49 浏览: 101
好的,我可以帮您编写一个 C 语言贪吃蛇小游戏。以下是代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#define WIDTH 30
#define HEIGHT 20
int snake[WIDTH * HEIGHT][2];
int food[2];
int length = 3;
int direction = 1; // 1: right, 2: down, 3: left, 4: up
void init() {
int i, j;
for (i = 0; i < WIDTH; i++) {
for (j = 0; j < HEIGHT; j++) {
if (i == 0 || i == WIDTH - 1 || j == 0 || j == HEIGHT - 1) {
printf("#");
} else {
printf(" ");
}
}
printf("\n");
}
snake[0][0] = WIDTH / 2;
snake[0][1] = HEIGHT / 2;
snake[1][0] = snake[0][0] - 1;
snake[1][1] = snake[0][1];
snake[2][0] = snake[1][0] - 1;
snake[2][1] = snake[1][1];
food[0] = rand() % (WIDTH - 2) + 1;
food[1] = rand() % (HEIGHT - 2) + 1;
printf("@");
printf("\033[%d;%dH", food[1] + 1, food[0] + 1);
printf("*");
}
void update() {
int i;
int tail[2];
tail[0] = snake[length - 1][0];
tail[1] = snake[length - 1][1];
for (i = length - 1; i > 0; i--) {
snake[i][0] = snake[i - 1][0];
snake[i][1] = snake[i - 1][1];
}
switch (direction) {
case 1:
snake[0][0]++;
break;
case 2:
snake[0][1]++;
break;
case 3:
snake[0][0]--;
break;
case 4:
snake[0][1]--;
break;
}
if (snake[0][0] == food[0] && snake[0][1] == food[1]) {
length++;
food[0] = rand() % (WIDTH - 2) + 1;
food[1] = rand() % (HEIGHT - 2) + 1;
printf("\033[%d;%dH", food[1] + 1, food[0] + 1);
printf("*");
}
printf("\033[%d;%dH", snake[0][1] + 1, snake[0][0] + 1);
printf("@");
printf("\033[%d;%dH", tail[1] + 1, tail[0] + 1);
printf(" ");
}
int main() {
srand(time(NULL));
init();
while (1) {
if (_kbhit()) {
int c = _getch();
if (c == 224) {
c = _getch();
switch (c) {
case 72:
if (direction != 2) {
direction = 4;
}
break;
case 80:
if (direction != 4) {
direction = 2;
}
break;
case 75:
if (direction != 1) {
direction = 3;
}
break;
case 77:
if (direction != 3) {
direction = 1;
}
break;
}
}
}
update();
Sleep(100);
}
return 0;
}
```
希望这个代码可以帮助您实现一个简单的贪吃蛇小游戏。
阅读全文