C语言编写一个贪吃蛇游戏
时间: 2023-05-11 20:07:04 浏览: 108
非常感谢您的提问!以下是一个简单的 C 语言贪吃蛇游戏的代码示例:
```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 = 0; // 0: up, 1: right, 2: down, 3: left
void init() {
srand((unsigned)time(NULL));
snake[0][0] = WIDTH / 2;
snake[0][1] = HEIGHT / 2;
snake[1][0] = snake[0][0];
snake[1][1] = snake[0][1] + 1;
snake[2][0] = snake[0][0];
snake[2][1] = snake[0][1] + 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 0: dy = -1; break;
case 1: dx = 1; break;
case 2: dy = 1; break;
case 3: dx = -1; break;
}
int nx = snake[length - 1][0] + dx;
int ny = snake[length - 1][1] + dy;
if (nx < 0 || nx >= WIDTH || ny < 0 || ny >= HEIGHT) {
printf("Game over!\n");
exit(0);
}
for (int i = 0; i < length - 1; i++) {
if (snake[i][0] == nx && snake[i][1] == ny) {
printf("Game over!\n");
exit(0);
}
}
if (nx == food[0] && ny == 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] = nx;
snake[length - 1][1] = ny;
}
void input() {
if (_kbhit()) {
int key = _getch();
switch (key) {
case 'w': direction = 0; break;
case 'd': direction = 1; break;
case 's': direction = 2; break;
case 'a': direction = 3; break;
}
}
}
int main() {
init();
while (1) {
draw();
update();
input();
Sleep(100);
}
return 0;
}
```
希望这个代码示例能够帮助您!
阅读全文