c语言写一个贪吃蛇游戏
时间: 2023-12-25 15:04:13 浏览: 69
抱歉,作为AI语言模型,我无法编写完整的程序,但我可以为您提供一个基本的贪吃蛇游戏框架:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#define WIDTH 20
#define HEIGHT 20
#define INIT_LENGTH 3
typedef struct
{
int x;
int y;
} Point;
typedef struct
{
Point head;
Point tail;
int length;
Point body[WIDTH * HEIGHT];
} Snake;
typedef struct
{
int x;
int y;
} Food;
Snake snake;
Food food;
char map[WIDTH][HEIGHT];
void initSnake()
{
int i;
snake.length = INIT_LENGTH;
snake.head.x = WIDTH / 2;
snake.head.y = HEIGHT / 2;
snake.tail.x = snake.head.x - snake.length + 1;
snake.tail.y = snake.head.y;
for (i = 0; i < snake.length; ++i)
{
snake.body[i].x = snake.head.x - i;
snake.body[i].y = snake.head.y;
}
}
void initFood()
{
srand((unsigned int)time(NULL));
food.x = rand() % WIDTH;
food.y = rand() % HEIGHT;
}
void drawMap()
{
int i, j;
system("cls");
for (i = 0; i < WIDTH; ++i)
{
for (j = 0; j < HEIGHT; ++j)
{
if (i == food.x && j == food.y)
{
printf("F");
}
else if (i == snake.head.x && j == snake.head.y)
{
printf("H");
}
else if (i == snake.tail.x && j == snake.tail.y)
{
printf("T");
}
else
{
printf("%c", map[i][j]);
}
}
printf("\n");
}
}
void moveSnake(int dx, int dy)
{
int i;
Point newHead;
newHead.x = snake.head.x + dx;
newHead.y = snake.head.y + dy;
if (newHead.x < 0 || newHead.x >= WIDTH || newHead.y < 0 || newHead.y >= HEIGHT)
{
printf("Game over!\n");
exit(0);
}
for (i = 0; i < snake.length - 1; ++i)
{
if (newHead.x == snake.body[i].x && newHead.y == snake.body[i].y)
{
printf("Game over!\n");
exit(0);
}
}
if (newHead.x == food.x && newHead.y == food.y)
{
snake.head = newHead;
snake.body[snake.length] = snake.head;
snake.length++;
initFood();
}
else
{
map[snake.tail.x][snake.tail.y] = ' ';
for (i = 0; i < snake.length - 1; ++i)
{
snake.body[i] = snake.body[i + 1];
}
snake.body[snake.length - 1] = newHead;
snake.head = newHead;
snake.tail = snake.body[0];
}
}
int main()
{
int dx = 0, dy = 0;
char ch;
initSnake();
initFood();
while (1)
{
drawMap();
ch = getch();
switch (ch)
{
case 'w':
dx = -1;
dy = 0;
break;
case 's':
dx = 1;
dy = 0;
break;
case 'a':
dx = 0;
dy = -1;
break;
case 'd':
dx = 0;
dy = 1;
break;
default:
break;
}
moveSnake(dx, dy);
}
return 0;
}
```
这个程序实现了一个基本的贪吃蛇游戏,玩家可以通过键盘控制贪吃蛇的移动方向,并尽可能地吃掉食物。当贪吃蛇撞墙或撞到自己时,游戏结束。
阅读全文