贪吃蛇代码
typedef struct SNAKE //蛇身的一个节点{
int x;
int y;
struct SNAKE *next;
}snake;
snake *head, *food;//蛇头指针,食物指针
snake *q;//遍历蛇的时候用到的指针
void Pos(int x,int y)//设置光标位置
{
COORD pos;
HANDLE hOutput;
pos.X=x;
pos.Y=y;
hOutput=GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hOutput,pos);
}
void initsnake()//初始化蛇身
{
snake *tail;
int i;
tail=(snake*)malloc(sizeof(snake));//从蛇尾开始,头插法,以x,y设定开始的位置//
tail->x=24;
tail->y=5;
tail->next=NULL;
for(i=1;i<=4;i++)
{
head=(snake*)malloc(sizeof(snake));
head->next=tail;
head->x=24+2*i;
head->y=5;
tail=head;
}
while(tail!=NULL)//从头到为,输出蛇身
{
Pos(tail->x,tail->y);
printf("■");
tail=tail->next;
}
}
void createfood()//随机出现食物
{
snake *food_1;
srand((unsigned)time(NULL));
food_1=(snake*)malloc(sizeof(snake));
while((food_1->x%2)!=0) //保证其为偶数,使得食物能与蛇头对其
{
food_1->x=rand()%52+2;
}
food_1->y=rand()%24+1;
q=head;
while(q->next==NULL)
{
if(q->x==food_1->x && q->y==food_1->y) //判断蛇身是否与食物重合
{
free(food_1);
createfood();
}
q=q->next;
}
Pos(food_1->x,food_1->y);
food=food_1;
printf("■");
}