用c语言实现贪吃蛇游戏代码
时间: 2023-06-06 14:05:43 浏览: 313
很高兴回答你的问题。以下是一个简单的贪吃蛇游戏的C语言代码实现:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define MAX 50
int main()
{
int i, j, x, y, k, len, score;
char c = ' ', map[MAX][MAX];
int fx, fy; //食物的坐标
int snake[MAX * MAX] = {0, 1, 2, 3}, head = 3, tail = 0;
len = 4;
score = 0;
//生成初始地图
for(i = 0; i < MAX; i++)
{
for(j = 0; j < MAX; j++)
{
if(i == 0 || i == MAX - 1 || j == 0 || j == MAX - 1)
map[i][j] = '#';
else
map[i][j] = ' ';
}
}
//生成蛇和食物
for(k = 1; k <= len; k++)
map[1][k] = '*';
srand((unsigned)time(NULL));
fx = 1 + rand() % (MAX - 2);
fy = 1 + rand() % (MAX - 2);
map[fx][fy] = '@';
while(c != 'q')
{
//显示地图
system("cls"); //清屏
printf("贪吃蛇游戏,当前得分:%d\n", score);
for(i = 0; i < MAX; i++)
{
for(j = 0; j < MAX; j++)
{
printf("%c", map[i][j]);
}
printf("\n");
}
//接收用户输入
Sleep(200); //延时200毫秒,控制蛇的移动速度
if(_kbhit())
{
c = _getch();
switch(c)
{
case 'w': if(snake[head] - snake[head - 1] != MAX) snake[head + 1] = snake[head] - MAX; break;
case 's': if(snake[head] - snake[head - 1] != -MAX) snake[head + 1] = snake[head] + MAX; break;
case 'a': if(snake[head] - snake[head - 1] != 1) snake[head + 1] = snake[head] - 1; break;
case 'd': if(snake[head] - snake[head - 1] != -1) snake[head + 1] = snake[head] + 1; break;
}
}
//移动蛇
tail++;
map[snake[tail] / MAX][snake[tail] % MAX] = ' '; //清除蛇尾
for(i = tail; i <= head; i++)
{
snake[i - tail] = snake[i];
}
head -= tail;
tail = 0;
map[snake[head] / MAX][snake[head] % MAX] = '*'; //添加蛇头
//判断是否吃到食物
if(snake[head] / MAX == fx && snake[head] % MAX == fy)
{
len++;
score += 100;
fx = 1 + rand() % (MAX - 2);
fy = 1 + rand() % (MAX - 2);
map[fx][fy] = '@';
}
//判断是否死亡
if(map[snake[head] / MAX][snake[head] % MAX + 1] == '*' ||
map[snake[head] / MAX][snake[head] % MAX - 1] == '*' ||
map[snake[head] / MAX + 1][snake[head] % MAX] == '*' ||
map[snake[head] / MAX - 1][snake[head] % MAX] == '*')
{
printf("\nGAME OVER!\n");
break;
}
}
return 0;
}
```
这是一个比较简单的实现,可能还存在一些小问题,需要根据实际情况进行调整。希望能够帮到你。
阅读全文