发一个贪吃蛇C语言代码
时间: 2023-06-06 17:05:58 浏览: 105
好的,这是一个简单的贪吃蛇C语言代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <Windows.h>
#define WIDE 50
#define HEIGHT 20
int score = 0;
int x, y;
int fx, fy;
int map[WIDE][HEIGHT];
void init_map()
{
int i, j;
for(i = 0; i <= WIDE-1; i++)
{
for(j = 0; j <= HEIGHT-1; j++)
{
if(i == 0 || i == WIDE-1 || j == 0 || j == HEIGHT-1)
{
//设置边界
map[i][j] = -1;
}
else
{
//设置食物和蛇的初始位置
map[i][j] = 0;
}
}
}
//设置初始蛇身长度和位置
x = WIDE/2;
y = HEIGHT/2;
map[x][y] = 1;
map[x+1][y] = 2;
map[x+2][y] = 3;
//设置初始食物位置
fx = rand()%(WIDE-2)+1;
fy = rand()%(HEIGHT-2)+1;
map[fx][fy] = 4;
}
void display()
{
int i, j;
for(i = 0; i <= WIDE-1; i++)
{
for(j = 0; j <= HEIGHT-1; j++)
{
if(map[i][j] == -1)
{
printf("#");
}
else if(map[i][j] == 0)
{
printf(" ");
}
else if(map[i][j] > 0 && map[i][j] < 4)
{
printf("*");
}
else if(map[i][j] == 4)
{
printf("$");
}
}
printf("\n");
}
printf("score:%d \n", score);
}
void move()
{
int dir = getch();
switch(dir)
{
case 'w':
x--;
break;
case 's':
x++;
break;
case 'a':
y--;
break;
case 'd':
y++;
break;
}
//判断是否撞墙
if(map[x][y] == -1)
{
printf("Game over\n");
exit(0);
}
//判断是否吃到食物
if(map[x][y] == 4)
{
score++;
//重新设置食物位置
fx = rand()%(WIDE-2)+1;
fy = rand()%(HEIGHT-2)+1;
while(map[fx][fy] != 0)
{
fx = rand()%(WIDE-2)+1;
fy = rand()%(HEIGHT-2)+1;
}
map[fx][fy] = 4;
}
else
{
//没有吃到食物时,设置蛇的位置
int i, j, k;
k = map[x][y] + 1;
map[x][y] = 1;
for(i = 0; i <= WIDE-1; i++)
{
for(j = 0; j <= HEIGHT-1; j++)
{
if(map[i][j] == k)
{
map[i][j] = 0;
}
else if(map[i][j] < k && map[i][j] > 0)
{
map[i][j]++;
}
}
}
}
}
int main()
{
init_map();
while(1)
{
system("cls");
display();
move();
Sleep(100);
}
return 0;
}
```
阅读全文