帮我用c语言写个贪吃蛇的小游戏
时间: 2023-05-20 19:01:38 浏览: 112
tanchishe.rar_c 小游戏代码_c语言 小游戏_c语言 贪吃蛇_c语言小游戏_贪吃蛇
好的,以下是一个简单的贪吃蛇小游戏的 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 = 0;
int score = 0;
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");
}
srand(time(NULL));
food[0] = rand() % (WIDTH - 2) + 1;
food[1] = rand() % (HEIGHT - 2) + 1;
printf("Score: %d\n", score);
}
void draw() {
int i, j;
for (i = 0; i < WIDTH; i++) {
for (j = 0; j < HEIGHT; j++) {
int flag = 0;
int k;
for (k = 0; k < length; k++) {
if (snake[k][0] == i && snake[k][1] == j) {
printf("O");
flag = 1;
break;
}
}
if (!flag) {
if (i == 0 || i == WIDTH - 1 || j == 0 || j == HEIGHT - 1) {
printf("#");
} else if (i == food[0] && j == food[1]) {
printf("*");
} else {
printf(" ");
}
}
}
printf("\n");
}
printf("Score: %d\n", score);
}
void update() {
int i;
for (i = length - 1; i > 0; i--) {
snake[i][0] = snake[i - 1][0];
snake[i][1] = snake[i - 1][1];
}
switch (direction) {
case 0:
snake[0][1]--;
break;
case 1:
snake[0][0]++;
break;
case 2:
snake[0][1]++;
break;
case 3:
snake[0][0]--;
break;
}
if (snake[0][0] == food[0] && snake[0][1] == food[1]) {
length++;
score += 10;
food[0] = rand() % (WIDTH - 2) + 1;
food[1] = rand() % (HEIGHT - 2) + 1;
}
if (snake[0][0] == 0 || snake[0][0] == WIDTH - 1 || snake[0][1] == 0 || snake[0][1] == HEIGHT - 1) {
printf("Game over!\n");
exit(0);
}
for (i = 1; i < length; i++) {
if (snake[0][0] == snake[i][0] && snake[0][1] == snake[i][1]) {
printf("Game over!\n");
exit(0);
}
}
}
int main() {
int i;
for (i = 0; i < length; i++) {
snake[i][0] = WIDTH / 2 + i;
snake[i][1] = HEIGHT / 2;
}
init();
while (1) {
if (_kbhit()) {
char ch = _getch();
if (ch == 'w' || ch == 'W') {
if (direction != 2) {
direction = 0;
}
} else if (ch == 'd' || ch == 'D') {
if (direction != 3) {
direction = 1;
}
} else if (ch == 's' || ch == 'S') {
if (direction != 0) {
direction = 2;
}
} else if (ch == 'a' || ch == 'A') {
if (direction != 1) {
direction = 3;
}
}
}
update();
system("cls");
draw();
Sleep(100);
}
return 0;
}
```
这个代码使用了 Windows 系统的 conio.h 库,所以在 Linux 等系统上可能无法编译运行。如果需要在 Linux 上运行,可以使用 ncurses 库来实现类似的效果。
阅读全文