用c语言编写一个贪吃蛇小游戏
时间: 2023-05-10 09:55:44 浏览: 47
好的,以下是一个简单的贪吃蛇小游戏的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 = 1; // 1: up, 2: right, 3: down, 4: left
void init() {
srand(time(NULL));
snake[0][0] = WIDTH/2;
snake[0][1] = HEIGHT/2;
snake[1][0] = WIDTH/2;
snake[1][1] = HEIGHT/2 + 1;
snake[2][0] = WIDTH/2;
snake[2][1] = HEIGHT/2 + 2;
food[0] = rand() % WIDTH;
food[1] = rand() % HEIGHT;
}
void draw() {
system("cls");
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (i == food[1] && j == food[0]) {
printf("F");
} else {
int flag = 0;
for (int k = 0; k < length; k++) {
if (snake[k][0] == j && snake[k][1] == i) {
printf("O");
flag = 1;
break;
}
}
if (!flag) {
printf(" ");
}
}
}
printf("\n");
}
}
void update() {
int dx = 0, dy = 0;
switch (direction) {
case 1:
dy = -1;
break;
case 2:
dx = 1;
break;
case 3:
dy = 1;
break;
case 4:
dx = -1;
break;
}
int new_x = snake[length-1][0] + dx;
int new_y = snake[length-1][1] + dy;
if (new_x < 0 || new_x >= WIDTH || new_y < 0 || new_y >= HEIGHT) {
printf("Game over!\n");
exit(0);
}
for (int i = 0; i < length-1; i++) {
if (snake[i][0] == new_x && snake[i][1] == new_y) {
printf("Game over!\n");
exit(0);
}
}
if (new_x == food[0] && new_y == food[1]) {
length++;
food[0] = rand() % WIDTH;
food[1] = rand() % HEIGHT;
}
for (int i = 0; i < length-1; i++) {
snake[i][0] = snake[i+1][0];
snake[i][1] = snake[i+1][1];
}
snake[length-1][0] = new_x;
snake[length-1][1] = new_y;
}
int main() {
init();
while (1) {
draw();
update();
if (_kbhit()) {
char c = _getch();
if (c == 'w' && direction != 3) {
direction = 1;
} else if (c == 'd' && direction != 4) {
direction = 2;
} else if (c == 's' && direction != 1) {
direction = 3;
} else if (c == 'a' && direction != 2) {
direction = 4;
}
}
Sleep(100);
}
return 0;
}
```
希望这个代码对你有帮助!