帮我使用C语言编写一个贪吃蛇游戏
时间: 2023-05-20 21:05:33 浏览: 146
好的,我可以帮您使用C语言编写一个贪吃蛇游戏。以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#define WIDTH 20
#define HEIGHT 20
#define SNAKE_MAX_LENGTH 100
int snakeX[SNAKE_MAX_LENGTH], snakeY[SNAKE_MAX_LENGTH];
int snakeLength = 3;
int foodX, foodY;
int score = 0;
int direction = 0; // 0: up, 1: right, 2: down, 3: left
void initGame() {
// 初始化蛇的位置
snakeX[0] = WIDTH / 2;
snakeY[0] = HEIGHT / 2;
snakeX[1] = snakeX[0];
snakeY[1] = snakeY[0] + 1;
snakeX[2] = snakeX[0];
snakeY[2] = snakeY[0] + 2;
// 随机生成食物的位置
srand(time(NULL));
foodX = rand() % WIDTH;
foodY = rand() % HEIGHT;
}
void drawGame() {
system("cls"); // 清屏
// 画出地图
for (int i = 0; i < WIDTH + 2; i++) {
printf("#");
}
printf("\n");
for (int i = 0; i < HEIGHT; i++) {
printf("#");
for (int j = 0; j < WIDTH; j++) {
if (i == snakeY[0] && j == snakeX[0]) {
printf("O"); // 画出蛇头
} else if (i == foodY && j == foodX) {
printf("*"); // 画出食物
} else {
int isBody = 0;
for (int k = 1; k < snakeLength; k++) {
if (i == snakeY[k] && j == snakeX[k]) {
printf("o"); // 画出蛇身
isBody = 1;
break;
}
}
if (!isBody) {
printf(" ");
}
}
}
printf("#\n");
}
for (int i = 0; i < WIDTH + 2; i++) {
printf("#");
}
printf("\n");
// 显示得分
printf("Score: %d\n", score);
}
void updateGame() {
// 移动蛇
for (int i = snakeLength - 1; i > 0; i--) {
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
switch (direction) {
case 0: snakeY[0]--; break;
case 1: snakeX[0]++; break;
case 2: snakeY[0]++; break;
case 3: snakeX[0]--; break;
}
// 判断是否吃到食物
if (snakeX[0] == foodX && snakeY[0] == foodY) {
score++;
snakeLength++;
foodX = rand() % WIDTH;
foodY = rand() % HEIGHT;
}
// 判断是否撞墙或撞到自己
if (snakeX[0] < 0 || snakeX[0] >= WIDTH || snakeY[0] < 0 || snakeY[0] >= HEIGHT) {
printf("Game over!\n");
exit(0);
}
for (int i = 1; i < snakeLength; i++) {
if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
printf("Game over!\n");
exit(0);
}
}
}
int main() {
initGame();
while (1) {
drawGame();
updateGame();
// 处理输入
if (_kbhit()) {
int key = _getch();
if (key == 'w' && direction != 2) {
direction = 0;
} else if (key == 'd' && direction != 3) {
direction = 1;
} else if (key == 's' && direction != 0) {
direction = 2;
} else if (key == 'a' && direction != 1) {
direction = 3;
}
}
// 控制游戏速度
Sleep(100);
}
return 0;
}
```
希望这个示例代码能够帮到您!
阅读全文