使用C语言写一个贪吃蛇游戏
时间: 2023-09-11 21:10:37 浏览: 101
抱歉,作为AI语言模型,我无法编写完整的游戏程序。但我可以提供一些贪吃蛇游戏的思路和一些基本代码实现。
思路:
1. 定义贪吃蛇的数据结构(如坐标、长度、方向等);
2. 定义游戏地图的大小和边界;
3. 定义食物的生成和吃掉的逻辑;
4. 定义蛇的移动逻辑(如根据方向移动、判断是否撞墙或撞到自己、是否吃掉食物等);
5. 定义游戏结束的判断逻辑;
6. 实现游戏循环(包括输入处理、游戏逻辑处理、界面更新等)。
代码实现:
以下是一个简单的贪吃蛇游戏示例代码,仅供参考。
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#define WIDTH 20 // 地图宽度
#define HEIGHT 20 // 地图高度
typedef struct {
int x;
int y;
} Point;
typedef enum {
UP,
DOWN,
LEFT,
RIGHT
} Direction;
struct Snake {
Point head;
Point body[WIDTH * HEIGHT];
int len;
Direction dir;
} snake;
Point food;
void initGame() {
// 初始化贪吃蛇
snake.head.x = WIDTH / 2;
snake.head.y = HEIGHT / 2;
snake.len = 1;
snake.body[0] = snake.head;
snake.dir = RIGHT;
// 初始化食物
srand((unsigned int)time(NULL));
food.x = rand() % WIDTH;
food.y = rand() % HEIGHT;
}
void drawMap() {
// 绘制地图
system("cls"); // 清屏
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (i == 0 || i == HEIGHT - 1 || j == 0 || j == WIDTH - 1)
printf("#"); // 边界
else if (i == food.y && j == food.x)
printf("*"); // 食物
else {
int flag = 0;
for (int k = 0; k < snake.len; k++) {
if (snake.body[k].x == j && snake.body[k].y == i) {
printf("O"); // 蛇身
flag = 1;
break;
}
}
if (!flag)
printf(" "); // 空格
}
}
printf("\n");
}
}
void moveSnake() {
// 移动贪吃蛇
for (int i = snake.len - 1; i > 0; i--)
snake.body[i] = snake.body[i - 1];
snake.body[0] = snake.head;
switch (snake.dir) {
case UP:
snake.head.y--;
break;
case DOWN:
snake.head.y++;
break;
case LEFT:
snake.head.x--;
break;
case RIGHT:
snake.head.x++;
break;
}
}
void checkCollision() {
// 检查是否撞墙或撞到自己
if (snake.head.x <= 0 || snake.head.x >= WIDTH - 1 ||
snake.head.y <= 0 || snake.head.y >= HEIGHT - 1) {
printf("Game Over! Press any key to continue...\n");
_getch();
exit(0);
}
for (int i = 1; i < snake.len; i++) {
if (snake.head.x == snake.body[i].x && snake.head.y == snake.body[i].y) {
printf("Game Over! Press any key to continue...\n");
_getch();
exit(0);
}
}
}
void checkFood() {
// 检查是否吃到食物
if (snake.head.x == food.x && snake.head.y == food.y) {
snake.len++;
snake.body[snake.len - 1] = snake.body[snake.len - 2];
switch (snake.dir) {
case UP:
snake.body[snake.len - 1].y++;
break;
case DOWN:
snake.body[snake.len - 1].y--;
break;
case LEFT:
snake.body[snake.len - 1].x++;
break;
case RIGHT:
snake.body[snake.len - 1].x--;
break;
}
food.x = rand() % WIDTH;
food.y = rand() % HEIGHT;
}
}
void update() {
// 更新游戏状态
moveSnake();
checkCollision();
checkFood();
}
void input() {
// 处理输入
if (_kbhit()) {
switch (_getch()) {
case 'w':
if (snake.dir != DOWN)
snake.dir = UP;
break;
case 's':
if (snake.dir != UP)
snake.dir = DOWN;
break;
case 'a':
if (snake.dir != RIGHT)
snake.dir = LEFT;
break;
case 'd':
if (snake.dir != LEFT)
snake.dir = RIGHT;
break;
}
}
}
int main() {
initGame();
while (1) {
drawMap();
input();
update();
}
return 0;
}
```
阅读全文